auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public List<Predicate<Entity>> createPredicates(Map<String, String> arguments, String mainSelector, ICommandSender sender, Vec3d position) { List<Predicate<Entity>> predicates = Lists.newArrayList(); String health = arguments.get("forge:min_health"); if (health != null) { final boolean invert = health.startsWith("!"); if (invert) { health = health.substring(1); } try { final int value = Integer.parseInt(health); predicates.add(new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { if (!(input instanceof EntityLivingBase)) return false; boolean health = ((EntityLivingBase) input).getHealth() >= value; return invert && !health || !invert && health; } }); } catch (NumberFormatException e) { sender.sendMessage(new TextComponentString("Entity selector 'forge:min_health' has to be an integer")); } } return predicates; }

Target:
public List<Predicate<Entity>> createPredicates(Map<String, String> arguments, String mainSelector, ICommandSender sender, Vec3d position) { String health = arguments.get("forge:min_health"); if (health != null) { final boolean invert = health.startsWith("!"); if (invert) { health = health.substring(1); } try { final int value = Integer.parseInt(health); return Collections.<Predicate<Entity>>singletonList(new Predicate<Entity>() { @Override public boolean apply(@Nullable Entity input) { if (!(input instanceof EntityLivingBase)) return false; return (((EntityLivingBase) input).getHealth() >= value)!=invert; } }); } catch (NumberFormatException e) { sender.sendMessage(new TextComponentString("Entity selector 'forge:min_health' has to be an integer")); } } return Collections.emptyList(); }
Source:
protected Application configure() { HiveConf conf = new HiveConf(); conf.addResource(Thread.currentThread().getContextClassLoader().getResource("grillserver-default.xml")); conf.addResource(Thread.currentThread().getContextClassLoader().getResource("grill-site.xml")); GrillApplication.init(conf); return new GrillApplication(); }

Target:
protected Application configure() { return new GrillApplication(); }
Source:
public String getFirstName() { return mFirstName; }

Target:
public String getFirstName() { return StringUtils.notNullStr(mFirstName); }
Source:
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { String name = desc.getName(); return Class.forName(name, false, classLoader); } catch (ClassNotFoundException e) { try { return super.resolveClass(desc); } catch (ClassNotFoundException e1) { try { return BeanManagerImpl.class.getClassLoader().loadClass(desc.getName()); } catch (ClassNotFoundException cnfe) { if (lastResortClassLoader != null) { return lastResortClassLoader.loadClass(desc.getName()); } else { throw new ClassNotFoundException(cnfe.getMessage(), cnfe.getCause()); } } } } }

Target:
protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { try { String name = desc.getName(); return Class.forName(name, false, tccl); } catch (ClassNotFoundException e) { try { return super.resolveClass(desc); } catch (ClassNotFoundException e1) { try { return BeanManagerImpl.class.getClassLoader().loadClass(desc.getName()); } catch (ClassNotFoundException cnfe) { if (optionalClassLoader != null) { return optionalClassLoader.loadClass(desc.getName()); } else { throw cnfe; } } } } }
Source:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { AlterPartitionMessage msg = deserializer.getAlterPartitionMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; Map<String, String> partSpec = new LinkedHashMap<>(); try { org.apache.hadoop.hive.metastore.api.Table tblObj = msg.getTableObj(); Iterator<String> afterIterator = msg.getPtnObjAfter().getValuesIterator(); for (FieldSchema fs : tblObj.getPartitionKeys()) { partSpec.put(fs.getName(), afterIterator.next()); } } catch (Exception e) { if (!(e instanceof SemanticException)) { throw new SemanticException("Error reading message members", e); } else { throw (SemanticException) e; } } TruncateTableDesc truncateTableDesc = new TruncateTableDesc(actualDbName + "." + actualTblName, partSpec, eventOnlyReplicationSpec(context)); Task<DDLWork> truncatePtnTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, truncateTableDesc), context.hiveConf); context.log.debug("Added truncate ptn task : {}:{}", truncatePtnTask.getId(), truncateTableDesc.getTableName()); databasesUpdated.put(actualDbName, context.dmd.getEventTo()); tablesUpdated.put(actualDbName + "." + actualTblName, context.dmd.getEventTo()); return Collections.singletonList(truncatePtnTask); }

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { AlterPartitionMessage msg = deserializer.getAlterPartitionMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; Map<String, String> partSpec = new LinkedHashMap<>(); try { org.apache.hadoop.hive.metastore.api.Table tblObj = msg.getTableObj(); Iterator<String> afterIterator = msg.getPtnObjAfter().getValuesIterator(); for (FieldSchema fs : tblObj.getPartitionKeys()) { partSpec.put(fs.getName(), afterIterator.next()); } } catch (Exception e) { if (!(e instanceof SemanticException)) { throw new SemanticException("Error reading message members", e); } else { throw (SemanticException) e; } } TruncateTableDesc truncateTableDesc = new TruncateTableDesc( actualDbName + "." + actualTblName, partSpec, context.eventOnlyReplicationSpec()); Task<DDLWork> truncatePtnTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, truncateTableDesc), context.hiveConf); context.log.debug("Added truncate ptn task : {}:{}", truncatePtnTask.getId(), truncateTableDesc.getTableName()); databasesUpdated.put(actualDbName, context.dmd.getEventTo()); tablesUpdated.put(actualDbName + "." + actualTblName, context.dmd.getEventTo()); return Collections.singletonList(truncatePtnTask); }
Source:
public void importProjectFromSVN(Object rootLocation, String[] projectLocations) { try { if (rootLocation instanceof IRepositoryResource) { } else { rootLocation = createRepositoryLocation(rootLocation.toString(), null); } List<IRepositoryResource> doCeckout_tmp = new ArrayList<IRepositoryResource>(); for (String location : projectLocations) { doCeckout_tmp.add(getRepositoryProjectResource((IRepositoryLocation) rootLocation, location)); } final IRepositoryResource[] doCeckout = doCeckout_tmp.toArray(new IRepositoryResource[] {}); Display.getDefault().syncExec(new Runnable() { @Override public void run() { Shell sh = Display.getDefault().getActiveShell(); IActionOperation op = ExtensionsManager.getInstance().getCurrentCheckoutFactory() .getCheckoutOperation(sh, doCeckout, null, true, null, SVNDepth.INFINITY, false); UIMonitorUtility.doTaskNowDefault(op, true); } }); } catch (Exception ex) { System.out.println(ex.getMessage()); } }

Target:
public void importProjectFromSVN(Object rootLocation, String[] projectLocations) { try { if (rootLocation instanceof IRepositoryResource) { } else { rootLocation = createRepositoryLocation(rootLocation.toString(), null, null); } List<IRepositoryResource> doCeckout_tmp = new ArrayList<IRepositoryResource>(); for (String location : projectLocations) { doCeckout_tmp.add(getRepositoryProjectResource((IRepositoryLocation) rootLocation, location)); } final IRepositoryResource[] doCeckout = doCeckout_tmp.toArray(new IRepositoryResource[] {}); Display.getDefault().syncExec(new Runnable() { @Override public void run() { Shell sh = Display.getDefault().getActiveShell(); IActionOperation op = ExtensionsManager.getInstance().getCurrentCheckoutFactory() .getCheckoutOperation(sh, doCeckout, null, true, null, SVNDepth.INFINITY, false); UIMonitorUtility.doTaskNowDefault(op, true); } }); } catch (Exception ex) { System.out.println(ex.getMessage()); } }
Source:
public DbUser doLogin(Map<String, Object> authResult) throws IOException, ServletException { DbUser user = null; try { String profileName = (String) authResult.get(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) authResult.get(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { InitialContext context = new InitialContext(); try { VdcLoginReturnValueBase returnValue = (VdcLoginReturnValueBase) FiltersHelper.getBackend(context).login(new LoginUserParameters( profileName, authRecord, VdcActionType.LoginUser, (AuthType) authResult.get(FiltersHelper.Constants.REQUEST_AUTH_TYPE_KEY) ) ); if (returnValue.getSucceeded()) { authResult.put( SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, returnValue.getSessionId() ); log.info("returnValue.getSessionId() = " + returnValue.getSessionId()); user = (DbUser) returnValue.getActionReturnValue(); ((EnginePrincipal) this.getIdentity()).setEngineSessionId(returnValue.getSessionId()); } } finally { context.close(); } } } catch (Exception ex) { log.error("Error in login to engine ", ex); } return user; }

Target:
public DbUser doLogin(Map<String, Object> authResult) throws IOException, ServletException { DbUser user = null; String profileName = (String) authResult.get(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) authResult.get(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { try { VdcLoginReturnValueBase returnValue = (VdcLoginReturnValueBase) BackendUtils.getBackendLocal(log).login(new LoginUserParameters( profileName, authRecord, VdcActionType.LoginUser, (AuthType) authResult.get(FiltersHelper.Constants.REQUEST_AUTH_TYPE_KEY) ) ); if (returnValue.getSucceeded()) { authResult.put( SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, returnValue.getSessionId() ); log.info("returnValue.getSessionId() = " + returnValue.getSessionId()); user = (DbUser) returnValue.getActionReturnValue(); ((EnginePrincipal) this.getIdentity()).setEngineSessionId(returnValue.getSessionId()); } } catch (Exception ex) { log.error("Error in login to engine ", ex); } } return user; }
Source:
public List<Class> getSupportedTypes() { return new ArrayList<>(Arrays.asList(boolean.class, Boolean.class)); }

Target:
public List<Class> getSupportedTypes() { return Arrays.asList(boolean.class, Boolean.class); }
Source:
public String[] getColumnTexts(@NonNull ITimeGraphEntry entry) { String[] texts = new String[fColumns.length]; for (int i = 0; i < fColumns.length; i++) { texts[i] = fLabelProvider.getColumnText(entry, i); } return texts; }

Target:
public String[] getColumnTexts(@NonNull ITimeGraphEntry entry) { String[] texts = null; if (fColumns != null) { texts = new String[fColumns.length]; for (int i = 0; i < fColumns.length; i++) { texts[i] = fLabelProvider.getColumnText(entry, i); } } else { texts = new String[1]; texts[0] = entry.getName(); } return texts; }
Source:
public NodeValue getAccValue() { if ( count == 0 ) return noValuesToMedian ; if ( super.errorCount != 0 ) return null ; double[] arrDouble = new double[collection.size()]; for(int i=0; i<collection.size(); i++){ arrDouble[i] = Double.parseDouble(collection.get(i).toString()); } System.out.println(new Median().evaluate(arrDouble)); return (NodeValue.makeDecimal((new Median().evaluate(arrDouble )))); }

Target:
public NodeValue getAccValue() { double median; if ( count == 0 ) return noValuesToMedian ; if ( super.errorCount != 0 ) return null ; int indexsize = collection.size(); double[] arrDouble = new double[indexsize]; for(int i=0; i<indexsize; i++){ arrDouble[i] = collection.get(i).getDouble(); } Arrays.sort(arrDouble); if(indexsize%2!=0) { median = arrDouble[(indexsize/2)]; }else { median = ((arrDouble[(indexsize/2)]+arrDouble[((indexsize/2)-1)])/2); } return NodeValue.makeDecimal(median); }
Source:
public void testCreateShareableSuccess() throws Exception { when(subjectIdentity.getIdentityAttribute()).thenReturn(TEST_ID_ATTR); Map<String, SortedSet<String>> attrs = ImmutableMap.of(TEST_ID_ATTR, ImmutableSortedSet.of("owner")); ShareableMetacardPreIngestPlugin wpip = makePlugin(attrs); ShareableMetacardImpl shareableMetacard = new ShareableMetacardImpl(); wpip.process(new CreateRequestImpl(shareableMetacard)); assertThat(shareableMetacard.getOwner(), is("owner")); }

Target:
public void testCreateShareableSuccess() throws Exception { when(subjectIdentity.getIdentityAttribute()).thenReturn(TEST_ID_ATTR); ShareableMetacardPreIngestPlugin plugin = makePlugin(); ShareableMetacardImpl shareableMetacard = new ShareableMetacardImpl(); shareableMetacard.setTags(Collections.singleton(WorkspaceAttributes.WORKSPACE_TAG)); plugin.process(new CreateRequestImpl(shareableMetacard)); assertThat(shareableMetacard.getOwner(), is("owner")); }
Source:
public void testSimple() { TestTransaction tx1 = new TestTransaction(env); tx1.mutate().row("row1").fam("fam1").qual("q1").set("v1"); tx1.mutate().row("row2").fam("fam1").qual("q2").set("v2"); tx1.mutate().row("row2").fam("fam2").qual("q3").set("v3"); tx1.mutate().row("row2").fam("fam2").qual("q1").set("v4"); tx1.done(); MiniAppRunner runner = new MiniAppRunner(config); runner.waitUntilFinished(); Assert.assertEquals(4, runner.scan(new String[] {})); Assert.assertEquals(1, runner.scan(new String[] {"-r", "row1"})); Assert.assertEquals(3, runner.scan(new String[] {"-r", "row2"})); Assert.assertEquals(2, runner.scan(new String[] {"-c", "fam1"})); Assert.assertEquals(1, runner.scan(new String[] {"-c", "fam1:q2"})); }

Target:
public void testSimple() { try(TypedTransaction tx1 = tl.wrap(client.newTransaction())){ tx1.mutate().row("row1").fam("ingest").qual("num").set(1); tx1.mutate().row("row2").fam("ingest").qual("num").set(1); tx1.mutate().row("row3").fam("ingest").qual("num").set(1); tx1.commit(); } Environment env = new Environment(config); MiniAppRunner runner = new MiniAppRunner(config); Assert.assertEquals(3, runner.countNotifications(env)); runner.waitUntilFinished(); Assert.assertEquals(0, runner.countNotifications(env)); Assert.assertEquals(3, runner.scan(new String[] {})); Assert.assertEquals(1, runner.scan(new String[] {"-r", "row1"})); Assert.assertEquals(1, runner.scan(new String[] {"-r", "row2"})); Assert.assertEquals(3, runner.scan(new String[] {"-c", "count"})); Assert.assertEquals(0, runner.scan(new String[] {"-c", "ingest"})); }
Source:
public Builder queryString(String queryString) { command.queryString = queryString; return builder; }

Target:
public Builder queryString(String queryString) { command.queryString = queryString; return this; }
Source:
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { WildFlyTracerFactory.registerTracer(ENV_TRACER).accept(new JaegerEnvTracerConfiguration()); TracingExtensionLogger.ROOT_LOGGER.activatingSubsystem(); context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor( SubsystemExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_OPENTRACING, new TracingDependencyProcessor() ); processorTarget.addDeploymentProcessor(SubsystemExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_MICROPROFILE_OPENTRACING, new TracingDeploymentProcessor() ); } }, OperationContext.Stage.RUNTIME); super.performBoottime(context, operation, model); }

Target:
protected void performBoottime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { WildFlyTracerFactory.registerTracer(ENV_TRACER).accept(new JaegerEnvTracerConfiguration()); TracingExtensionLogger.ROOT_LOGGER.activatingSubsystem();String defaultTracer = DEFAULT_TRACER.resolveModelAttribute(context, operation).asStringOrNull(); if (defaultTracer != null && !defaultTracer.isEmpty()) { CapabilityServiceBuilder<?> builder = context.getCapabilityServiceTarget().addCapability(DEFAULT_TRACER_CAPABILITY); final Supplier<TracerConfiguration> config = builder.requiresCapability(TRACER_CAPABILITY_NAME, TracerConfiguration.class, defaultTracer); final Consumer<TracerConfiguration> injector = builder.provides(DEFAULT_TRACER_CAPABILITY); builder.setInstance(new Service() { @Override public void start(StartContext context) throws StartException { injector.accept(config.get()); WildFlyTracerFactory.registerDefaultTracer().accept(config.get()); } @Override public void stop(StopContext context) { injector.accept(null); WildFlyTracerFactory.registerDefaultTracer().accept(config.get()); } }).setInitialMode(ServiceController.Mode.ACTIVE).install(); } context.addStep(new AbstractDeploymentChainStep() { @Override public void execute(DeploymentProcessorTarget processorTarget) { processorTarget.addDeploymentProcessor( SubsystemExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MICROPROFILE_OPENTRACING, new TracingDependencyProcessor() ); processorTarget.addDeploymentProcessor(SubsystemExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_MICROPROFILE_OPENTRACING, new TracingDeploymentProcessor() ); } }, OperationContext.Stage.RUNTIME); }
Source:
private void copyArtifactToHistoryFolder(Path historyFolder, String fileName, String planKey, int buildId) throws Exception { URL artifactUrl = new URL(getHistoryArtifactUrl(fileName, planKey, buildId)); URLConnection uc = artifactUrl.openConnection(); InputStream inputStream = uc.getInputStream(); Files.copy(inputStream, historyFolder.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); }

Target:
private void copyArtifactToHistoryFolder(Path historyFolder, String fileName, String planKey, int buildId) { try (InputStream inputStream = getArtifactContent(fileName, planKey, buildId)) { Files.createDirectories(historyFolder); Files.copy(inputStream, historyFolder.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { LOGGER.error("Could not copy file {}", fileName); } }
Source:
void delete() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == DELETING || status == DELETED) { Logger.v(BATCH + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + " abort delete batch"); return; } downloadBatchStatus.markAsDeleting(); Logger.v("delete request for " + BATCH + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + ", should be deleting"); notifyCallback(callback, downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.delete(); } deleteDownloadDirs(); if (status == PAUSED || status == DOWNLOADED || status == WAITING_FOR_NETWORK || status == ERROR) { Logger.v("delete async paused or downloaded " + BATCH + downloadBatchStatus.getDownloadBatchId().rawId()); downloadsBatchPersistence.deleteAsync(downloadBatchStatus, downloadBatchId -> { Logger.v("delete paused or downloaded mark as deleted: " + downloadBatchId.rawId()); downloadBatchStatus.markAsDeleted(); notifyCallback(callback, downloadBatchStatus); }); } Logger.v("delete request for " + BATCH + "end " + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + ", should be deleting"); }

Target:
void delete() { DownloadBatchStatus.Status status = downloadBatchStatus.status(); if (status == DELETING || status == DELETED) { Logger.v(BATCH + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + " abort delete batch"); return; } downloadBatchStatus.markAsDeleting(); Logger.v("delete request for " + BATCH + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + ", should be deleting"); notifyCallback(callback, downloadBatchStatus); for (DownloadFile downloadFile : downloadFiles) { downloadFile.delete(); } deleteDownloadDirectories(); if (status == PAUSED || status == DOWNLOADED || status == WAITING_FOR_NETWORK || status == ERROR) { Logger.v("delete async paused or downloaded " + BATCH + downloadBatchStatus.getDownloadBatchId().rawId()); downloadsBatchPersistence.deleteAsync(downloadBatchStatus, downloadBatchId -> { Logger.v("delete paused or downloaded mark as deleted: " + downloadBatchId.rawId()); downloadBatchStatus.markAsDeleted(); notifyCallback(callback, downloadBatchStatus); }); } Logger.v("delete request for " + BATCH + "end " + downloadBatchStatus.getDownloadBatchId().rawId() + STATUS + status + ", should be deleting"); }
Source:
private void validateSections(List<StudentAttributes> studentList, String courseId) throws EntityDoesNotExistException, EnrollException { List<StudentAttributes> mergedList = new ArrayList<StudentAttributes>(); List<StudentAttributes> studentsInCourse = getStudentsForCourse(courseId); for(StudentAttributes student : studentList) { mergedList.add(student); } for(StudentAttributes student : studentsInCourse) { if(!isInEnrollList(student, mergedList)){ mergedList.add(student); } } if(mergedList.size() < 2){ return; } Collections.sort(mergedList, new Comparator<StudentAttributes>() { @Override public int compare(StudentAttributes o1, StudentAttributes o2) { return o1.team.compareTo(o2.team); } }); String errorMessage = ""; List<String> invalidTeamList = new ArrayList<String>(); for(int i = 1; i < mergedList.size(); i++){ StudentAttributes currentStudent = mergedList.get(i); StudentAttributes previousStudent = mergedList.get(i-1); if(currentStudent.team.equals(previousStudent.team) && !currentStudent.section.equals(previousStudent.section)){ if(!invalidTeamList.contains(currentStudent.team)){ invalidTeamList.add(currentStudent.team); } } } for(String team : invalidTeamList){ errorMessage += "Cannot put team \"" + team + "\" in 2 different sections<br>"; } if(!errorMessage.equals("")){ throw new EnrollException(errorMessage); } }

Target:
public void validateSections(List<StudentAttributes> studentList, String courseId) throws EntityDoesNotExistException, EnrollException { List<StudentAttributes> mergedList = new ArrayList<StudentAttributes>(); List<StudentAttributes> studentsInCourse = getStudentsForCourse(courseId); for(StudentAttributes student : studentList) { mergedList.add(student); } for(StudentAttributes student : studentsInCourse) { if(!isInEnrollList(student, mergedList)){ mergedList.add(student); } } if(mergedList.size() < 2){ return; } Collections.sort(mergedList, new Comparator<StudentAttributes>() { @Override public int compare(StudentAttributes o1, StudentAttributes o2) { return o1.team.compareTo(o2.team); } }); String errorMessage = ""; List<String> invalidTeamList = new ArrayList<String>(); for(int i = 1; i < mergedList.size(); i++){ StudentAttributes currentStudent = mergedList.get(i); StudentAttributes previousStudent = mergedList.get(i-1); if(currentStudent.team.equals(previousStudent.team) && !currentStudent.section.equals(previousStudent.section)){ if(!invalidTeamList.contains(currentStudent.team)){ invalidTeamList.add(currentStudent.team); } } } for(String team : invalidTeamList){ errorMessage += String.format(Const.StatusMessages.TEAM_INVALID_SECTION_EDIT, team); } if(!errorMessage.equals("")){ throw new EnrollException(errorMessage); } }
Source:
public Message read() { assert hasNext(); if (nMessages++ % checkMessagesPerSecond == 0) { RateLimitUtil.acquire(checkMessagesPerSecond); } MessageAndMetadata<byte[], byte[]> kafkaMessage = mIterator.next(); Message message = new Message(kafkaMessage.topic(), kafkaMessage.partition(), kafkaMessage.offset(), kafkaMessage.message()); TopicPartition topicPartition = new TopicPartition(message.getTopic(), message.getKafkaPartition()); updateAccessTime(topicPartition); long committedOffsetCount = mOffsetTracker.getTrueCommittedOffsetCount(topicPartition); LOG.debug("read message {}", message); if (nMessages % checkMessagesPerSecond == 0) { exportStats(); } if (message.getOffset() < committedOffsetCount) { LOG.debug("skipping message message " + message + " because its offset precedes " + "committed offset count " + committedOffsetCount); return null; } return message; }

Target:
public Message read() { assert hasNext(); mNMessages = (mNMessages + 1) % mCheckMessagesPerSecond; if (mNMessages % mCheckMessagesPerSecond == 0) { RateLimitUtil.acquire(mCheckMessagesPerSecond); } MessageAndMetadata<byte[], byte[]> kafkaMessage = mIterator.next(); Message message = new Message(kafkaMessage.topic(), kafkaMessage.partition(), kafkaMessage.offset(), kafkaMessage.message()); TopicPartition topicPartition = new TopicPartition(message.getTopic(), message.getKafkaPartition()); updateAccessTime(topicPartition); long committedOffsetCount = mOffsetTracker.getTrueCommittedOffsetCount(topicPartition); LOG.debug("read message {}", message); if (mNMessages % mCheckMessagesPerSecond == 0) { exportStats(); } if (message.getOffset() < committedOffsetCount) { LOG.debug("skipping message because its offset precedes committed offset count {}", message, committedOffsetCount); return null; } return message; }
Source:
public TaskAdded handle(AddTask cmd, CommandContext ctx) { return Given.EventMessage.taskAddedMsg(cmd.getProjectId()); }

Target:
public TaskAdded handle(AddTask cmd, CommandContext ctx) { return Given.EventMessage.taskAdded(cmd.getProjectId()); }
Source:
public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryMimeType = (String) in.getHeader(CdrBinaryMimeType); String binaryPath = (String) in.getHeader(CdrBinaryPath); String derivativePath = binaryPath + fileSuffix; String text = extractText(binaryPath); writeFile(derivativePath, text); InputStream binaryStream = new FileInputStream(derivativePath); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, derivativePath, binaryMimeType, PcdmUse.ExtractedText); log.info("Adding derivative for from {}", binaryUri, derivativePath); }

Target:
public void process(Exchange exchange) throws Exception { final Message in = exchange.getIn(); String binaryUri = (String) in.getHeader(FCREPO_URI); String binaryMimeType = (String) in.getHeader(CdrBinaryMimeType); String binaryPath = (String) in.getHeader(CdrBinaryPath); String text = extractText(binaryPath); InputStream binaryStream = new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); BinaryObject binary = repository.getBinary(PIDs.get(binaryUri)); FileObject parent = (FileObject) binary.getParent(); parent.addDerivative(slug, binaryStream, fileName, binaryMimeType, PcdmUse.ExtractedText); log.info("Adding derivative for from {}", binaryUri, fileName); }
Source:
private void activateDisplayPreferences() { showOwnOffersInOfferBook.setSelected(preferences.isShowOwnOffersInOfferBook()); showOwnOffersInOfferBook.setOnAction(e -> preferences.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook.isSelected())); useAnimations.setSelected(preferences.isUseAnimations()); useAnimations.setOnAction(e -> preferences.setUseAnimations(useAnimations.isSelected())); useDarkMode.setSelected(preferences.getCssTheme() == 1); useDarkMode.setOnAction(e -> preferences.setCssTheme(useDarkMode.isSelected())); sortMarketCurrenciesNumerically.setSelected(preferences.isSortMarketCurrenciesNumerically()); sortMarketCurrenciesNumerically.setOnAction(e -> preferences.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically.isSelected())); resetDontShowAgainButton.setOnAction(e -> preferences.resetDontShowAgain()); if (displayStandbyModeFeature) { avoidStandbyMode.setSelected(!preferences.isUseStandbyMode()); avoidStandbyMode.setOnAction(e -> preferences.setUseStandbyMode(!avoidStandbyMode.isSelected())); } }

Target:
private void activateDisplayPreferences() { showOwnOffersInOfferBook.setSelected(preferences.isShowOwnOffersInOfferBook()); showOwnOffersInOfferBook.setOnAction(e -> preferences.setShowOwnOffersInOfferBook(showOwnOffersInOfferBook.isSelected())); useAnimations.setSelected(preferences.isUseAnimations()); useAnimations.setOnAction(e -> preferences.setUseAnimations(useAnimations.isSelected())); useDarkMode.setSelected(preferences.getCssTheme() == 1); useDarkMode.setOnAction(e -> preferences.setCssTheme(useDarkMode.isSelected())); sortMarketCurrenciesNumerically.setSelected(preferences.isSortMarketCurrenciesNumerically()); sortMarketCurrenciesNumerically.setOnAction(e -> preferences.setSortMarketCurrenciesNumerically(sortMarketCurrenciesNumerically.isSelected())); resetDontShowAgainButton.setOnAction(e -> preferences.resetDontShowAgain()); if (displayStandbyModeFeature) { avoidStandbyMode.setSelected(!preferences.isUseStandbyMode()); avoidStandbyMode.setOnAction(e -> preferences.setUseStandbyMode(!avoidStandbyMode.isSelected())); } else { preferences.setUseStandbyMode(false); } }
Source:
public void testWriteMultipleStringDataLinesThroughUDP() { String measurement = TestUtils.getRandomMeasurement(); this.influxDB.write(UDP_PORT, Arrays.asList( measurement + ",atag=test1 idle=100,usertime=10,system=1", measurement + ",atag=test2 idle=200,usertime=20,system=2", measurement + ",atag=test3 idle=300,usertime=30,system=3" )); Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); Query query = new Query("SELECT * FROM " + measurement + " GROUP BY *", UDP_DATABASE); QueryResult result = this.influxDB.query(query); Assertions.assertEquals(3, result.getResults().get(0).getSeries().size()); Assertions.assertEquals(result.getResults().get(0).getSeries().get(0).getTags().get("atag"), "test1"); Assertions.assertEquals(result.getResults().get(0).getSeries().get(1).getTags().get("atag"), "test2"); Assertions.assertEquals(result.getResults().get(0).getSeries().get(2).getTags().get("atag"), "test3"); }

Target:
public void testWriteMultipleStringDataLinesThroughUDP() { String measurement = TestUtils.getRandomMeasurement(); this.influxDB.write(UDP_PORT, Arrays.asList( measurement + ",atag=test1 idle=100,usertime=10,system=1", measurement + ",atag=test2 idle=200,usertime=20,system=2", measurement + ",atag=test3 idle=300,usertime=30,system=3" )); Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); Query query = new Query("SELECT * FROM " + measurement + " GROUP BY *", UDP_DATABASE); QueryResult result = this.influxDB.query(query); Assertions.assertEquals(3, result.getResults().get(0).getSeries().size()); Assertions.assertEquals("test1", result.getResults().get(0).getSeries().get(0).getTags().get("atag")); Assertions.assertEquals("test2", result.getResults().get(0).getSeries().get(1).getTags().get("atag")); Assertions.assertEquals("test3", result.getResults().get(0).getSeries().get(2).getTags().get("atag")); }
Source:
protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.d(TAG, "onNewIntent called"); requested = intent.getData(); if (requested == null) { Log.e(TAG, "Got null intent data in onNewIntent()"); return; } if (bound == null) { Log.e(TAG, "We're not bound in onNewIntent()"); return; } TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment()); int requestedIndex = 0; synchronized (pager) { if (requestedBridge == null) { try { Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s)," + "so creating one now", requested.toString(), requested.getFragment())); requestedBridge = bound.openConnection(requested); } catch (Exception e) { Log.e(TAG, "Problem while trying to create new requested bridge from URI", e); return; } adapter.notifyDataSetChanged(); requestedIndex = adapter.getCount(); } else { final int flipIndex = bound.getBridges().indexOf(requestedBridge); if (flipIndex > requestedIndex) { requestedIndex = flipIndex; } } pager.setCurrentItem(requestedIndex); } }

Target:
protected void onNewIntent(Intent intent) { super.onNewIntent(intent); Log.d(TAG, "onNewIntent called"); requested = intent.getData(); if (requested == null) { Log.e(TAG, "Got null intent data in onNewIntent()"); return; } if (bound == null) { Log.e(TAG, "We're not bound in onNewIntent()"); return; } TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment()); int requestedIndex = 0; synchronized (pager) { if (requestedBridge == null) { try { Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s)," + "so creating one now", requested.toString(), requested.getFragment())); requestedBridge = bound.openConnection(requested); } catch (Exception e) { Log.e(TAG, "Problem while trying to create new requested bridge from URI", e); return; } adapter.notifyDataSetChanged(); requestedIndex = adapter.getCount(); } else { final int flipIndex = bound.getBridges().indexOf(requestedBridge); if (flipIndex > requestedIndex) { requestedIndex = flipIndex; } } setDisplayedTerminal(requestedIndex); } }
Source:
public void dispose() { this.h.removeMessages(EVENT_DTMF_DONE); this.h.removeMessages(EVENT_PAUSE_DONE); this.h.removeMessages(EVENT_NEXT_POST_DIAL); this.parent.dispose(); this.h = null; this.owner = null; this.parent = null; }

Target:
public void dispose() { }
Source:
public void setUp() throws Exception { FileUtils.forceMkdir(taskStoreDir); Mockito.when(jobsClientMock.getJobStatus(Mockito.any())) .thenReturn(JobStatus.STOPPED); Task task = new Task("localHost", "test-task", 0, new ArrayList<>(), ImmutableList.of("test-store")); Mockito.when(jobsClientMock.getTasks(Mockito.any())) .thenReturn(ImmutableList.of(task)); localStoreMonitor = new LocalStoreMonitor(new LocalStoreMonitorConfig(new MapConfig(config)), new LocalStoreMonitorMetrics("TestMonitorName", new NoOpMetricsRegistry()), jobsClientMock); }

Target:
public void setUp() throws Exception { FileUtils.forceMkdir(taskStoreDir); taskStoreSize = taskStoreDir.getTotalSpace(); Mockito.when(jobsClientMock.getJobStatus(Mockito.any())) .thenReturn(JobStatus.STOPPED); Task task = new Task("localHost", "test-task", 0, new ArrayList<>(), ImmutableList.of("test-store")); Mockito.when(jobsClientMock.getTasks(Mockito.any())) .thenReturn(ImmutableList.of(task)); localStoreMonitorMetrics = new LocalStoreMonitorMetrics("TestMonitorName", new NoOpMetricsRegistry()); localStoreMonitor = new LocalStoreMonitor(new LocalStoreMonitorConfig(new MapConfig(config)), localStoreMonitorMetrics, jobsClientMock); }
Source:
public static void main(String[] args) { XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE); try { myDevice.connect(); } catch (XBeeException e) { e.printStackTrace(); } catch (InvalidOperatingModeException e) { e.printStackTrace(); } myDevice.startlisteningForSerialData(new MySerialDataReceiveListener()); }

Target:
public static void main(String[] args) { XBeeDevice myDevice = new XBeeDevice(PORT, BAUD_RATE); try { myDevice.open(); } catch (XBeeException e) { e.printStackTrace(); } catch (InvalidOperatingModeException e) { e.printStackTrace(); } myDevice.startListeningForSerialData(new MySerialDataReceiveListener()); }
Source:
public void checkOffsetsIncludeWeekends() { Map<LocalDate, Double> map = ImmutableMap.<LocalDate, Double>builder() .put(dt(2014, 12, 26), 14d) .put(dt(2014, 12, 29), 13d) .put(dt(2014, 12, 30), 12d) .put(dt(2014, 12, 31), 11d) .put(dt(2015, 1, 2), 11d) .put(dt(2015, 1, 5), 12d) .put(dt(2015, 1, 6), 13d) .put(dt(2015, 1, 7), 14d) .build(); LocalDateDoubleTimeSeries ts = LocalDateDoubleTimeSeries.builder().putAll(map).build(); assertThat(ts.get(dt(2014, 12, 26))).hasValue(14d); assertThat(ts.get(dt(2014, 12, 27))).isEqualTo(OptionalDouble.empty()); assertThat(ts.get(dt(2014, 12, 28))).isEqualTo(OptionalDouble.empty()); assertThat(ts.get(dt(2014, 12, 29))).hasValue(13d); assertThat(ts.get(dt(2014, 12, 30))).hasValue(12d); assertThat(ts.get(dt(2014, 12, 31))).hasValue(11d); assertThat(ts.get(dt(2015, 1, 1))).isEqualTo(OptionalDouble.empty()); assertThat(ts.get(dt(2015, 1, 2))).hasValue(11d); assertThat(ts.get(dt(2015, 1, 3))).isEqualTo(OptionalDouble.empty()); assertThat(ts.get(dt(2015, 1, 4))).isEqualTo(OptionalDouble.empty()); assertThat(ts.get(dt(2015, 1, 5))).hasValue(12d); assertThat(ts.get(dt(2015, 1, 6))).hasValue(13d); assertThat(ts.get(dt(2015, 1, 7))).hasValue(14d); }

Target:
public void checkOffsetsIncludeWeekends() { Map<LocalDate, Double> map = ImmutableMap.<LocalDate, Double>builder() .put(dt(2014, 12, 26), 14d) .put(dt(2014, 12, 29), 13d) .put(dt(2014, 12, 30), 12d) .put(dt(2014, 12, 31), 11d) .put(dt(2015, 1, 2), 11d) .put(dt(2015, 1, 5), 12d) .put(dt(2015, 1, 6), 13d) .put(dt(2015, 1, 7), 14d) .build(); LocalDateDoubleTimeSeries ts = LocalDateDoubleTimeSeries.builder().putAll(map).build(); assertThat(ts.get(dt(2014, 12, 26))).hasValue(14d); assertThat(ts.get(dt(2014, 12, 27))).isEmpty(); assertThat(ts.get(dt(2014, 12, 28))).isEmpty(); assertThat(ts.get(dt(2014, 12, 29))).hasValue(13d); assertThat(ts.get(dt(2014, 12, 30))).hasValue(12d); assertThat(ts.get(dt(2014, 12, 31))).hasValue(11d); assertThat(ts.get(dt(2015, 1, 1))).isEmpty(); assertThat(ts.get(dt(2015, 1, 2))).hasValue(11d); assertThat(ts.get(dt(2015, 1, 3))).isEmpty(); assertThat(ts.get(dt(2015, 1, 4))).isEmpty(); assertThat(ts.get(dt(2015, 1, 5))).hasValue(12d); assertThat(ts.get(dt(2015, 1, 6))).hasValue(13d); assertThat(ts.get(dt(2015, 1, 7))).hasValue(14d); }
Source:
public Collection<PlannedNode> provision(Label label, int excessWorkload) { List<PlannedNode> list = new ArrayList<PlannedNode>(); final MesosLabel mesosLabel = matchSelectedLabel(mesosLabels, label); try { while (excessWorkload > 0) { final int numExecutors = Math.min(excessWorkload, mesosLabel.getMaxExecutors()); excessWorkload -= numExecutors; LOGGER.info("Provisioning Jenkins Slave on Mesos with " + numExecutors + " executors. Remaining excess workload: " + excessWorkload + " executors)"); list.add(new PlannedNode(this.getDisplayName(), Computer.threadPoolForRemoting .submit(new Callable<Node>() { public Node call() throws Exception { MesosSlave s = doProvision(numExecutors, mesosLabel); return s; } }), numExecutors)); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to create instances on Mesos", e); return Collections.emptyList(); } return list; }

Target:
public Collection<PlannedNode> provision(Label label, int excessWorkload) { List<PlannedNode> list = new ArrayList<PlannedNode>(); final MesosSlaveInfo slaveInfo = getSlaveInfo(slaveInfos, label); try { while (excessWorkload > 0) { final int numExecutors = Math.min(excessWorkload, slaveInfo.getMaxExecutors()); excessWorkload -= numExecutors; LOGGER.info("Provisioning Jenkins Slave on Mesos with " + numExecutors + " executors. Remaining excess workload: " + excessWorkload + " executors)"); list.add(new PlannedNode(this.getDisplayName(), Computer.threadPoolForRemoting .submit(new Callable<Node>() { public Node call() throws Exception { MesosSlave s = doProvision(numExecutors, slaveInfo); return s; } }), numExecutors)); } } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to create instances on Mesos", e); return Collections.emptyList(); } return list; }
Source:
public void testgenearateMappingFile() { bmutils.generateMappingFile("mongodb"); }

Target:
public void testgenearateMappingFile() { GoraBenchmarkUtils.generateMappingFile(Constants.MONGODB); GoraBenchmarkUtils.generateMappingFile(Constants.HBASE); GoraBenchmarkUtils.generateMappingFile(Constants.COUCHDB); assertTrue("Failed", fileExists(Constants.DB_MAPPING_PATH + "/" + Constants.MONGO_MAPPING_FILE)); assertTrue("Failed", fileExists(Constants.DB_MAPPING_PATH + "/" + Constants.COUCHDB_MAPPING_FILE)); assertTrue("Failed", fileExists(Constants.DB_MAPPING_PATH + "/" + Constants.HBASE_MAPPING_FILE)); }
Source:
public ClassLoader getExternalAuthenticatorsClassLoader(ClassLoader parent) { Path authenticatorsDirectory; try { authenticatorsDirectory = Paths.get( configurationResourceResolver.getConfigurationResource("strongbox.authentication.lib", "webapp/WEB-INF/lib").getURI()); } catch (FileNotFoundException e) { logger.debug(e.getMessage()); return parent; } catch (IOException e) { throw new UndeclaredThrowableException(e); } if (!Files.exists(authenticatorsDirectory)) { logger.debug("{} does not exist.", authenticatorsDirectory); return parent; } if (!Files.isDirectory(authenticatorsDirectory)) { logger.error("{} is not a directory.", authenticatorsDirectory); return parent; } final Set<Path> authenticatorsJarPaths = getAuthenticatorJarPaths(authenticatorsDirectory); if (CollectionUtils.isEmpty(authenticatorsJarPaths)) { logger.debug("{} contains 0 authenticators jar files.", authenticatorsDirectory); return parent; } return ClassLoaderFactory.urlClassLoaderFromPaths(parent, authenticatorsJarPaths); }

Target:
public ClassLoader getExternalAuthenticatorsClassLoader(ClassLoader parent) { Path authenticatorsDirectory; try { authenticatorsDirectory = Paths.get( configurationResourceResolver.getConfigurationResource("strongbox.authentication.lib", "webapp/WEB-INF/lib").getURI()); } catch (FileNotFoundException e) { logger.debug(e.getMessage()); return parent; } catch (IOException e) { throw new UndeclaredThrowableException(e); } if (!Files.exists(authenticatorsDirectory)) { logger.debug("{} does not exist.", authenticatorsDirectory); return parent; } if (!Files.isDirectory(authenticatorsDirectory)) { logger.error("{} is not a directory.", authenticatorsDirectory); return parent; } final Set<Path> authenticatorsJarPaths = getAuthenticatorJarPaths(authenticatorsDirectory); if (CollectionUtils.isEmpty(authenticatorsJarPaths)) { logger.debug("{} does not contain any authenticator jar files.", authenticatorsDirectory); return parent; } return ClassLoaderFactory.urlClassLoaderFromPaths(parent, authenticatorsJarPaths); }
Source:
private ProcessDTO convertRelatedJSONObjects(JsonObject jsonObject, ProcessDTO processDTO) throws DataException { Integer project = jsonObject.getInt("project.id"); if (project > 0) { processDTO.setProject(serviceManager.getProjectService().findById(project)); } processDTO.setBatches(convertRelatedJSONObjectToDTO(jsonObject, "batches", serviceManager.getBatchService())); processDTO.setBatchID(getBatchID(processDTO)); processDTO.setTasks(convertRelatedJSONObjectToDTO(jsonObject, "tasks", serviceManager.getTaskService())); processDTO.setImageFolderInUse(isImageFolderInUse(processDTO)); processDTO.setProgressClosed(getProgressClosed(null, processDTO)); processDTO.setProgressInProcessing(getProgressInProcessing(null, processDTO)); processDTO.setProgressOpen(getProgressOpen(null, processDTO)); processDTO.setProgressLocked(getProgressLocked(null, processDTO)); processDTO.setBlockedUser(getBlockedUser(processDTO)); processDTO.setContainsUnreachableSteps(getContainsUnreachableSteps(processDTO)); return processDTO; }

Target:
private ProcessDTO convertRelatedJSONObjects(JsonObject jsonObject, ProcessDTO processDTO) throws DataException { Integer project = jsonObject.getInt("project.id"); if (project > 0) { processDTO.setProject(serviceManager.getProjectService().findById(project)); } processDTO.setBatchID(getBatchID(processDTO)); processDTO.setTasks(convertRelatedJSONObjectToDTO(jsonObject, "tasks", serviceManager.getTaskService())); processDTO.setImageFolderInUse(isImageFolderInUse(processDTO)); processDTO.setProgressClosed(getProgressClosed(null, processDTO)); processDTO.setProgressInProcessing(getProgressInProcessing(null, processDTO)); processDTO.setProgressOpen(getProgressOpen(null, processDTO)); processDTO.setProgressLocked(getProgressLocked(null, processDTO)); processDTO.setBlockedUser(getBlockedUser(processDTO)); processDTO.setContainsUnreachableSteps(getContainsUnreachableSteps(processDTO)); return processDTO; }
Source:
public static BingTile decode(long tile) { int version = (int) (tile >>> VERSION_OFFSET) & BITS_5; if (version == 0) { return decodeV0(tile); } else { throw new IllegalArgumentException(format("Unknown Bing Tile encoding version: {}", version)); } }

Target:
public static BingTile decode(long tile) { int version = (int) (tile >>> VERSION_OFFSET) & BITS_5; if (version == 0) { return decodeV0(tile); } else { throw new IllegalArgumentException(format("Unknown Bing Tile encoding version: %s", version)); } }
Source:
protected ReplicationUser(AuthConfig authConfig, @Assisted Set<AccountGroup.Id> authGroups) { super(AccessPath.REPLICATION, authConfig); this.effectiveGroups = authGroups; if (effectiveGroups.isEmpty()) { effectiveGroups.addAll(authConfig.getRegisteredGroups()); } }

Target:
protected ReplicationUser(AuthConfig authConfig, @Assisted Set<AccountGroup.Id> authGroups) { super(AccessPath.REPLICATION, authConfig); effectiveGroups = new HashSet<AccountGroup.Id>(authGroups); if (effectiveGroups.isEmpty()) { effectiveGroups.addAll(authConfig.getRegisteredGroups()); } effectiveGroups = Collections.unmodifiableSet(effectiveGroups); }
Source:
public List<Guid> runFilters(List<String> filterNames, List<Guid> hostIDs, Guid vmID, Map<String, String> propertiesMap) { try { if (filterNames.isEmpty()) return hostIDs; XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); Object result = client.execute(FILTER, createFilterArgs(filterNames, hostIDs, vmID, propertiesMap)); return parseFilterResults(result); } catch (XmlRpcException e) { log.error("Could not communicate with the external scheduler while filtering", e); AuditLogableBase loggable = new AuditLogableBase(); AuditLogDirector.log(loggable, AuditLogType.FAILED_TO_CONNECT_TO_SCHEDULER_PROXY); return hostIDs; } }

Target:
public List<Guid> runFilters(List<String> filterNames, List<Guid> hostIDs, Guid vmID, Map<String, String> propertiesMap) { try { if (filterNames.isEmpty()) { return hostIDs; } XmlRpcClient client = new XmlRpcClient(); client.setConfig(config); Object result = client.execute(FILTER, createFilterArgs(filterNames, hostIDs, vmID, propertiesMap)); return parseFilterResults(result); } catch (XmlRpcException e) { log.error("Could not communicate with the external scheduler while filtering", e); auditLogFailedToConnect(); return hostIDs; } }
Source:
private QueryParameters parseQuery(String query) throws Exception{ QueryParameters q = new QueryParameters(); versions = new ArrayList<String>(); if (query == null || query.equals("")) { return q; } query = query.replaceAll(" and ", "|"); query = query.replaceAll(", ", ","); query = query.replaceAll(": ", ":"); String[] tokens = query.split("\\|", -1); System.out.print(tokens.length); for (int i = 0; i < tokens.length; i++) { String[] pair = tokens[i].split(":", -1); if (pair.length != 2) { throw new Exception("Invalid format"); } String[] values = pair[1].split(",", -1); String label = pair[0]; if (label.equals("version")) { for (int j = 0; j < values.length; j++) { versions.add(values[j].replace(".", "-")); } } else if (label.equals("from")) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm"); Date d = sdf.parse(values[0] + " 00:00"); Calendar cal = Calendar.getInstance(); cal.setTime(d); cal = TimeHelper.convertToUserTimeZone(cal, - Const.SystemParams.ADMIN_TIMZE_ZONE_DOUBLE); fromDateValue = cal.getTime().getTime(); } else if (label.equals("to")) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm"); Date d = sdf.parse(values[0] + " 23:59"); Calendar cal = Calendar.getInstance(); cal.setTime(d); cal = TimeHelper.convertToUserTimeZone(cal, - Const.SystemParams.ADMIN_TIMZE_ZONE_DOUBLE); toDateValue = cal.getTime().getTime(); } else { q.add(label, values); } } return q; }

Target:
private QueryParameters parseQuery(String query) throws Exception{ QueryParameters q = new QueryParameters(); versions = new ArrayList<String>(); if (query == null || query.equals("")) { return q; } query = query.replaceAll(" and ", "|"); query = query.replaceAll(", ", ","); query = query.replaceAll(": ", ":"); String[] tokens = query.split("\\|", -1); System.out.print(tokens.length); for (int i = 0; i < tokens.length; i++) { String[] pair = tokens[i].split(":", -1); if (pair.length != 2) { throw new Exception("Invalid format"); } String[] values = pair[1].split(",", -1); String label = pair[0]; if (label.equals("version")) { for (int j = 0; j < values.length; j++) { versions.add(values[j].replace(".", "-")); } } else if (label.equals("from")) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm"); sdf.setTimeZone(TimeZone.getTimeZone(Const.SystemParams.ADMIN_TIME_ZONE)); Date d = sdf.parse(values[0] + " 00:00"); Calendar cal = TimeHelper.now(0.0); cal.setTime(d); fromDateValue = cal.getTime().getTime(); } else if (label.equals("to")) { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy HH:mm"); sdf.setTimeZone(TimeZone.getTimeZone(Const.SystemParams.ADMIN_TIME_ZONE)); Date d = sdf.parse(values[0] + " 23:59"); Calendar cal = TimeHelper.now(0.0); cal.setTime(d); toDateValue = cal.getTime().getTime(); } else { q.add(label, values); } } return q; }