Input:
    public void whenPlayerMoves(PlayerMoveEvent event) {
        final Player player = event.getPlayer();
        if (onPad.contains(player)) return;
        if (player.hasPermission("telepads.use")) {
            Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
            if (!checkPad(block)) {
                return;
            }
            final Location loc = new Location(null, block.getX(), block.getY(), block.getZ());
            if (!plugin.telepads.containsKey(loc)) {
                return;
            }
            onPad.add(player);
            player.sendMessage(ChatColor.GRAY + plugin.wait_msg.replace("%time%", plugin.telepad_teleport_time + " Seconds"));
            plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                public void run() {
                    onPad.remove(player);
                    Block cBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
                    if (!checkPad(cBlock)) return;
                    if (!plugin.telepads.containsKey(loc)) return;
                    plugin.gotoPad(loc, player);
                }
            }, plugin.telepad_teleport_time * 20L);
        }
    }

Output:
    public void whenPlayerMoves(PlayerMoveEvent event) {
        final Player player = event.getPlayer();
        if (onPad.contains(player)) return;
        if (player.hasPermission("telepads.use")) {
            Block block = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
            if (!checkPad(block)) {
                return;
            }
            final Location loc = new Location(null, block.getX(), block.getY(), block.getZ());
            if (!plugin.telepads.containsKey(loc)) {
                return;
            }
            onPad.add(player);
            player.sendMessage(ChatColor.GRAY + plugin.wait_msg.replace("%time%", plugin.telepad_teleport_time + " Seconds"));
            plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
                public void run() {
                    onPad.remove(player);
                    Block cBlock = player.getLocation().getBlock().getRelative(BlockFace.DOWN);
                    if (!checkPad(cBlock)) return;
                    Location floc = new Location(null, cBlock.getX(), cBlock.getY(), cBlock.getZ());
                    if (!plugin.telepads.containsKey(floc)) return;
                    plugin.gotoPad(loc, player);
                }
            }, plugin.telepad_teleport_time * 20L);
        }
    }


Input:
    private List<String> findFactoryCandidates(BundleContext context) throws IOException {
        Bundle[] bundles = context.getBundles();
        List<String> factoryCandidates = new ArrayList<String>();
        for (Bundle bundle : bundles) {
            if (bundle.getSymbolicName().equals("system.bundle")) {
                continue;
            }
            Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
            if (urls == null) {
                continue;
            }
            while (urls.hasMoreElements()) {
                URL u = (URL) urls.nextElement();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(u.openStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.startsWith("#") && line.length() > 0) {
                        factoryCandidates.add(line);
                    }
                }
                reader.close();
            }
        }
        factoryCandidates.add("com.sun.script.javascript.RhinoScriptEngineFactory");
        return factoryCandidates;
    }

Output:
    private List<String> findFactoryCandidates(BundleContext context) throws IOException {
        Bundle[] bundles = context.getBundles();
        List<String> factoryCandidates = new ArrayList<String>();
        for (Bundle bundle : bundles) {
            if (bundle.getSymbolicName().equals("system.bundle")) {
                continue;
            }
            Enumeration urls = bundle.findEntries("META-INF/services", "javax.script.ScriptEngineFactory", false);
            if (urls == null) {
                continue;
            }
            while (urls.hasMoreElements()) {
                URL u = (URL) urls.nextElement();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(u.openStream(), "UTF-8"));
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (!line.startsWith("#") && line.length() > 0) {
                        factoryCandidates.add(line);
                    }
                }
                reader.close();
            }
        }
        factoryCandidates.add("com.sun.script.javascript.RhinoScriptEngineFactory");
        return factoryCandidates;
    }


Input:
	public JobStatus run() {
		UserPreferences userPrefs = new UserPreferences();
		SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
		UpsertResult result = null;
		JobStatus runStatus = JobStatus.SUCCESS;
		JobStatus validationStatus = validate(connectionInfo);
		if(validationStatus.isError()) {
			runStatus = validationStatus;
		} else {
			final Soda2Producer producer = Soda2Producer.newProducer(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken());
			final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken());
			File fileToPublishFile = new File(fileToPublish);
			File deleteRowsFile = null;
			if(!fileRowsToDelete.equals(DELETE_ZERO_ROWS)) {
				deleteRowsFile = new File(fileRowsToDelete);
			}
			String errorMessage = "";
			boolean noPublishExceptions = false;
			try {
				if(publishMethod.equals(PublishMethod.upsert)) {
                    if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) {
                        result = IntegrationUtility.upsertInChunks(
                                NUM_ROWS_PER_CHUNK, producer, importer, datasetID, deleteRowsFile, fileToPublishFile);
                    } else {
					    result = IntegrationUtility.upsert(producer, importer, datasetID, deleteRowsFile, fileToPublishFile);
                    }
                    noPublishExceptions = true;
				}
				else if(publishMethod.equals(PublishMethod.append)) {
                    if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) {
                        result = IntegrationUtility.appendInChunks(
                                NUM_ROWS_PER_CHUNK, producer, datasetID, fileToPublishFile);
                    } else {
                        result = IntegrationUtility.append(producer, datasetID, fileToPublishFile);
                    }
                    noPublishExceptions = true;
				}
				else if(publishMethod.equals(PublishMethod.replace)) {
					result = IntegrationUtility.replaceNew(producer, datasetID, fileToPublishFile);
					noPublishExceptions = true;
				} else {
					errorMessage = JobStatus.INVALID_PUBLISH_METHOD.toString();
				}
			}
			catch (IOException ioException) {
				errorMessage = ioException.getMessage();
			}
			catch (SodaError sodaError) {
				errorMessage = sodaError.getMessage();
			}
			catch (InterruptedException intrruptException) {
				errorMessage = intrruptException.getMessage();
			}
			catch (Exception other) {
				errorMessage = other.toString() + ": " + other.getMessage();
			}
			finally {
				if(noPublishExceptions) {
					if(result != null) {
						if(result.errorCount() > 0) {
							for (UpsertError upsertErr : result.getErrors()) {
								errorMessage += upsertErr.getError() + " (line "
										+ (upsertErr.getIndex() + 1) + " of file) \n";
							}
							runStatus = JobStatus.PUBLISH_ERROR;
							runStatus.setMessage(errorMessage);
						}
					} else {
						runStatus = JobStatus.SUCCESS;
					}
				} else {
					runStatus = JobStatus.PUBLISH_ERROR;
					runStatus.setMessage(errorMessage);
				}
			}
		}
		String adminEmail = userPrefs.getAdminEmail();
		String logDatasetID = userPrefs.getLogDatasetID();
		JobStatus logStatus = JobStatus.SUCCESS;
		if(!logDatasetID.equals("")) {
			logStatus = IntegrationUtility.addLogEntry(logDatasetID, connectionInfo, this, runStatus, result);
		}
		if(userPrefs.emailUponError() && !adminEmail.equals("")) {
			String errorEmailMessage = "";
			String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID;
			if(runStatus.isError()) {
				errorEmailMessage += "There was an error updating a dataset.\n"
						+ "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID()
						+ "\nFile to be published: " + fileToPublish
						+ "\nPublish method: " + publishMethod
						+ "\nJob File: " + pathToSavedJobFile
						+ "\nError message: " + runStatus.getMessage()
						+ "\nLog dataset: " + urlToLogDataset + "\n\n";
			}
			if(logStatus.isError()) {
				errorEmailMessage += "There was an error updating the log dataset: "
						+ urlToLogDataset + "\n"
						+ "Error message: " + logStatus.getMessage() + "\n\n";
			}
			if(runStatus.isError() || logStatus.isError()) {
				try {
					SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage);
				} catch (Exception e) {
					System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage());
				}
			}
		}
		return runStatus;
	}

Output:
	public JobStatus run() {
		UserPreferences userPrefs = new UserPreferences();
		SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
		UpsertResult result = null;
		JobStatus runStatus = JobStatus.SUCCESS;
		JobStatus validationStatus = validate(connectionInfo);
		if(validationStatus.isError()) {
			runStatus = validationStatus;
		} else {
			final Soda2Producer producer = Soda2Producer.newProducer(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken());
			final SodaImporter importer = SodaImporter.newImporter(connectionInfo.getUrl(), connectionInfo.getUser(), connectionInfo.getPassword(), connectionInfo.getToken());
			File fileToPublishFile = new File(fileToPublish);
			File deleteRowsFile = null;
			if(!fileRowsToDelete.equals(DELETE_ZERO_ROWS)) {
				deleteRowsFile = new File(fileRowsToDelete);
			}
			String errorMessage = "";
			boolean noPublishExceptions = false;
			try {
				if(publishMethod.equals(PublishMethod.upsert)) {
                    if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) {
                        result = IntegrationUtility.upsertInChunks(
                                NUM_ROWS_PER_CHUNK, producer, importer, datasetID, deleteRowsFile, fileToPublishFile);
                    } else {
					    result = IntegrationUtility.upsert(producer, importer, datasetID, deleteRowsFile, fileToPublishFile);
                    }
                    noPublishExceptions = true;
				}
				else if(publishMethod.equals(PublishMethod.append)) {
                    if(fileToPublishFile.length() > FILESIZE_CHUNK_CUTOFF_BYTES) {
                        result = IntegrationUtility.appendInChunks(
                                NUM_ROWS_PER_CHUNK, producer, datasetID, fileToPublishFile);
                    } else {
                        result = IntegrationUtility.append(producer, datasetID, fileToPublishFile);
                    }
                    noPublishExceptions = true;
				}
				else if(publishMethod.equals(PublishMethod.replace)) {
					result = IntegrationUtility.replaceNew(producer, datasetID, fileToPublishFile);
					noPublishExceptions = true;
				} else {
					errorMessage = JobStatus.INVALID_PUBLISH_METHOD.toString();
				}
			}
			catch (IOException ioException) {
				errorMessage = ioException.getMessage();
			}
			catch (SodaError sodaError) {
                errorMessage = sodaError.getMessage();
			}
			catch (InterruptedException intrruptException) {
				errorMessage = intrruptException.getMessage();
			}
			catch (Exception other) {
				errorMessage = other.toString() + ": " + other.getMessage();
			}
			finally {
				if(noPublishExceptions) {
					if(result != null) {
                        if(result.errorCount() > 0) {
							for (UpsertError upsertErr : result.getErrors()) {
								errorMessage += upsertErr.getError() + " (line "
										+ (upsertErr.getIndex() + 1) + " of file) \n";
							}
							runStatus = JobStatus.PUBLISH_ERROR;
							runStatus.setMessage(errorMessage);
						} else {
                        }
					} else {
						runStatus = JobStatus.SUCCESS;
					}
				} else {
					runStatus = JobStatus.PUBLISH_ERROR;
					runStatus.setMessage(errorMessage);
				}
			}
		}
		String adminEmail = userPrefs.getAdminEmail();
		String logDatasetID = userPrefs.getLogDatasetID();
		JobStatus logStatus = JobStatus.SUCCESS;
		if(!logDatasetID.equals("")) {
			logStatus = IntegrationUtility.addLogEntry(logDatasetID, connectionInfo, this, runStatus, result);
		}
		if(userPrefs.emailUponError() && !adminEmail.equals("")) {
			String errorEmailMessage = "";
			String urlToLogDataset = connectionInfo.getUrl() + "/d/" + logDatasetID;
			if(runStatus.isError()) {
				errorEmailMessage += "There was an error updating a dataset.\n"
						+ "\nDataset: " + connectionInfo.getUrl() + "/d/" + getDatasetID()
						+ "\nFile to be published: " + fileToPublish
						+ "\nPublish method: " + publishMethod
						+ "\nJob File: " + pathToSavedJobFile
						+ "\nError message: " + runStatus.getMessage()
						+ "\nLog dataset: " + urlToLogDataset + "\n\n";
			}
			if(logStatus.isError()) {
				errorEmailMessage += "There was an error updating the log dataset: "
						+ urlToLogDataset + "\n"
						+ "Error message: " + logStatus.getMessage() + "\n\n";
			}
			if(runStatus.isError() || logStatus.isError()) {
				try {
					SMTPMailer.send(adminEmail, "Socrata DataSync Error", errorEmailMessage);
				} catch (Exception e) {
					System.out.println("Error sending email to: " + adminEmail + "\n" + e.getMessage());
				}
			}
		}
		return runStatus;
	}


Input:
  public void enhance(GenClass genClass,
		      JMethod jMethod,
		      JAnnotation jAnn)
  {
    TransactionAttributeType type;
    type = (TransactionAttributeType) jAnn.get("value");
    BaseMethod genMethod = genClass.createMethod(jMethod);
    CallChain call = genMethod.getCall();
    switch (type) {
    case MANDATORY:
      call = new MandatoryCallChain(call);
      break;
    case REQUIRED:
      call = new RequiredCallChain(call);
      break;
    case REQUIRESNEW:
      call = new RequiresNewCallChain(call);
      break;
    case NEVER:
      call = new NeverCallChain(call);
      break;
    case SUPPORTS:
      call = new SupportsCallChain(call);
      break;
    case NOTSUPPORTED:
      call = new SuspendCallChain(call);
      break;
    default:
      break;
    }
    genMethod.setCall(call);
  }

Output:
  public void enhance(GenClass genClass,
		      JMethod jMethod,
		      JAnnotation jAnn)
  {
    TransactionAttributeType type;
    type = (TransactionAttributeType) jAnn.get("value");
    BaseMethod genMethod = genClass.createMethod(jMethod);
    CallChain call = genMethod.getCall();
    switch (type) {
    case MANDATORY:
      call = new MandatoryCallChain(call);
      break;
    case REQUIRED:
      call = new RequiredCallChain(call);
      break;
    case REQUIRES_NEW:
      call = new RequiresNewCallChain(call);
      break;
    case NEVER:
      call = new NeverCallChain(call);
      break;
    case SUPPORTS:
      call = new SupportsCallChain(call);
      break;
    case NOT_SUPPORTED:
      call = new SuspendCallChain(call);
      break;
    default:
      break;
    }
    genMethod.setCall(call);
  }


Input:
	protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
		boolean b = super.processKeyBinding(ks, e, condition, pressed);
		if (!b) {
			AbstractAction actionForKey = _controller.getActionForKeyStroke(ks);
			if (actionForKey != null) {
				Object eventSource = e.getSource();
				if (!(eventSource instanceof FlexoActionSource) && eventSource instanceof Component) {
					eventSource = SwingUtilities.getAncestorOfClass(FlexoActionSource.class, (Component) eventSource);
				}
				actionForKey.actionPerformed(new ActionEvent(eventSource != null ? eventSource : e.getSource(), e.getID(), KEY_PRESSED));
				b = true;
			}
		}
		return b;
	}

Output:
	protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) {
		boolean b = super.processKeyBinding(ks, e, condition, pressed);
		if (!b && ks!=null) {
			AbstractAction actionForKey = _controller.getActionForKeyStroke(ks);
			if (actionForKey != null) {
				Object eventSource = e.getSource();
				if (!(eventSource instanceof FlexoActionSource) && eventSource instanceof Component) {
					eventSource = SwingUtilities.getAncestorOfClass(FlexoActionSource.class, (Component) eventSource);
				}
				actionForKey.actionPerformed(new ActionEvent(eventSource != null ? eventSource : e.getSource(), e.getID(), KEY_PRESSED));
				b = true;
			}
		}
		return b;
	}


Input:
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_carregar);
		textViewAutor = (TextView) findViewById(R.id.textAutor);
		textViewAlbum = (TextView) findViewById(R.id.textAlbum);
		textViewGenero = (TextView) findViewById(R.id.textGenero);
		textViewAutor.setText("Autor: "+"Campo Vázio");
		textViewAlbum.setText("Album: "+"Campo Vázio");
		textViewGenero.setText("Genero: "+"Campo Vázio");
		ImageButton botaoAdd = (ImageButton) findViewById(R.id.botaoAddMusica);
		botaoAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(file != null){
					if (!(ListMusic.getInstance().getListMusic().contains(file))){
						ListMusic.getInstance().addMusica(file);
						MainActivity.fileAdapter.notifyDataSetChanged();
					}
				}
			}
		});
		sdcard = Environment.getExternalStorageDirectory();
		final File[] files = sdcard.listFiles();
		listView = (ListView) findViewById(R.id.files);
		updateList(files);
		adapter = new FileAdapter(getApplicationContext(), list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
	        @Override
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
	        	if (list.get(position).isDirectory()){
	        		File[] filesAux = list.get(position).listFiles();
	        		File auxParent = list.get(position).getParentFile();
	        		updateList(filesAux);
	        		list.add(0, auxParent);
	        		adapter.notifyDataSetChanged();
	        	}else{
	        		try {
	        			System.out.println("entrou");
						MP3 m = new MP3(list.get(position));
						if(m.getAlbum()!=null){
							String album = String.valueOf(m.getAlbum()).length()>12 ? String.valueOf(m.getAlbum()).substring(0,20)+"...":String.valueOf(m.getAlbum());
							textViewAlbum.setText("Album: "+album);
						}
						if(m.getMusicBy() !=null){
							String musicBy = String.valueOf(m.getMusicBy()).length()>12 ? String.valueOf(m.getMusicBy()).substring(0,20)+"...":String.valueOf(m.getMusicBy());
							textViewAutor.setText("Autor: "+musicBy);
						}
						if(m.getMusicType() != null){
							String genero = String.valueOf(m.getMusicType()).length()>12 ? String.valueOf(m.getMusicType()).substring(0,20)+"...":String.valueOf(m.getMusicType());
							textViewGenero.setText("Genero: "+genero);
						}
						file = list.get(position);
					} catch (IOException e) {
						System.out.println("Não foi possivel adicionar musica!");
					}
	        	}
	        }
	    });
	}

Output:
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_carregar);
		textViewAutor = (TextView) findViewById(R.id.textAutor);
		textViewAlbum = (TextView) findViewById(R.id.textAlbum);
		textViewGenero = (TextView) findViewById(R.id.textGenero);
		textViewAutor.setText("Autor: "+"Campo Vázio");
		textViewAlbum.setText("Album: "+"Campo Vázio");
		textViewGenero.setText("Genero: "+"Campo Vázio");
		ImageButton botaoAdd = (ImageButton) findViewById(R.id.botaoAddMusica);
		botaoAdd.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(file != null){
					if (!(ListMusic.getInstance().getListMusic().contains(file))){
						ListMusic.getInstance().addMusica(file);
						MainActivity.fileAdapter.notifyDataSetChanged();
					}
				}
			}
		});
		sdcard = Environment.getExternalStorageDirectory();
		final File[] files = sdcard.listFiles();
		listView = (ListView) findViewById(R.id.files);
		updateList(files);
		adapter = new FileAdapter(getApplicationContext(), list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {
	        @Override
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
	        	if (list.get(position).isDirectory()){
	        		File[] filesAux = list.get(position).listFiles();
	        		File auxParent = list.get(position).getParentFile();
	        		updateList(filesAux);
	        		list.add(0, auxParent);
	        		adapter.notifyDataSetChanged();
	        	}else{
	        		try {
	        			System.out.println("entrou");
						MP3 m = new MP3(list.get(position));
						if(m.getAlbum()!=null && m.getAlbum().length()>20){
							String album = String.valueOf(m.getAlbum()).length()>12 ? String.valueOf(m.getAlbum()).substring(0,20)+"...":String.valueOf(m.getAlbum());
							textViewAlbum.setText("Album: "+album);
						}
						if(m.getMusicBy() !=null && m.getMusicBy().length()> 20){
							String musicBy = String.valueOf(m.getMusicBy()).length()>12 ? String.valueOf(m.getMusicBy()).substring(0,20)+"...":String.valueOf(m.getMusicBy());
							textViewAutor.setText("Autor: "+musicBy);
						}
						if(m.getMusicType() != null && m.getMusicType().length()>20){
							String genero = String.valueOf(m.getMusicType()).length()>12 ? String.valueOf(m.getMusicType()).substring(0,20)+"...":String.valueOf(m.getMusicType());
							textViewGenero.setText("Genero: "+genero);
						}
						file = list.get(position);
					} catch (IOException e) {
						System.out.println("Não foi possivel adicionar musica!");
					}
	        	}
	        }
	    });
	}


Input:
    public void initialize() throws OperatorException {
        Product aotProduct;
        if (step1) {
            aotProduct = processAot(sourceProduct);
            if (aotProduct == GaMasterOp.EMPTY_PRODUCT) {
                setTargetProduct(GaMasterOp.EMPTY_PRODUCT);
                return;
            }
        } else {
            aotProduct = sourceProduct;
        }
        if (useFileTileCache) {
            attachFileTileCache(aotProduct);
        }
        Product bbdrProduct;
        if (step2) {
            bbdrProduct = processBbdr(aotProduct);
            if (sensor == Sensor.MERIS) {
                for (String rayleighBandName : BRR_BANDS) {
                    bbdrProduct.addBand(aotProduct.getBand(rayleighBandName));
                }
            }
        } else {
            bbdrProduct = aotProduct;
        }
        setTargetProduct(bbdrProduct);
    }

Output:
    public void initialize() throws OperatorException {
        Product aotProduct;
        if (step1) {
            aotProduct = processAot(sourceProduct);
            if (aotProduct == GaMasterOp.EMPTY_PRODUCT) {
                setTargetProduct(GaMasterOp.EMPTY_PRODUCT);
                return;
            }
        } else {
            aotProduct = sourceProduct;
        }
        if (useFileTileCache) {
            attachFileTileCache(aotProduct);
        }
        Product bbdrProduct;
        if (step2) {
            bbdrProduct = processBbdr(aotProduct);
            if (sensor == Sensor.MERIS && idepixAlgorithm == CloudScreeningSelector.GlobAlbedo) {
                for (String rayleighBandName : BRR_BANDS) {
                    bbdrProduct.addBand(aotProduct.getBand(rayleighBandName));
                }
            }
        } else {
            bbdrProduct = aotProduct;
        }
        setTargetProduct(bbdrProduct);
    }


Input:
    public synchronized void populateQuestions() {
        Logger.d(TAG, "Populating poll");
        int nSlots = questionsStorage.getNSlotsPerPoll();
        HashMap<Integer, ArrayList<Question>> slots =
                new HashMap<Integer, ArrayList<Question>>();
        SlottedQuestions slottedQuestions =
                questionsStorage.getSlottedQuestions();
        Logger.v(TAG, "Got {} questions from DB", slottedQuestions.size());
        HashMap<Integer, ArrayList<Question>> positionedGroups =
                slottedQuestions.getPositionedQuestionGroups();
        Logger.v(TAG, "Got {} positioned question groups",
                positionedGroups.size());
        int originalIndex;
        int convertedIndex;
        for (Map.Entry<Integer, ArrayList<Question>> groupEntry :
                positionedGroups.entrySet()) {
            originalIndex = groupEntry.getKey();
            convertedIndex = originalIndex < 0 ?
                    nSlots + originalIndex : originalIndex;
            Logger.v(TAG, "Placing group at slot {}", convertedIndex);
            slots.put(convertedIndex, groupEntry.getValue());
        }
        ArrayList<Integer> remainingIndices = new ArrayList<Integer>();
        for (int i = 0; i < nSlots; i++) {
            if (!slots.containsKey(i)) {
                remainingIndices.add(i);
            }
        }
        int nFloatingToFill = remainingIndices.size();
        Logger.v(TAG, "Still have {} slots to fill", nFloatingToFill);
        ArrayList<ArrayList<Question>> floatingGroups =
                slottedQuestions.getRandomFloatingQuestionGroups(
                        nFloatingToFill);
        Logger.v(TAG, "Got {} floating groups to fill the slots",
                floatingGroups.size());
        for (int i = 0; i < nFloatingToFill; i++) {
            Logger.v(TAG, "Putting group {0} at slot {1}",
                    floatingGroups.get(i).get(0).getSlot(),
                    remainingIndices.get(i));
            slots.put(remainingIndices.get(i), floatingGroups.get(i));
        }
        ArrayList<ArrayList<Question>> slotsArray =
                new ArrayList<ArrayList<Question>>(nSlots);
        ArrayList<Question> slotQuestions;
        for (Map.Entry<Integer, ArrayList<Question>> groupEntry :
                slots.entrySet()) {
            Logger.v(TAG, "Shuffling slot {}", groupEntry.getKey());
            slotQuestions = groupEntry.getValue();
            util.shuffle(slotQuestions);
            slotsArray.add(groupEntry.getKey(), slotQuestions);
        }
        Logger.v(TAG, "Flattening the slots into an array");
        questions = new ArrayList<Question>();
        for (ArrayList<Question> slot : slotsArray) {
            questions.addAll(slot);
        }
    }

Output:
    public synchronized void populateQuestions() {
        Logger.d(TAG, "Populating poll");
        int nSlots = questionsStorage.getNSlotsPerPoll();
        HashMap<Integer, ArrayList<Question>> slots =
                new HashMap<Integer, ArrayList<Question>>();
        SlottedQuestions slottedQuestions =
                questionsStorage.getSlottedQuestions();
        Logger.v(TAG, "Got {} questions from DB", slottedQuestions.size());
        HashMap<Integer, ArrayList<Question>> positionedGroups =
                slottedQuestions.getPositionedQuestionGroups();
        Logger.v(TAG, "Got {} positioned question groups",
                positionedGroups.size());
        int originalIndex;
        int convertedIndex;
        for (Map.Entry<Integer, ArrayList<Question>> groupEntry :
                positionedGroups.entrySet()) {
            originalIndex = groupEntry.getKey();
            convertedIndex = originalIndex < 0 ?
                    nSlots + originalIndex : originalIndex;
            Logger.v(TAG, "Placing group at slot {}", convertedIndex);
            slots.put(convertedIndex, groupEntry.getValue());
        }
        ArrayList<Integer> remainingIndices = new ArrayList<Integer>();
        for (int i = 0; i < nSlots; i++) {
            if (!slots.containsKey(i)) {
                remainingIndices.add(i);
            }
        }
        int nFloatingToFill = remainingIndices.size();
        Logger.v(TAG, "Still have {} slots to fill", nFloatingToFill);
        ArrayList<ArrayList<Question>> floatingGroups =
                slottedQuestions.getRandomFloatingQuestionGroups(
                        nFloatingToFill);
        Logger.v(TAG, "Got {} floating groups to fill the slots",
                floatingGroups.size());
        for (int i = 0; i < nFloatingToFill; i++) {
            Logger.v(TAG, "Putting group {0} at slot {1}",
                    floatingGroups.get(i).get(0).getSlot(),
                    remainingIndices.get(i));
            slots.put(remainingIndices.get(i), floatingGroups.get(i));
        }
        ArrayList<ArrayList<Question>> slotsArray =
                new ArrayList<ArrayList<Question>>(nSlots);
        ArrayList<Question> slotQuestions;
        for (Map.Entry<Integer, ArrayList<Question>> groupEntry :
                slots.entrySet()) {
            Logger.v(TAG, "Shuffling slot {}", groupEntry.getKey());
            slotQuestions = groupEntry.getValue();
            util.shuffle(slotQuestions);
            slotsArray.add(groupEntry.getKey(), slotQuestions);
        }
        Logger.v(TAG, "Flattening the slots into an array");
        questions = new ArrayList<Question>();
        for (ArrayList<Question> slot : slotsArray) {
            for (Question q : slot) {
                addQuestion(q);
            }
        }
    }


Input:
    public void mergeAlignment() {
        final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
        final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
        final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
        this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
        int aligned = 0;
        int unmapped = 0;
        final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
        SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
        final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
            SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
            MAX_RECORDS_IN_RAM);
        SAMRecord firstOfPair = null;
        while (unmappedIterator.hasNext()) {
            final SAMRecord rec = unmappedIterator.next();
            if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
                throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
                        ") is behind the unmapped reads (" + rec.getReadName() + ")");
            }
            rec.setHeader(this.header);
            if (isMatch(rec, nextAligned)) {
                if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
                    setValuesFromAlignment(rec, nextAligned);
                    updateCigarForTrimmedOrClippedBases(rec, nextAligned);
                    if (this.programRecord != null) {
                        rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
                            this.programRecord.getProgramGroupId());
                    }
                    aligned++;
                }
                else {
                    unmapped++;
                }
                nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
            }
            else {
                unmapped++;
            }
            if (!rec.getReadPairedFlag()) {
                if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
                    coordinateSorted.add(rec);
                }
            }
            else {
                if (firstOfPair == null) {
                    firstOfPair = rec;
                }
                else {
                    if (!rec.getReadName().equals(firstOfPair.getReadName())) {
                        coordinateSorted.add(firstOfPair);
                        firstOfPair = rec;
                    }
                    else {
                        if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
                            clipForOverlappingReads(rec, firstOfPair);
                            SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
                            coordinateSorted.add(firstOfPair);
                            coordinateSorted.add(rec);
                            firstOfPair = null;
                        }
                    }
                }
            }
        }
        unmappedIterator.close();
        if (alignedIterator.hasNext()) {
            throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
        }
        alignedIterator.close();
        final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
        int count = 0;
        CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
        while (it.hasNext()) {
            SAMRecord rec = it.next();
            if (!rec.getReadUnmappedFlag()) {
                if (refSeq != null) {
                    byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
                    rec.setAttribute(SAMTag.NM.name(),
                        SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
                    if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
                        rec.setAttribute(SAMTag.UQ.name(),
                            SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
                    }
                }
            }
            writer.addAlignment(rec);
            if (++count % 1000000 == 0) {
                log.info(count + " SAMRecords written to " + targetBamFile.getName());
            }
        }
        writer.close();
        log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
    }

Output:
    public void mergeAlignment() {
        final SAMRecordQueryNameComparator comparator = new SAMRecordQueryNameComparator();
        final SAMFileReader unmappedSam = new SAMFileReader(this.unmappedBamFile);
        final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
        this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
        int aligned = 0;
        int unmapped = 0;
        final CloseableIterator<SAMRecord> alignedIterator = getQuerynameSortedAlignedRecords();
        SAMRecord nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
        final SortingCollection<SAMRecord> coordinateSorted = SortingCollection.newInstance(
            SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
            MAX_RECORDS_IN_RAM);
        SAMRecord firstOfPair = null;
        while (unmappedIterator.hasNext()) {
            final SAMRecord rec = unmappedIterator.next();
            if (nextAligned != null && comparator.compare(rec, nextAligned) > 0) {
                throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
                        ") is behind the unmapped reads (" + rec.getReadName() + ")");
            }
            rec.setHeader(this.header);
            if (isMatch(rec, nextAligned)) {
                if (!(nextAligned.getReadUnmappedFlag() || ignoreAlignment(nextAligned))) {
                    setValuesFromAlignment(rec, nextAligned);
                    updateCigarForTrimmedOrClippedBases(rec, nextAligned);
                    if (this.programRecord != null) {
                        rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID,
                            this.programRecord.getProgramGroupId());
                    }
                    aligned++;
                }
                else {
                    unmapped++;
                }
                nextAligned = alignedIterator.hasNext() ? alignedIterator.next() : null;
            }
            else {
                unmapped++;
            }
            if (!rec.getReadPairedFlag()) {
                if (!rec.getReadUnmappedFlag() || !alignedReadsOnly) {
                    coordinateSorted.add(rec);
                }
            }
            else {
                if (firstOfPair == null) {
                    firstOfPair = rec;
                }
                else {
                    if (!rec.getReadName().equals(firstOfPair.getReadName())) {
                        throw new PicardException("Second read from pair not found in unmapped bam: " +
                            rec.getReadName());
                    }
                    else {
                        if ((!rec.getReadUnmappedFlag() || !firstOfPair.getReadUnmappedFlag()) || !alignedReadsOnly) {
                            clipForOverlappingReads(rec, firstOfPair);
                            SamPairUtil.setProperPairAndMateInfo(rec, firstOfPair, header, expectedOrientations);
                            coordinateSorted.add(firstOfPair);
                            coordinateSorted.add(rec);
                            firstOfPair = null;
                        }
                    }
                }
            }
        }
        unmappedIterator.close();
        if (alignedIterator.hasNext()) {
            throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
        }
        alignedIterator.close();
        final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
        int count = 0;
        CloseableIterator<SAMRecord> it = coordinateSorted.iterator();
        while (it.hasNext()) {
            SAMRecord rec = it.next();
            if (!rec.getReadUnmappedFlag()) {
                if (refSeq != null) {
                    byte referenceBases[] = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
                    rec.setAttribute(SAMTag.NM.name(),
                        SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
                    if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
                        rec.setAttribute(SAMTag.UQ.name(),
                            SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
                    }
                }
            }
            writer.addAlignment(rec);
            if (++count % 1000000 == 0) {
                log.info(count + " SAMRecords written to " + targetBamFile.getName());
            }
        }
        writer.close();
        log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
    }


Input:
	public Rock(Stage stage,float fallSpeed,float rotationSpeed, float width, float height){
		this.fallSpeed = fallSpeed;
		this.rotationSpeed = rotationSpeed;
		this.width = width;
		this.height = height;
		this.rgn = new TextureRegion(Assets.get().rock);
		setSize(this.width,this.height);
		setOrigin(this.width/2,this.height/2);
		float x = (random.nextFloat() *stage.getWidth());
		setPosition(x,stage.getHeight());
		addAction(sequence(
				moveTo(x, stage.getHeight()+32f, this.fallSpeed),
				run(new Runnable() {
					@Override
					public void run() {
						Rock.this.remove();
					}})
				));
		addAction(forever(rotateBy(360, this.rotationSpeed)));
	}

Output:
	public Rock(Stage stage,float fallSpeed,float rotationSpeed, float width, float height){
		this.fallSpeed = fallSpeed;
		this.rotationSpeed = rotationSpeed;
		this.width = width;
		this.height = height;
		this.rgn = new TextureRegion(Assets.get().rock);
		setSize(this.width,this.height);
		setOrigin(this.width/2,this.height/2);
		float x = (random.nextFloat() *stage.getWidth());
		setPosition(x,stage.getHeight());
		addAction(sequence(
				moveTo(x, -32f, this.fallSpeed),
				run(new Runnable() {
					@Override
					public void run() {
						Rock.this.remove();
					}})
				));
		addAction(forever(rotateBy(360, this.rotationSpeed)));
	}


Input:
        public void execute(CancellationToken cancelToken) {
            assert eventScheduler.isExecutingInThis();
            OrderedData<DataType> data = pollData();
            if (data == null) {
                return;
            }
            if (forwardedData && data.getIndex() <= lastSentIndex) {
                return;
            }
            if (done) {
                return;
            }
            wrappedListener.onDataArrive(data.getRawData());
        }

Output:
        public void execute(CancellationToken cancelToken) {
            assert eventScheduler.isExecutingInThis();
            OrderedData<DataType> data = pollData();
            if (data == null) {
                return;
            }
            if (forwardedData && data.getIndex() <= lastSentIndex) {
                return;
            }
            if (done) {
                return;
            }
            lastSentIndex = data.getIndex();
            forwardedData = true;
            wrappedListener.onDataArrive(data.getRawData());
        }


Input:
        public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
            this.client = client;
            final ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
            for (final Iterator<Widget> iterator = iterator(); iterator
                    .hasNext();) {
                oldWidgets.add(iterator.next());
            }
            clear();
            ValueMap mapAttribute = null;
            if (uidl.hasAttribute("css")) {
                mapAttribute = uidl.getMapAttribute("css");
            }
            for (final Iterator<Object> i = uidl.getChildIterator(); i
                    .hasNext();) {
                final UIDL r = (UIDL) i.next();
                final Paintable child = client.getPaintable(r);
                if (oldWidgets.contains(child)) {
                    oldWidgets.remove(child);
                }
                add((Widget) child);
                if (mapAttribute != null && mapAttribute.containsKey(r.getId())) {
                    String css = null;
                    try {
                        Style style = ((Widget) child).getElement().getStyle();
                        css = mapAttribute.getString(r.getId());
                        String[] cssRules = css.split(";");
                        for (int j = 0; j < cssRules.length; j++) {
                            String[] rule = cssRules[j].split(":");
                            if (rule.length == 0) {
                                continue;
                            } else {
                                style.setProperty(
                                        makeCamelCase(rule[0].trim()),
                                        rule[1].trim());
                            }
                        }
                    } catch (Exception e) {
                        VConsole.log("CssLayout encounterd invalid css string: "
                                + css);
                    }
                }
                if (!r.getBooleanAttribute("cached")) {
                    child.updateFromUIDL(r, client);
                }
            }
            for (Widget w : oldWidgets) {
                if (w instanceof Paintable) {
                    final Paintable p = (Paintable) w;
                    client.unregisterPaintable(p);
                }
                widgetToCaption.remove(w);
            }
        }

Output:
        public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
            this.client = client;
            final ArrayList<Widget> oldWidgets = new ArrayList<Widget>();
            for (final Iterator<Widget> iterator = iterator(); iterator
                    .hasNext();) {
                oldWidgets.add(iterator.next());
            }
            clear();
            ValueMap mapAttribute = null;
            if (uidl.hasAttribute("css")) {
                mapAttribute = uidl.getMapAttribute("css");
            }
            for (final Iterator<Object> i = uidl.getChildIterator(); i
                    .hasNext();) {
                final UIDL r = (UIDL) i.next();
                final Paintable child = client.getPaintable(r);
                if (oldWidgets.contains(child)) {
                    oldWidgets.remove(child);
                    VCaption vCaption = widgetToCaption.get(child);
                    if (vCaption != null) {
                        add(vCaption);
                        oldWidgets.remove(vCaption);
                    }
                }
                add((Widget) child);
                if (mapAttribute != null && mapAttribute.containsKey(r.getId())) {
                    String css = null;
                    try {
                        Style style = ((Widget) child).getElement().getStyle();
                        css = mapAttribute.getString(r.getId());
                        String[] cssRules = css.split(";");
                        for (int j = 0; j < cssRules.length; j++) {
                            String[] rule = cssRules[j].split(":");
                            if (rule.length == 0) {
                                continue;
                            } else {
                                style.setProperty(
                                        makeCamelCase(rule[0].trim()),
                                        rule[1].trim());
                            }
                        }
                    } catch (Exception e) {
                        VConsole.log("CssLayout encounterd invalid css string: "
                                + css);
                    }
                }
                if (!r.getBooleanAttribute("cached")) {
                    child.updateFromUIDL(r, client);
                }
            }
            for (Widget w : oldWidgets) {
                if (w instanceof Paintable) {
                    final Paintable p = (Paintable) w;
                    client.unregisterPaintable(p);
                }
                widgetToCaption.remove(w);
            }
        }


Input:
	public static HttpRequestMessage of(ByteBuffer buffer) {
		String raw = new String(buffer.array(), Charset.forName("US-ASCII"));
		String[] fields = raw.split("\\r\\n");
		String requestLine = fields[0];
		Map<String, String> generalHeaders = new HashMap<String, String>();
		for (int i = 1; i < fields.length; i++) {
			String[] header = fields[i].split(": ");
			generalHeaders.put(header[0], header[1]);
		}
		return new HttpRequestMessage(requestLine, generalHeaders);
	}

Output:
	public static HttpRequestMessage of(ByteBuffer buffer) {
		String raw = new String(buffer.array(), Charset.forName("US-ASCII"));
		String[] fields = raw.split("\\r\\n");
		String requestLine = fields[0];
		Map<String, String> generalHeaders = new HashMap<String, String>();
		for (int i = 1; i < fields.length; i++) {
			if (fields[i].trim().equals("")) {
				continue;
			}
			String[] header = fields[i].split(": ");
			generalHeaders.put(header[0], header[1]);
		}
		return new HttpRequestMessage(requestLine, generalHeaders);
	}


Input:
	@Test public void testEmail(){
		Boolean doIreallyWantToSpam = false;
	    String from = "";
	    String[] recipients = { ""};
	    String SMTP_HOST_NAME = "localhost";
	    String SMTP_PORT = "25";
	    String message = "Hi, Test Message Contents";
	    String subject = "A test from collectionspace test suite";
	    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        boolean debug = true;
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "false");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(debug);
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom;
		try {
			addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        if(doIreallyWantToSpam){
        	Transport.send(msg);
        	assertTrue(doIreallyWantToSpam);
        }
		} catch (AddressException e) {
			log.info(e.getMessage());
			assertTrue(false);
		} catch (MessagingException e) {
			log.info(e.getMessage());
			assertTrue(false);
		}
	}

Output:
	@Test public void testEmail(){
		Boolean doIreallyWantToSpam = false;
	    String from = "";
	    String[] recipients = { ""};
	    String SMTP_HOST_NAME = "localhost";
	    String SMTP_PORT = "25";
	    String message = "Hi, Test Message Contents";
	    String subject = "A test from collectionspace test suite";
	    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        boolean debug = true;
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST_NAME);
        props.put("mail.smtp.auth", "false");
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.port", SMTP_PORT);
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        Session session = Session.getDefaultInstance(props);
        session.setDebug(debug);
        if(doIreallyWantToSpam){
        Message msg = new MimeMessage(session);
        InternetAddress addressFrom;
		try {
			addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);
        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setContent(message, "text/plain");
        if(doIreallyWantToSpam){
        	Transport.send(msg);
        	assertTrue(doIreallyWantToSpam);
        }
		} catch (AddressException e) {
			log.info(e.getMessage());
			assertTrue(false);
		} catch (MessagingException e) {
			log.info(e.getMessage());
			assertTrue(false);
		}
		}
	}


Input:
    public void addBody(Body body) throws WingException, SQLException
    {
        EPerson currentUser = context.getCurrentUser();
        if (currentUser != null)
        {
            Statement statement = context.getDBConnection().createStatement();
            String title_field_query =
                "SELECT metadata_field_id" +
                "    FROM metadatafieldregistry AS fields," +
                "            metadataschemaregistry AS schemas" +
                "    WHERE fields.metadata_schema_id" +
                "            = schemas.metadata_schema_id" +
                "        AND schemas.short_id = 'dc'" +
                "        AND fields.element = 'title'" +
                "        AND fields.qualifier IS NULL" +
                "    LIMIT 1;";
            ResultSet dcTitleField = statement.executeQuery(title_field_query);
            dcTitleField.next();
            String dcTitleID = dcTitleField.getString("metadata_field_id");
            String submissions_query =
                "SELECT COUNT(metadatavalue.text_value)" +
                "    FROM workflowitem, item, metadatavalue" +
                "    WHERE workflowitem.item_id = item.item_id" +
                "        AND item.item_id = metadatavalue.item_id" +
                "        AND metadatavalue.metadata_field_id = " + dcTitleID +
                "        AND item.submitter_id = " + currentUser.getID() + ";";
            ResultSet submissions = statement.executeQuery(submissions_query);
            submissions.next();
            int rowCount = submissions.getInt(1);
            if (rowCount > 0)
            {
                Message T_link;
                Message T_outtro;
                if (rowCount == 1)
                {
                    T_link = T_one_pending_submission;
                    T_outtro = T_pending_submissions_outtro_single;
                }
                else
                {
                    T_link =
                        T_multiple_pending_submissions.parameterize(rowCount);
                    T_outtro  = T_pending_submissions_outtro_multiple;
                }
                Division pending = body.addDivision("pending-submissions");
                Para para = pending.addPara();
                para.addContent(T_pending_submissions_intro);
                para.addXref("submissions", T_link);
                para.addContent(T_outtro);
            }
        }
    }

Output:
    public void addBody(Body body) throws WingException, SQLException
    {
        EPerson currentUser = context.getCurrentUser();
        if (currentUser != null)
        {
            Statement statement = context.getDBConnection().createStatement();
            String title_field_query =
                "SELECT metadata_field_id" +
                "    FROM metadatafieldregistry AS fields," +
                "            metadataschemaregistry AS schemas" +
                "    WHERE fields.metadata_schema_id" +
                "            = schemas.metadata_schema_id" +
                "        AND schemas.short_id = 'dc'" +
                "        AND fields.element = 'title'" +
                "        AND fields.qualifier IS NULL" +
                "    LIMIT 1;";
            ResultSet dcTitleField = statement.executeQuery(title_field_query);
            dcTitleField.next();
            String dcTitleID = dcTitleField.getString("metadata_field_id");
            String submissions_query =
                "SELECT COUNT(metadatavalue.text_value)" +
                "    FROM workflowitem, item, metadatavalue" +
                "    WHERE workflowitem.item_id = item.item_id" +
                "        AND item.item_id = metadatavalue.item_id" +
                "        AND metadatavalue.metadata_field_id = " + dcTitleID +
                "        AND item.submitter_id = " + currentUser.getID() + ";";
            ResultSet submissions = statement.executeQuery(submissions_query);
            submissions.next();
            int rowCount = submissions.getInt(1);
            if (rowCount > 0)
            {
                Message T_link;
                Message T_outtro;
                if (rowCount == 1)
                {
                    T_link = T_one_pending_submission;
                    T_outtro = T_pending_submissions_outtro_single;
                }
                else
                {
                    T_link =
                        T_multiple_pending_submissions.parameterize(rowCount);
                    T_outtro  = T_pending_submissions_outtro_multiple;
                }
                Division pending = body.addDivision("pending-submissions");
                Para para = pending.addPara();
                para.addContent(T_pending_submissions_intro);
                para.addXref("/xmlui/submissions", T_link);
                para.addContent(T_outtro);
            }
        }
    }


Input:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Session session = HibernateSessionHelper.getSession();
		Template template = TemplateFactory.getTemplate(request, response);
		PrintWriter out = response.getWriter();
		TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
		Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
		if (task == null) {
			template.printTemplateHeader("Aufgabe nicht gefunden");
			out.println("
zur �bersicht
");
			template.printTemplateFooter();
			return;
		}
		ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
		Participation studentParticipation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture());
		if (studentParticipation == null) {
			template.printTemplateHeader("Ung�ltige Anfrage");
			out.println("
Sie sind kein Teilnehmer dieser Veranstaltung.
");
			out.println("
zur �bersicht
");
			template.printTemplateFooter();
			return;
		}
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		int partnerID = 0;
		int uploadFor = 0;
		List<FileItem> items = null;
		if (!isMultipart) {
			partnerID = Util.parseInteger(request.getParameter("partnerid"), 0);
		} else {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
				return;
			}
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (item.isFormField() && "partnerid".equals(item.getFieldName())) {
					partnerID = Util.parseInteger(item.getString(), 0);
				} else if (item.isFormField() && "uploadFor".equals(item.getFieldName())) {
					uploadFor = Util.parseInteger(item.getString(), 0);
				}
			}
		}
		if (uploadFor > 0) {
			if (!(studentParticipation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && studentParticipation.getRoleType() == ParticipationRole.TUTOR))) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Sie sind nicht berechtigt bei dieser Veranstaltung Dateien f�r Studenten hochzuladen.
");
				out.println("
zur �bersicht
");
				template.printTemplateFooter();
				return;
			}
			studentParticipation = participationDAO.getParticipation(uploadFor);
			if (studentParticipation == null || studentParticipation.getLecture().getId() != task.getLecture().getId()) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Der gew�hlte Student ist kein Teilnehmer dieser Veranstaltung.
");
				out.println("
zur �bersicht
");
				template.printTemplateFooter();
				return;
			}
			if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.
");
				template.printTemplateFooter();
				return;
			}
		} else {
			if (studentParticipation.getRoleType() == ParticipationRole.ADVISOR || studentParticipation.getRoleType() == ParticipationRole.TUTOR) {
				request.setAttribute("title", "Betreuer und Tutoren k�nnen keine eigenen L�sungen einsenden.");
				request.getRequestDispatcher("MessageView").forward(request, response);
				return;
			}
			if (task.getStart().after(Util.correctTimezone(new Date()))) {
				request.setAttribute("title", "Abgabe nicht gefunden");
				request.getRequestDispatcher("MessageView").forward(request, response);
				return;
			}
			if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
				request.setAttribute("title", "Abgabe nicht mehr m�glich");
				request.getRequestDispatcher("MessageView").forward(request, response);
				return;
			}
			if (isMultipart && "-".equals(task.getFilenameRegexp())) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Dateiupload ist f�r diese Aufgabe deaktiviert.
");
				template.printTemplateFooter();
				return;
			} else if (!isMultipart && !task.isShowTextArea()) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Textl�sungen sind f�r diese Aufgabe deaktiviert.
");
				template.printTemplateFooter();
				return;
			}
		}
		SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
		Transaction tx = session.beginTransaction();
		Submission submission = submissionDAO.createSubmission(task, studentParticipation);
		if (partnerID > 0) {
			Participation partnerParticipation = participationDAO.getParticipation(partnerID);
			if (submission.getSubmitters().size() < 2 && partnerParticipation != null && partnerParticipation.getLecture().getId() == task.getLecture().getId() && submissionDAO.getSubmissionLocked(task, partnerParticipation.getUser()) == null) {
				submission.getSubmitters().add(partnerParticipation);
				session.update(submission);
			} else {
				tx.rollback();
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("
Der ausgew�hlte Partner hat bereits eine eigene Abgabe initiiert oder Sie haben bereits einen Partner ausgew�hlt.
");
				template.printTemplateFooter();
				return;
			}
		}
		ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
		File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator"));
		if (path.exists() == false) {
			path.mkdirs();
		}
		if (isMultipart) {
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (!item.isFormField()) {
					if (item.getName().toLowerCase().endsWith(".zip") || item.getName().toLowerCase().endsWith(".jar")) {
						ZipInputStream zipFile;
						Pattern pattern = Pattern.compile("([\\/a-zA-Z0-9_.-]+)$");
						try {
							zipFile = new ZipInputStream(item.getInputStream());
							ZipEntry entry = null;
							while ((entry = zipFile.getNextEntry()) != null) {
								if (entry.getName().contains("..")) {
									continue;
								}
								StringBuffer submittedFileName = new StringBuffer(entry.getName());
								if (!pattern.matcher(submittedFileName).matches()) {
									System.out.println("Ignored entry: " + submittedFileName);
									continue;
								}
								if (entry.isDirectory() == false && !entry.getName().toLowerCase().endsWith(".class")) {
									if (submittedFileName.lastIndexOf(".") > 0) {
										int lastDot = submittedFileName.lastIndexOf(".");
										submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
									}
									File fileToCreate = new File(path, submittedFileName.toString());
									if (!fileToCreate.getParentFile().exists()) {
										fileToCreate.getParentFile().mkdirs();
									}
									copyInputStream(zipFile, new BufferedOutputStream(new FileOutputStream(fileToCreate)));
								}
							}
							zipFile.close();
						} catch (IOException e) {
							Util.recursiveDeleteEmptySubDirectories(path);
							tx.rollback();
							System.out.println(e.getMessage());
							e.printStackTrace();
							template.printTemplateHeader("Ung�ltige Anfrage");
							out.println("Problem beim entpacken der .zip-Datei.");
							template.printTemplateFooter();
							return;
						}
					} else {
						Pattern pattern;
						if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty() || uploadFor > 0) {
							pattern = Pattern.compile(".*?(?:\\\\|/)?([a-zA-Z0-9_.-]+)$");
						} else {
							pattern = Pattern.compile(".*?(?:\\\\|/)?(" + task.getFilenameRegexp() + ")$");
						}
						StringBuffer submittedFileName = new StringBuffer(item.getName());
						if (submittedFileName.lastIndexOf(".") > 0) {
							int lastDot = submittedFileName.lastIndexOf(".");
							submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
						}
						Matcher m = pattern.matcher(submittedFileName);
						if (!m.matches()) {
							tx.rollback();
							template.printTemplateHeader("Ung�ltige Anfrage");
							out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).
Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt.");
							template.printTemplateFooter();
							return;
						}
						String fileName = m.group(1);
						File uploadedFile = new File(path, fileName);
						if (fileName.toLowerCase().endsWith(".java")) {
							uploadedFile = File.createTempFile("upload", null, path);
						}
						try {
							item.write(uploadedFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (fileName.toLowerCase().endsWith(".java")) {
							NormalizerIf stripComments = new StripCommentsNormalizer();
							StringBuffer javaFileContents = stripComments.normalize(Util.loadFile(uploadedFile));
							Pattern packagePattern = Pattern.compile(".*package\\s+([a-zA-Z$]([a-zA-Z0-9_$]|\\.[a-zA-Z0-9_$])*)\\s*;.*", Pattern.DOTALL);
							Matcher packageMatcher = packagePattern.matcher(javaFileContents);
							if (packageMatcher.matches()) {
								String packageName = packageMatcher.group(1).replace(".", System.getProperty("file.separator"));
								File packageDirectory = new File(path, packageName);
								packageDirectory.mkdirs();
								uploadedFile.renameTo(new File(packageDirectory, fileName));
							} else {
								uploadedFile.renameTo(new File(path, fileName));
							}
						}
					}
					submission.setLastModified(new Date());
					submissionDAO.saveSubmission(submission);
					Util.recursiveDeleteEmptyDirectories(path);
					tx.commit();
					new LogDAO(session).createLogEntry(studentParticipation.getUser(), null, task, LogAction.UPLOAD, null, null);
					response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
					return;
				}
			}
			tx.rollback();
			out.println("Problem: Keine Abgabedaten gefunden.");
		} else if (request.getParameter("textsolution") != null) {
			File uploadedFile = new File(path, "textloesung.txt");
			FileWriter fileWriter = new FileWriter(uploadedFile);
			fileWriter.write(request.getParameter("textsolution"));
			fileWriter.flush();
			fileWriter.close();
			submission.setLastModified(new Date());
			submissionDAO.saveSubmission(submission);
			tx.commit();
			response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
		} else {
			tx.rollback();
			out.println("Problem: Keine Abgabedaten gefunden.");
		}
	}

Output:
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		Session session = HibernateSessionHelper.getSession();
		Template template = TemplateFactory.getTemplate(request, response);
		PrintWriter out = response.getWriter();
		TaskDAOIf taskDAO = DAOFactory.TaskDAOIf(session);
		Task task = taskDAO.getTask(Util.parseInteger(request.getParameter("taskid"), 0));
		if (task == null) {
			template.printTemplateHeader("Aufgabe nicht gefunden");
			out.println("<div class=mid><a href=\"" + response.encodeURL("?") + "\">zur �bersicht</a></div>");
			template.printTemplateFooter();
			return;
		}
		ParticipationDAOIf participationDAO = DAOFactory.ParticipationDAOIf(session);
		Participation studentParticipation = participationDAO.getParticipation(new SessionAdapter(request).getUser(session), task.getLecture());
		if (studentParticipation == null) {
			template.printTemplateHeader("Ung�ltige Anfrage");
			out.println("<div class=mid>Sie sind kein Teilnehmer dieser Veranstaltung.</div>");
			out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
			template.printTemplateFooter();
			return;
		}
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		int partnerID = 0;
		int uploadFor = 0;
		List<FileItem> items = null;
		if (!isMultipart) {
			partnerID = Util.parseInteger(request.getParameter("partnerid"), 0);
		} else {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
				return;
			}
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (item.isFormField() && "partnerid".equals(item.getFieldName())) {
					partnerID = Util.parseInteger(item.getString(), 0);
				} else if (item.isFormField() && "uploadFor".equals(item.getFieldName())) {
					uploadFor = Util.parseInteger(item.getString(), 0);
				}
			}
		}
		if (uploadFor > 0) {
			if (!(studentParticipation.getRoleType() == ParticipationRole.ADVISOR || (task.isTutorsCanUploadFiles() && studentParticipation.getRoleType() == ParticipationRole.TUTOR))) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Sie sind nicht berechtigt bei dieser Veranstaltung Dateien f�r Studenten hochzuladen.</div>");
				out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
				template.printTemplateFooter();
				return;
			}
			studentParticipation = participationDAO.getParticipation(uploadFor);
			if (studentParticipation == null || studentParticipation.getLecture().getId() != task.getLecture().getId()) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Der gew�hlte Student ist kein Teilnehmer dieser Veranstaltung.</div>");
				out.println("<div class=mid><a href=\"" + response.encodeURL("Overview") + "\">zur �bersicht</a></div>");
				template.printTemplateFooter();
				return;
			}
			if (task.isShowTextArea() == false && "-".equals(task.getFilenameRegexp())) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Das Einsenden von L�sungen ist f�r diese Aufgabe deaktiviert.</div>");
				template.printTemplateFooter();
				return;
			}
		} else {
			if (studentParticipation.getRoleType() == ParticipationRole.ADVISOR || studentParticipation.getRoleType() == ParticipationRole.TUTOR) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Betreuer und Tutoren k�nnen keine eigenen L�sungen einsenden.</div>");
				template.printTemplateFooter();
				return;
			}
			if (task.getStart().after(Util.correctTimezone(new Date()))) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Abgabe nicht gefunden.</div>");
				template.printTemplateFooter();
				return;
			}
			if (task.getDeadline().before(Util.correctTimezone(new Date()))) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Abgabe nicht mehr m�glich.</div>");
				template.printTemplateFooter();
				return;
			}
			if (isMultipart && "-".equals(task.getFilenameRegexp())) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Dateiupload ist f�r diese Aufgabe deaktiviert.</div>");
				template.printTemplateFooter();
				return;
			} else if (!isMultipart && !task.isShowTextArea()) {
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Textl�sungen sind f�r diese Aufgabe deaktiviert.</div>");
				template.printTemplateFooter();
				return;
			}
		}
		SubmissionDAOIf submissionDAO = DAOFactory.SubmissionDAOIf(session);
		Transaction tx = session.beginTransaction();
		Submission submission = submissionDAO.createSubmission(task, studentParticipation);
		if (partnerID > 0) {
			Participation partnerParticipation = participationDAO.getParticipation(partnerID);
			if (submission.getSubmitters().size() < 2 && partnerParticipation != null && partnerParticipation.getLecture().getId() == task.getLecture().getId() && submissionDAO.getSubmissionLocked(task, partnerParticipation.getUser()) == null) {
				submission.getSubmitters().add(partnerParticipation);
				session.update(submission);
			} else {
				tx.rollback();
				template.printTemplateHeader("Ung�ltige Anfrage");
				out.println("<div class=mid>Der ausgew�hlte Partner hat bereits eine eigene Abgabe initiiert oder Sie haben bereits einen Partner ausgew�hlt.</div>");
				template.printTemplateFooter();
				return;
			}
		}
		ContextAdapter contextAdapter = new ContextAdapter(getServletContext());
		File path = new File(contextAdapter.getDataPath().getAbsolutePath() + System.getProperty("file.separator") + task.getLecture().getId() + System.getProperty("file.separator") + task.getTaskid() + System.getProperty("file.separator") + submission.getSubmissionid() + System.getProperty("file.separator"));
		if (path.exists() == false) {
			path.mkdirs();
		}
		if (isMultipart) {
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				if (!item.isFormField()) {
					if (item.getName().toLowerCase().endsWith(".zip") || item.getName().toLowerCase().endsWith(".jar")) {
						ZipInputStream zipFile;
						Pattern pattern = Pattern.compile("([\\/a-zA-Z0-9_.-]+)$");
						try {
							zipFile = new ZipInputStream(item.getInputStream());
							ZipEntry entry = null;
							while ((entry = zipFile.getNextEntry()) != null) {
								if (entry.getName().contains("..")) {
									continue;
								}
								StringBuffer submittedFileName = new StringBuffer(entry.getName());
								if (!pattern.matcher(submittedFileName).matches()) {
									System.out.println("Ignored entry: " + submittedFileName);
									continue;
								}
								if (entry.isDirectory() == false && !entry.getName().toLowerCase().endsWith(".class")) {
									if (submittedFileName.lastIndexOf(".") > 0) {
										int lastDot = submittedFileName.lastIndexOf(".");
										submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
									}
									File fileToCreate = new File(path, submittedFileName.toString());
									if (!fileToCreate.getParentFile().exists()) {
										fileToCreate.getParentFile().mkdirs();
									}
									copyInputStream(zipFile, new BufferedOutputStream(new FileOutputStream(fileToCreate)));
								}
							}
							zipFile.close();
						} catch (IOException e) {
							Util.recursiveDeleteEmptySubDirectories(path);
							tx.rollback();
							System.out.println(e.getMessage());
							e.printStackTrace();
							template.printTemplateHeader("Ung�ltige Anfrage");
							out.println("Problem beim entpacken der .zip-Datei.");
							template.printTemplateFooter();
							return;
						}
					} else {
						Pattern pattern;
						if (task.getFilenameRegexp() == null || task.getFilenameRegexp().isEmpty() || uploadFor > 0) {
							pattern = Pattern.compile(".*?(?:\\\\|/)?([a-zA-Z0-9_.-]+)$");
						} else {
							pattern = Pattern.compile(".*?(?:\\\\|/)?(" + task.getFilenameRegexp() + ")$");
						}
						StringBuffer submittedFileName = new StringBuffer(item.getName());
						if (submittedFileName.lastIndexOf(".") > 0) {
							int lastDot = submittedFileName.lastIndexOf(".");
							submittedFileName.replace(lastDot, submittedFileName.length(), submittedFileName.subSequence(lastDot, submittedFileName.length()).toString().toLowerCase());
						}
						Matcher m = pattern.matcher(submittedFileName);
						if (!m.matches()) {
							tx.rollback();
							template.printTemplateHeader("Ung�ltige Anfrage");
							out.println("Dateiname ung�ltig bzw. entspricht nicht der Vorgabe (ist ein Klassenname vorgegeben, so muss die Datei genauso hei�en).<br>Tipp: Nur A-Z, a-z, 0-9, ., - und _ sind erlaubt.");
							template.printTemplateFooter();
							return;
						}
						String fileName = m.group(1);
						File uploadedFile = new File(path, fileName);
						if (fileName.toLowerCase().endsWith(".java")) {
							uploadedFile = File.createTempFile("upload", null, path);
						}
						try {
							item.write(uploadedFile);
						} catch (Exception e) {
							e.printStackTrace();
						}
						if (fileName.toLowerCase().endsWith(".java")) {
							NormalizerIf stripComments = new StripCommentsNormalizer();
							StringBuffer javaFileContents = stripComments.normalize(Util.loadFile(uploadedFile));
							Pattern packagePattern = Pattern.compile(".*package\\s+([a-zA-Z$]([a-zA-Z0-9_$]|\\.[a-zA-Z0-9_$])*)\\s*;.*", Pattern.DOTALL);
							Matcher packageMatcher = packagePattern.matcher(javaFileContents);
							if (packageMatcher.matches()) {
								String packageName = packageMatcher.group(1).replace(".", System.getProperty("file.separator"));
								File packageDirectory = new File(path, packageName);
								packageDirectory.mkdirs();
								uploadedFile.renameTo(new File(packageDirectory, fileName));
							} else {
								uploadedFile.renameTo(new File(path, fileName));
							}
						}
					}
					submission.setLastModified(new Date());
					submissionDAO.saveSubmission(submission);
					Util.recursiveDeleteEmptyDirectories(path);
					tx.commit();
					new LogDAO(session).createLogEntry(studentParticipation.getUser(), null, task, LogAction.UPLOAD, null, null);
					response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
					return;
				}
			}
			tx.rollback();
			out.println("Problem: Keine Abgabedaten gefunden.");
		} else if (request.getParameter("textsolution") != null) {
			File uploadedFile = new File(path, "textloesung.txt");
			FileWriter fileWriter = new FileWriter(uploadedFile);
			fileWriter.write(request.getParameter("textsolution"));
			fileWriter.flush();
			fileWriter.close();
			submission.setLastModified(new Date());
			submissionDAO.saveSubmission(submission);
			tx.commit();
			response.sendRedirect(response.encodeRedirectURL("ShowTask?taskid=" + task.getTaskid()));
		} else {
			tx.rollback();
			out.println("Problem: Keine Abgabedaten gefunden.");
		}
	}


Input:
    public <T> boolean that(T actual, Matcher<? super T> matcher, String category, String reason, Object... messageParameters) {
        if (!matcher.matches(actual)) {
        	if (reason != null) {
        		errors.add(new I18nMessage(category, reason, messageParameters));
            } else {
                Description description = new ResourceBundleDescription();
                description.appendDescriptionOf(matcher);
                errors.add(new I18nMessage(description.toString(), category));
            }
            return false;
        }
        return true;
    }

Output:
    public <T> boolean that(T actual, Matcher<? super T> matcher, String category, String reason, Object... messageParameters) {
        if (!matcher.matches(actual)) {
        	if (reason != null) {
        		errors.add(new I18nMessage(category, reason, messageParameters));
            } else {
                Description description = new ResourceBundleDescription();
                description.appendDescriptionOf(matcher);
                errors.add(new I18nMessage(category, description.toString(), actual));
            }
            return false;
        }
        return true;
    }


Input:
   public Environment()
      throws IOException
   {
      String command = null;
      String OS = System.getProperty("os.name");
      String lowerOs = OS.toLowerCase();
      if (OS.indexOf("Windows") > -1) {
         command = "cmd /C set";
      } else if (OS.indexOf("ix") > -1 || OS.indexOf("inux") > -1) {
         command = "env";
      } else if(lowerOs.startsWith("mac os x")) {
         command = "env";
      } else {
      }
      if (command == null) {
         throw new RuntimeException("Operating system " + OS
            + " not supported by this class");
      }
      Process pid = Runtime.getRuntime().exec(command);
      BufferedReader in =
         new BufferedReader(
         new InputStreamReader(
         pid.getInputStream()));
      while(true) {
         String line = in.readLine();
         if (line == null)
            break;
         int p = line.indexOf("=");
         if (p != -1) {
            String name = line.substring(0, p);
            String value = line.substring(p+1);
            setProperty(name, value);
         }
      }
      in.close();
      try {
         pid.waitFor();
      }
      catch (InterruptedException e) {
         throw new IOException(e.getMessage());
      }
   }

Output:
   public Environment()
      throws IOException
   {
      String command = null;
      String OS = System.getProperty("os.name");
      String lowerOs = OS.toLowerCase();
      if (OS.indexOf("Windows") > -1) {
         command = "cmd /C set";
      } else if (lowerOs.indexOf("ix") > -1 || lowerOs.indexOf("linux") > -1
        || lowerOs.indexOf("freebsd") > -1
        || lowerOs.indexOf("sunos") > -1 || lowerOs.indexOf("solaris") > -1
        || lowerOs.indexOf("hp-ux") > -1) {
         command = "env";
      } else if(lowerOs.startsWith("mac os x")) {
         command = "env";
      } else {
      }
      if (command == null) {
         throw new RuntimeException("Operating system " + OS
            + " not supported by this class");
      }
      Process pid = Runtime.getRuntime().exec(command);
      BufferedReader in =
         new BufferedReader(
         new InputStreamReader(
         pid.getInputStream()));
      while(true) {
         String line = in.readLine();
         if (line == null)
            break;
         int p = line.indexOf("=");
         if (p != -1) {
            String name = line.substring(0, p);
            String value = line.substring(p+1);
            setProperty(name, value);
         }
      }
      in.close();
      try {
         pid.waitFor();
      }
      catch (InterruptedException e) {
         throw new IOException(e.getMessage());
      }
   }


Input:
    protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException {
        try {
            String urlStr = url.toString();
            if (urlStr.startsWith("http://localhost") || urlStr.contains("/selenium-server/")) {
                return super.proxyPlainTextRequest(url, pathInContext, pathParams, request, response);
            }
            if (urlStr.startsWith("https://sb-ssl.google.com:443/safebrowsing")
                    || urlStr.startsWith("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml")
                    || urlStr.startsWith("http://fxfeeds.mozilla.com/firefox/headlines.xml")
                    || urlStr.startsWith("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml")
                    || urlStr.startsWith("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml")) {
                request.setHandled(true);
                return -1;
            }
            if (httpClient == null) {
                request.setHandled(true);
                return -1;
            }
            BrowserMobHttpRequest httpReq = null;
            if ("GET".equals(request.getMethod())) {
                httpReq = httpClient.newGet(urlStr);
            } else if ("POST".equals(request.getMethod())) {
                httpReq = httpClient.newPost(urlStr);
            } else if ("PUT".equals(request.getMethod())) {
                httpReq = httpClient.newPut(urlStr);
            } else if ("DELETE".equals(request.getMethod())) {
                httpReq = httpClient.newDelete(urlStr);
            } else if ("OPTIONS".equals(request.getMethod())) {
                httpReq = httpClient.newOptions(urlStr);
            } else if ("HEAD".equals(request.getMethod())) {
                httpReq = httpClient.newHead(urlStr);
            } else {
                LOG.warn("Unexpected request method %s, giving up", request.getMethod());
                request.setHandled(true);
                return -1;
            }
            boolean isGet = "GET".equals(request.getMethod());
            boolean hasContent = false;
            Enumeration enm = request.getFieldNames();
            long contentLength = 0;
            while (enm.hasMoreElements()) {
                String hdr = (String) enm.nextElement();
                if (!isGet && HttpFields.__ContentType.equals(hdr)) {
                    hasContent = true;
                }
                if (!isGet && HttpFields.__ContentLength.equals(hdr)) {
                    contentLength = Long.parseLong(request.getField(hdr));
                    continue;
                }
                Enumeration vals = request.getFieldValues(hdr);
                while (vals.hasMoreElements()) {
                    String val = (String) vals.nextElement();
                    if (val != null) {
                        if ("User-Agent".equals(hdr)) {
                            val = updateUserAgent(val);
                        }
                        if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) {
                            continue;
                        }
                        if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                            hasContent = true;
                        }
                        httpReq.addRequestHeader(hdr, val);
                    }
                }
            }
            try {
                InputStream in = request.getInputStream();
                if (hasContent) {
                    httpReq.setRequestInputStream(in, contentLength);
                }
            } catch (Exception e) {
                LOG.fine(e.getMessage(), e);
            }
            httpReq.setOutputStream(response.getOutputStream());
            httpReq.setRequestCallback(new RequestCallback() {
                @Override
                public void handleStatusLine(StatusLine statusLine) {
                    response.setStatus(statusLine.getStatusCode());
                    response.setReason(statusLine.getReasonPhrase());
                }
                @Override
                public void handleHeaders(Header[] headers) {
                    for (Header header : headers) {
                        if (reportHeader(header)) {
                            response.addField(header.getName(), header.getValue());
                        }
                    }
                }
                @Override
                public boolean reportHeader(Header header) {
                    return !_DontProxyHeaders.containsKey(header.getName()) && !_ProxyAuthHeaders.containsKey(header.getName());
                }
                @Override
                public void reportError(Exception e) {
                    BrowserMobProxyHandler.reportError(e, url, response);
                }
            });
            BrowserMobHttpResponse httpRes = httpReq.execute();
            request.setHandled(true);
            return httpRes.getEntry().getResponse().getBodySize();
        } catch (BadURIException e) {
            LOG.info(e.getMessage());
            BrowserMobProxyHandler.reportError(e, url, response);
            return -1;
        } catch (Exception e) {
            LOG.info("Exception while proxying " + url, e);
            BrowserMobProxyHandler.reportError(e, url, response);
            return -1;
        }
    }

Output:
    protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException {
        try {
            String urlStr = url.toString();
            if (urlStr.contains("/selenium-server/")) {
                return super.proxyPlainTextRequest(url, pathInContext, pathParams, request, response);
            }
            if (urlStr.startsWith("https://sb-ssl.google.com:443/safebrowsing")
                    || urlStr.startsWith("http://en-us.fxfeeds.mozilla.com/en-US/firefox/headlines.xml")
                    || urlStr.startsWith("http://fxfeeds.mozilla.com/firefox/headlines.xml")
                    || urlStr.startsWith("http://fxfeeds.mozilla.com/en-US/firefox/headlines.xml")
                    || urlStr.startsWith("http://newsrss.bbc.co.uk/rss/newsonline_world_edition/front_page/rss.xml")) {
                request.setHandled(true);
                return -1;
            }
            if (httpClient == null) {
                request.setHandled(true);
                return -1;
            }
            BrowserMobHttpRequest httpReq = null;
            if ("GET".equals(request.getMethod())) {
                httpReq = httpClient.newGet(urlStr);
            } else if ("POST".equals(request.getMethod())) {
                httpReq = httpClient.newPost(urlStr);
            } else if ("PUT".equals(request.getMethod())) {
                httpReq = httpClient.newPut(urlStr);
            } else if ("DELETE".equals(request.getMethod())) {
                httpReq = httpClient.newDelete(urlStr);
            } else if ("OPTIONS".equals(request.getMethod())) {
                httpReq = httpClient.newOptions(urlStr);
            } else if ("HEAD".equals(request.getMethod())) {
                httpReq = httpClient.newHead(urlStr);
            } else {
                LOG.warn("Unexpected request method %s, giving up", request.getMethod());
                request.setHandled(true);
                return -1;
            }
            boolean isGet = "GET".equals(request.getMethod());
            boolean hasContent = false;
            Enumeration enm = request.getFieldNames();
            long contentLength = 0;
            while (enm.hasMoreElements()) {
                String hdr = (String) enm.nextElement();
                if (!isGet && HttpFields.__ContentType.equals(hdr)) {
                    hasContent = true;
                }
                if (!isGet && HttpFields.__ContentLength.equals(hdr)) {
                    contentLength = Long.parseLong(request.getField(hdr));
                    continue;
                }
                Enumeration vals = request.getFieldValues(hdr);
                while (vals.hasMoreElements()) {
                    String val = (String) vals.nextElement();
                    if (val != null) {
                        if ("User-Agent".equals(hdr)) {
                            val = updateUserAgent(val);
                        }
                        if ("Referer".equals(hdr) && (-1 != val.indexOf("/selenium-server/"))) {
                            continue;
                        }
                        if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) {
                            hasContent = true;
                        }
                        httpReq.addRequestHeader(hdr, val);
                    }
                }
            }
            try {
                InputStream in = request.getInputStream();
                if (hasContent) {
                    httpReq.setRequestInputStream(in, contentLength);
                }
            } catch (Exception e) {
                LOG.fine(e.getMessage(), e);
            }
            httpReq.setOutputStream(response.getOutputStream());
            httpReq.setRequestCallback(new RequestCallback() {
                @Override
                public void handleStatusLine(StatusLine statusLine) {
                    response.setStatus(statusLine.getStatusCode());
                    response.setReason(statusLine.getReasonPhrase());
                }
                @Override
                public void handleHeaders(Header[] headers) {
                    for (Header header : headers) {
                        if (reportHeader(header)) {
                            response.addField(header.getName(), header.getValue());
                        }
                    }
                }
                @Override
                public boolean reportHeader(Header header) {
                    return !_DontProxyHeaders.containsKey(header.getName()) && !_ProxyAuthHeaders.containsKey(header.getName());
                }
                @Override
                public void reportError(Exception e) {
                    BrowserMobProxyHandler.reportError(e, url, response);
                }
            });
            BrowserMobHttpResponse httpRes = httpReq.execute();
            request.setHandled(true);
            return httpRes.getEntry().getResponse().getBodySize();
        } catch (BadURIException e) {
            LOG.info(e.getMessage());
            BrowserMobProxyHandler.reportError(e, url, response);
            return -1;
        } catch (Exception e) {
            LOG.info("Exception while proxying " + url, e);
            BrowserMobProxyHandler.reportError(e, url, response);
            return -1;
        }
    }


Input:
	public void dispatchDraw(Canvas canvas) {
		long currentTime;
		if(startTime==0){
			startTime=SystemClock.uptimeMillis();
			currentTime=0;
		}else{
			currentTime=SystemClock.uptimeMillis()-startTime;
		}
		if(mStatus==OPENING){
			mScaleFactor=easeOut(currentTime, 3.0f, 1.0f, mAnimationDuration);
		}else if (mStatus==CLOSING){
			mScaleFactor=easeIn(currentTime, 1.0f, 3.0f, mAnimationDuration);
		}
		if(currentTime>=mAnimationDuration){
			isAnimating=false;
			if(mStatus==OPENING){
				mStatus=OPEN;
				dispatchFadingEvent(OnFadingListener.OPEN);
				clearChildrenCache();
				setChildrenDrawingCacheEnabled(true);
			}else if(mStatus==CLOSING){
				mStatus=CLOSED;
				dispatchFadingEvent(OnFadingListener.CLOSE);
			}
		}
		shouldDrawLabels=(currentTime>mAnimationDuration/2 && mStatus==OPENING)||(currentTime<mAnimationDuration/2 && mStatus==CLOSING);
		int alpha=255;
		if(isAnimating){
			float porcentajeScale=1.0f-((mScaleFactor-1)/3.0f);
			if(porcentajeScale>=0.9f)porcentajeScale=1;
			if(porcentajeScale<0)porcentajeScale=0;
			alpha=(int)(porcentajeScale*255);
			dispatchFadingAlphaEvent(alpha);
		}
		mPaint.setAlpha(alpha);
		if(mStatus!=CLOSED){
			super.dispatchDraw(canvas);
		}
	}

Output:
	public void dispatchDraw(Canvas canvas) {
		long currentTime;
		if(startTime==0){
			startTime=SystemClock.uptimeMillis();
			currentTime=0;
		}else{
			currentTime=SystemClock.uptimeMillis()-startTime;
		}
		if(mStatus==OPENING){
			mScaleFactor=easeOut(currentTime, 3.0f, 1.0f, mAnimationDuration);
		}else if (mStatus==CLOSING){
			mScaleFactor=easeIn(currentTime, 1.0f, 3.0f, mAnimationDuration);
		}
		if(currentTime>=mAnimationDuration){
			isAnimating=false;
			if(mStatus==OPENING){
				mStatus=OPEN;
				dispatchFadingEvent(OnFadingListener.OPEN);
				clearChildrenCache();
				setChildrenDrawingCacheEnabled(true);
			}else if(mStatus==CLOSING){
				mStatus=CLOSED;
				dispatchFadingEvent(OnFadingListener.CLOSE);
			}
		}
		shouldDrawLabels=(currentTime>mAnimationDuration/2 && mStatus==OPENING)||(currentTime<mAnimationDuration/2 && mStatus==CLOSING);
		int alpha=255;
		if(isAnimating){
			float porcentajeScale=1.0f-((mScaleFactor-1)/3.0f);
			if(porcentajeScale>=0.9f)porcentajeScale=1;
			if(porcentajeScale<0)porcentajeScale=0;
			alpha=(int)(porcentajeScale*255);
		}
		dispatchFadingAlphaEvent(alpha);
		mPaint.setAlpha(alpha);
		if(mStatus!=CLOSED){
			super.dispatchDraw(canvas);
		}
	}