auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try { int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } case HttpURLConnection.HTTP_UNAUTHORIZED: cookie = getCookie(connection.getURL()); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } break; default: break; } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }

Target:
public HttpConnectionInterceptorContext interceptResponse(HttpConnectionInterceptorContext context) { HttpURLConnection connection = context.connection.getConnection(); try { boolean renewCookie = false; int statusCode = connection.getResponseCode(); switch (statusCode) { case HttpURLConnection.HTTP_FORBIDDEN: InputStream errorStream = connection.getErrorStream(); String errorString = new String(IOUtils.toString(errorStream, "UTF-8")); try { JsonObject errorResponse = new Gson().fromJson(errorString, JsonObject .class); String error = errorResponse.getAsJsonPrimitive ("error").getAsString(); String reason = errorResponse.getAsJsonPrimitive ("reason").getAsString(); if (!"credentials_expired".equals(error)) { throw new HttpConnectionInterceptorException(error, reason); } else { renewCookie = true; } } catch (JsonParseException e) { throw new HttpConnectionInterceptorException(errorString); } finally { errorStream.close(); } break; case HttpURLConnection.HTTP_UNAUTHORIZED: renewCookie = true; break; default: break; } if (renewCookie) { cookie = getCookie(connection.getURL()); if (cookie != null) { context.replayRequest = true; } else { context.replayRequest = false; } } } catch (IOException e) { logger.log(Level.SEVERE, "Failed to get response code from request", e); } return context; }
Source:
protected static List<BuildFileStatement> getUnparseableStatements(@NotNull PsiElement element) { if (element instanceof PsiComment || element instanceof GrStatement) { return ImmutableList.of((BuildFileStatement)new UnparseableStatement(element)); } else { return Collections.EMPTY_LIST; } }

Target:
protected static List<BuildFileStatement> getUnparseableStatements(@NotNull PsiElement element) { if (element instanceof PsiComment || element instanceof GrStatement) { return ImmutableList.of((BuildFileStatement)new UnparseableStatement(element)); } else { return Collections.emptyList(); } }
Source:
private String prettyPrintContentWithTimeOut( AsyncPrettyPrinter asyncPrettyPrinter, InputStream in) throws IOException { AsyncPrettyPrintingTask prettyPrintingTask = new AsyncPrettyPrintingTask( in, asyncPrettyPrinter); ExecutorService executor = Executors.newSingleThreadExecutor(); Future<String> future = executor.submit(prettyPrintingTask); String prettifiedContent = ""; try { prettifiedContent = future.get(10, TimeUnit.SECONDS); } catch (TimeoutException | InterruptedException | ExecutionException e) { future.cancel(true); prettifiedContent = "Failed to pretty print data\n" + readContentsAsUTF8(in); } executor.shutdownNow(); return prettifiedContent; }

Target:
private String prettyPrintContentWithTimeOut( AsyncPrettyPrinter asyncPrettyPrinter, InputStream in) throws IOException { AsyncPrettyPrintingCallable prettyPrintingCallable = new AsyncPrettyPrintingCallable( in, asyncPrettyPrinter); Future<String> future = sExecutorService.submit(prettyPrintingCallable); try { return Util.getUninterruptibly(future, PRETTY_PRINT_TIMEOUT_SEC, TimeUnit.SECONDS); } catch (TimeoutException e) { future.cancel(true); return "Time out after " + PRETTY_PRINT_TIMEOUT_SEC + " seconds of attempting to pretty print\n" + Util.readAsUTF8(in); } catch (ExecutionException e) { Throwable cause = e.getCause(); ExceptionUtil.propagateIfInstanceOf(cause, IOException.class); throw ExceptionUtil.propagate(cause); } }
Source:
private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal = conf.get(StramClientUtils.TOKEN_REFRESH_PRINCIPAL, StramUserLogin.getPrincipal()); String keytabPath = principal.equals(StramUserLogin.getPrincipal()) ? conf.get(StramClientUtils.KEY_TAB_FILE, null) : conf.get(StramClientUtils.TOKEN_REFRESH_KEYTAB, null); LOG.debug("User principal is {}, keytab is {}", principal, keytabPath); if (keytabPath == null) { String keytab = StramUserLogin.getKeytab(); if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } } if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }

Target:
private void setTokenRefreshCredentials(LogicalPlan dag, Configuration conf) throws IOException { String principal = conf.get(StramClientUtils.TOKEN_REFRESH_PRINCIPAL, StramUserLogin.getPrincipal()); String keytabPath = conf.get(StramClientUtils.TOKEN_REFRESH_KEYTAB, conf.get(StramClientUtils.KEY_TAB_FILE)); if (keytabPath == null) { String keytab = StramUserLogin.getKeytab(); if (keytab != null) { Path localKeyTabPath = new Path(keytab); try (FileSystem fs = StramClientUtils.newFileSystemInstance(conf)) { Path destPath = new Path(StramClientUtils.getDTDFSRootDir(fs, conf), localKeyTabPath.getName()); if (!fs.exists(destPath)) { fs.copyFromLocalFile(false, false, localKeyTabPath, destPath); } keytabPath = destPath.toString(); } } } LOG.debug("User principal is {}, keytab is {}", principal, keytabPath); if ((principal != null) && (keytabPath != null)) { dag.setAttribute(LogicalPlan.PRINCIPAL, principal); dag.setAttribute(LogicalPlan.KEY_TAB_FILE, keytabPath); } else { LOG.warn("Credentials for refreshing tokens not available, application may not be able to run indefinitely"); } }
Source:
public void testIsExternalVM() throws IOException { try { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); } catch (Exception e) { e.printStackTrace(); } }

Target:
public void testIsExternalVM() throws Exception { XmlDocument xmlDocument = new XmlDocument(getXmlOvfData()); assertFalse("VM should not be external VM", OvfUtils.isExternalVM(xmlDocument)); }
Source:
private void abandonTask(EntityRef oreon) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); if (!oreonTaskComponent.assignedTaskType.equals(AssignedTaskType.None)) { oreon.getComponent(OreonSpawnComponent.class).parent.getOwner().send(new ChatMessageEvent("Oreon got stuck abandoning task", notificationMessageEntity)); NetworkComponent networkComponent = new NetworkComponent(); networkComponent.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; taskEntity = entityManager.create(networkComponent); TaskComponent taskComponent = new TaskComponent(); taskComponent.assignedTaskType = oreonTaskComponent.assignedTaskType; taskComponent.assignedAreaIndex = oreonTaskComponent.assignedAreaIndex; taskComponent.taskRegion = oreonTaskComponent.taskRegion; taskComponent.creationTime = oreonTaskComponent.creationTime; taskComponent.buildingType = oreonTaskComponent.buildingType; taskComponent.taskStatus = oreonTaskComponent.taskStatus; taskEntity.addComponent(taskComponent); OreonSpawnComponent oreonSpawnComponent = oreon.getComponent(OreonSpawnComponent.class); addTask(oreonSpawnComponent.parent); oreonTaskComponent.assignedTaskType = AssignedTaskType.None; oreon.saveComponent(oreonTaskComponent); } }

Target:
private void abandonTask(EntityRef oreon) { TaskComponent oreonTaskComponent = oreon.getComponent(TaskComponent.class); if (!oreonTaskComponent.assignedTaskType.equals(AssignedTaskType.None)) { String message = "Oreon " + oreon.getComponent(NameTagComponent.class).text + " got stuck. Abandoning task " + oreonTaskComponent.assignedTaskType; oreon.getComponent(OreonSpawnComponent.class).parent.getOwner().send(new ChatMessageEvent(message, notificationMessageEntity)); NetworkComponent networkComponent = new NetworkComponent(); networkComponent.replicateMode = NetworkComponent.ReplicateMode.ALWAYS; taskEntity = entityManager.create(networkComponent); TaskComponent taskComponent = new TaskComponent(); taskComponent.assignedTaskType = oreonTaskComponent.assignedTaskType; taskComponent.assignedAreaIndex = oreonTaskComponent.assignedAreaIndex; taskComponent.taskRegion = oreonTaskComponent.taskRegion; taskComponent.creationTime = oreonTaskComponent.creationTime; taskComponent.buildingType = oreonTaskComponent.buildingType; taskComponent.taskStatus = oreonTaskComponent.taskStatus; taskEntity.addComponent(taskComponent); OreonSpawnComponent oreonSpawnComponent = oreon.getComponent(OreonSpawnComponent.class); addTask(oreonSpawnComponent.parent); oreonTaskComponent.assignedTaskType = AssignedTaskType.None; oreon.saveComponent(oreonTaskComponent); } }
Source:
public StoreContext createStoreContext() { return new StoreContext( getUri(), getBucket(), getConf(), getUsername(), owner, boundedThreadPool, executorCapacity, invoker, getInstrumentation(), getStorageStatistics(), getInputPolicy(), changeDetectionPolicy, enableMultiObjectsDelete, metadataStore, this::keyToQualifiedPath, useListV1, false, (prefix, len) -> createTmpFileForWrite(prefix, len, getConf()), this::getBucketLocation); }

Target:
public StoreContext createStoreContext() { return new StoreContext( getUri(), getBucket(), getConf(), getUsername(), owner, boundedThreadPool, executorCapacity, invoker, getInstrumentation(), getStorageStatistics(), getInputPolicy(), changeDetectionPolicy, enableMultiObjectsDelete, metadataStore, useListV1, new ContextAccessorsImpl(), getTtlTimeProvider()); }
Source:
private List<Snapshot> prepareSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<Snapshot> result = new LinkedList<Snapshot>(); List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { Snapshot updated = prepareSnapshotConfigWithoutImageSingleImage(snapshotDisk.getvm_snapshot_id().getValue(), snapshotDisk.getImageId()); if (updated != null) { result.add(updated); } } } return result; }

Target:
private List<Snapshot> prepareSnapshotConfigWithoutImage(Guid imageGroupToRemove) { List<Snapshot> result = new LinkedList<Snapshot>(); List<DiskImage> snapshotDisks = getDiskImageDao().getAllSnapshotsForImageGroup(imageGroupToRemove); for (DiskImage snapshotDisk : snapshotDisks) { NGuid vmSnapshotId = snapshotDisk.getvm_snapshot_id(); if (vmSnapshotId != null && !Guid.Empty.equals(vmSnapshotId.getValue())) { Snapshot updated = prepareSnapshotConfigWithoutImageSingleImage(vmSnapshotId.getValue(), snapshotDisk.getImageId()); if (updated != null) { result.add(updated); } } } return result; }
Source:
private static boolean tryRecursiveDelete(File file) { boolean success = true; for (int i = 0; i < 5; i++) { success = recursiveDelete(file); if (success) { break; } else { System.gc(); System.runFinalization(); try { Thread.sleep(50); } catch (InterruptedException e) { } } } return success; }

Target:
private static boolean tryRecursiveDelete(File file) { boolean interrupted = false; try { for (int i = 0; i < 5; i++) { if (recursiveDelete(file) || !isWindows()) { return true; } else { System.gc(); System.runFinalization(); try { Thread.sleep(50); } catch (InterruptedException e) { interrupted = true; } } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return false; }
Source:
public void setValue(PreparedStatement st, int startIndex, T value) throws SQLException { if (!type.isAssignableFrom(value.getClass())) { } Array arr = st.getConnection().createArrayOf(typeName, (Object[])value); st.setArray(startIndex, arr); }

Target:
public void setValue(PreparedStatement st, int startIndex, T value) throws SQLException { if (convertPrimitives) { int length = java.lang.reflect.Array.getLength(value); Object value2 = java.lang.reflect.Array.newInstance(Primitives.wrap(type.getComponentType()), length); copy(value, value2, length); value = (T)value2; } Array arr = st.getConnection().createArrayOf(typeName, (Object[])value); st.setArray(startIndex, arr); }
Source:
public void saveCondition_shouldSaveNewCondition(){ int patientId = 2; Date date = new Date(); Condition condition = new Condition(); condition.setCondition(new CodedOrFreeText()); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setAdditionalDetail("saving a condition"); condition.setVerificationStatus(ConditionVerificationStatus.CONFIRMED); condition.setOnsetDate(date); condition.setUuid(UUID); condition.setPatient(patientService.getPatient(patientId)); expectedException = ExpectedException.none(); conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(UUID); Assert.assertEquals(ConditionVerificationStatus.CONFIRMED, savedCondition.getVerificationStatus()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertEquals(UUID, savedCondition.getUuid()); }

Target:
public void saveCondition_shouldSaveNewCondition(){ Integer patientId = 2; String uuid = "08002000-4469-12q3-551f-0339000c9a76"; CodedOrFreeText codedOrFreeText = new CodedOrFreeText(); Condition condition = new Condition(); condition.setCondition(codedOrFreeText); condition.setClinicalStatus(ConditionClinicalStatus.ACTIVE); condition.setUuid(uuid); condition.setPatient(new Patient(patientId)); conditionService.saveCondition(condition); Condition savedCondition = conditionService.getConditionByUuid(uuid); Assert.assertEquals(patientId, savedCondition.getPatient().getPatientId()); Assert.assertEquals(uuid, savedCondition.getUuid()); Assert.assertEquals(codedOrFreeText, savedCondition.getCondition()); Assert.assertEquals(ConditionClinicalStatus.ACTIVE, savedCondition.getClinicalStatus()); Assert.assertNotNull(savedCondition.getConditionId()); }
Source:
public void update() { if (worldObj.isRemote || mode != Mode.On) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); if (worldObj.rand.nextDouble() > 0.9) { sendNetworkUpdate(NET_LED_STATUS); } if (isComplete) { return; } initCurrentPos(); mine(); }

Target:
public void update() { if (worldObj.isRemote || mode != Mode.On) { return; } battery.tick(getWorld(), getPos()); battery.addPower(1000); if(true) { sendNetworkUpdate(NET_LED_STATUS); } if(tubeY == 0) { tubeY = pos.getY(); } else { double diff = currentPos.getY() - tubeY + this.getTubeOffset(); if(Math.abs(diff) <= 0.01) { tubeY = currentPos.getY() + this.getTubeOffset(); } else if(diff > 0) { tubeY += Math.max(diff * 0.05, 0.01); } else { tubeY += Math.min(diff * 0.05, -0.01); } } if (isComplete) { return; } initCurrentPos(); mine(); }
Source:
public TypedAST parseGeneratedModule(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "TSL Parse"); if (typAST instanceof wyvern.tools.typedAST.core.declarations.ModuleDeclaration) { return (wyvern.tools.typedAST.core.declarations.ModuleDeclaration) typAST; } else { throw new RuntimeException("Unexpected parsing input is not a module declaration: \"" + input + "\""); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }

Target:
public wyvern.tools.typedAST.core.declarations.ModuleDeclaration parseGeneratedModule(String input) throws ParseException { InterpreterState state = getLocalThreadInterpreter(); GenContext genContext = Globals.getGenContext(state); try { TypedAST typAST = TestUtil.getNewAST(input.trim() + "\n", "Module generation"); if (typAST instanceof wyvern.tools.typedAST.core.declarations.ModuleDeclaration) { return (wyvern.tools.typedAST.core.declarations.ModuleDeclaration) typAST; } else { throw new RuntimeException("Unexpected parsing input is not a module declaration: \"" + input + "\""); } } catch (ParseException e) { System.err.println("Error when running parseExpression on input \"" + input + "\""); throw e; } }
Source:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final StorageDomainStatic masterDomain, final String exceptionMessage, final String logMessage) { getEventQueue().submitEventSync(new Event(_storagePoolId, masterDomain.getId(), null, EventType.RECONSTRUCT, "Reconstruct caused by failure to execute spm command"), () -> { log.warn(logMessage); AuditLogable logable = new AuditLogableImpl(); logable.setVdsName(vdsDao.get(currentVdsId).getName()); logable.setStorageDomainName(masterDomain.getName()); new AuditLogDirector().log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); return getEventListener().masterDomainNotOperational(masterDomain.getId(), storagePoolId, false, true); }); throw new IRSNoMasterDomainException(exceptionMessage); }

Target:
private void reconstructMasterDomainNotInSync(final Guid storagePoolId, final StorageDomainStatic masterDomain, final String exceptionMessage, final String logMessage) { getEventQueue().submitEventSync(new Event(_storagePoolId, masterDomain.getId(), null, EventType.RECONSTRUCT, "Reconstruct caused by failure to execute spm command"), () -> { log.warn(logMessage); AuditLogable logable = new AuditLogableImpl(); logable.setVdsName(vdsStaticDao.get(currentVdsId).getName()); logable.setStorageDomainName(masterDomain.getName()); new AuditLogDirector().log(logable, AuditLogType.SYSTEM_MASTER_DOMAIN_NOT_IN_SYNC); return getEventListener().masterDomainNotOperational(masterDomain.getId(), storagePoolId, false, true); }); throw new IRSNoMasterDomainException(exceptionMessage); }
Source:
public void addToOrderBook(Order order) { if (order.getType() == OrderType.BUY) { ArrayList<Order> tempList = this.buyOrders.get(order .getStockSymbol()); if (tempList == null) { tempList = new ArrayList<Order>(); } tempList.add(order); this.buyOrders.put(order.getStockSymbol(), tempList); } if (order.getType() == OrderType.SELL) { ArrayList<Order> tempList = this.sellOrders.get(order .getStockSymbol()); if (tempList == null) { tempList = new ArrayList<Order>(); } tempList.add(order); this.sellOrders.put(order.getStockSymbol(), tempList); } }

Target:
public void addToOrderBook(Order order) { if (order.getType() == OrderType.BUY) { addToOrders(this.buyOrders, order); } if (order.getType() == OrderType.SELL) { addToOrders(this.sellOrders, order); } }
Source:
private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fis = openFileInput(fileName)) { int n = 0; while (n < bytes.length) { n += fis.read(bytes, n, bytes.length - n); } } catch (IOException e) { throw new RuntimeException("Couldn't read from " + fileName, e); } }

Target:
private void readBytesFromFile(String fileName, byte[] bytes) { try (FileInputStream fis = openFileInput(fileName)) { int numBytes = 0; while (numBytes < bytes.length) { int n = fis.read(bytes, numBytes, bytes.length - numBytes); if (n <= 0) { throw new RuntimeException("Couldn't read from " + fileName); } numBytes += n; } } catch (IOException e) { throw new RuntimeException("Couldn't read from " + fileName, e); } }
Source:
public void setUp() throws Exception { mockViolationSink = mock(ViolationSink.class); mockViolationSink = mock(ViolationSink.class); lambdaPluginProperties = new LambdaPluginProperties(); lambdaPlugin = new LambdaPlugin(mockViolationSink, lambdaPluginProperties); }

Target:
public void setUp() throws Exception { mockViolationSink = mock(ViolationSink.class); lambdaPluginProperties = new LambdaPluginProperties(); lambdaPluginProperties.setS3Buckets("zalando-lambda-repository-eu-central-1,zalando-lambda-repository-eu-west-1"); lambdaPlugin = new LambdaPlugin(mockViolationSink, lambdaPluginProperties); }
Source:
private void maybeAddLegacySuppressFilter() { try { Class<? extends Annotation> legacySuppressClass = (Class<? extends Annotation>) Class.forName("android.test.suitebuilder.annotation.Suppress"); filter.intersect(new AnnotationExclusionFilter(legacySuppressClass)); } catch (ClassNotFoundException e) { } }

Target:
private void maybeAddLegacySuppressFilter() { try { Class<? extends Annotation> legacySuppressClass = (Class<? extends Annotation>) Class.forName("android.test.suitebuilder.annotation.Suppress"); filter = filter.intersect(new AnnotationExclusionFilter(legacySuppressClass)); } catch (ClassNotFoundException e) { } }
Source:
public GenericShuffleProducer construct(final ConstructArgs args) { Set<Integer> workerIds = getRealWorkerIds(); List<ExchangePairID> operatorIds = getRealOperatorIds(); distributeFunction.setNumDestinations(workerIds.size(), operatorIds.size()); GenericShuffleProducer producer = new GenericShuffleProducer( null, operatorIds.toArray(new ExchangePairID[] {}), MyriaUtils.integerSetToIntArray(workerIds), distributeFunction); if (argBufferStateType != null) { producer.setBackupBuffer(argBufferStateType); } return producer; }

Target:
public GenericShuffleProducer construct(final ConstructArgs args) { Set<Integer> workerIds = getRealWorkerIds(); List<ExchangePairID> operatorIds = getRealOperatorIds(); distributeFunction.setDestinations(workerIds.size(), operatorIds.size()); GenericShuffleProducer producer = new GenericShuffleProducer( null, operatorIds.toArray(new ExchangePairID[] {}), Ints.toArray(workerIds), distributeFunction); if (argBufferStateType != null) { producer.setBackupBuffer(argBufferStateType); } return producer; }
Source:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> removeUnregisteredEntityParams = getRemoveUnregisteredEntityParams(storagePool.getId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), removeUnregisteredEntityParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }

Target:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); List<ActionParametersBase> removeUnregisteredEntityParams = getRemoveUnregisteredEntityParams(getEntity().getStoragePoolId()); Frontend.getInstance().runMultipleAction( getRemoveActionType(), removeUnregisteredEntityParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); }
Source:
public boolean equals(Object aObj, Object bObj) { if (areInstances(aObj, bObj, IFeatureModel.class)) { IFeature a = ((IFeatureModel) aObj).getFeature(); IFeature b = ((IFeatureModel) bObj).getFeature(); return a.getId().equals(b.getId()); } else if (areInstances(aObj, bObj, IFeatureChild.class)) { IFeatureChild a = (IFeatureChild) aObj; IFeatureChild b = (IFeatureChild) bObj; return a.getId().equals(b.getId()) && equals(a.getModel(), b.getModel()); } else if (areInstances(aObj, bObj, IFeaturePlugin.class)) { IFeaturePlugin a = (IFeaturePlugin) aObj; IFeaturePlugin b = (IFeaturePlugin) bObj; return a.getId().equals(b.getId()) && equals(a.getModel(), b.getModel()); } else { return aObj.equals(bObj); } }

Target:
public boolean equals(Object aObj, Object bObj) { return Objects.equals(aObj, bObj); }
Source:
public BigDecimal eval() { try { evalValidation(); } catch (Exception e) { throw new ExpressionException(e.getMessage()); } return eval(true); }

Target:
public BigDecimal eval() { varDefValidation(); return eval(true); }
Source:
public DebugContextEvent(IDebugContextProvider source, ISelection context, int flags) { super(source); Assert.isNotNull(context, "DebugContextEvent context should not be null"); fContext = context; fFlags = flags; }

Target:
public DebugContextEvent(IDebugContextProvider source, ISelection context, int flags) { super(source); Assert.isNotNull(context, "DebugContextEvent context must not be null"); fContext = context; fFlags = flags; }
Source:
public EvictingBoundedList<ArchivedExecution> getPriorExecutionAttempts() { return priorExecutions; }

Target:
public List<AccessExecution> getPriorExecutionAttempts() { List<AccessExecution> accessExecutionList = new ArrayList<>(); for (ArchivedExecution archivedExecution: priorExecutions) { if (priorExecutions != null) { accessExecutionList.add(archivedExecution); } } return Collections.unmodifiableList(accessExecutionList); }
Source:
void updateTopologyComponentParallelism(String topologyName, String newParallelism) throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { LOG.fine(String.format("updateTopologyHandler called for %s with %s", topologyName, newParallelism)); SchedulerStateManagerAdaptor manager = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = manager.getTopology(topologyName); Map<String, Integer> changeRequests = parseNewParallelismParam(newParallelism); PackingPlans.PackingPlan currentPlan = manager.getPackingPlan(topologyName); if (!changeDetected(currentPlan, changeRequests)) { throw new TopologyRuntimeManagementException( String.format("The component parallelism request (%s) is the same as the " + "current topology parallelism. Not taking action.", newParallelism)); } PackingPlans.PackingPlan proposedPlan = buildNewPackingPlan(currentPlan, changeRequests, topology); if (Context.dryRun(config)) { PackingPlanProtoDeserializer deserializer = new PackingPlanProtoDeserializer(); PackingPlan oldPlan = deserializer.fromProto(currentPlan); PackingPlan newPlan = deserializer.fromProto(proposedPlan); throw new UpdateDryRunResponse(topology, config, newPlan, oldPlan, changeRequests); } Scheduler.UpdateTopologyRequest updateTopologyRequest = Scheduler.UpdateTopologyRequest.newBuilder() .setCurrentPackingPlan(currentPlan) .setProposedPackingPlan(proposedPlan) .build(); LOG.fine("Sending Updating topology request: " + updateTopologyRequest); if (!schedulerClient.updateTopology(updateTopologyRequest)) { throw new TopologyRuntimeManagementException( "Failed to update topology with Scheduler, updateTopologyRequest=" + updateTopologyRequest + "The topology can be in a strange stage. " + "Please check carefully or redeploy the topology !!"); } }

Target:
void updateTopologyComponentParallelism(String topologyName, String newParallelism) throws TopologyRuntimeManagementException, PackingException, UpdateDryRunResponse { LOG.fine(String.format("updateTopologyHandler called for %s with %s", topologyName, newParallelism)); Map<String, Integer> changeRequests = parseNewParallelismParam(newParallelism); SchedulerStateManagerAdaptor manager = Runtime.schedulerStateManagerAdaptor(runtime); TopologyAPI.Topology topology = manager.getTopology(topologyName); PackingPlans.PackingPlan currentPlan = manager.getPackingPlan(topologyName); if (!parallelismChangeDetected(currentPlan, changeRequests)) { throw new TopologyRuntimeManagementException( String.format("The component parallelism request (%s) is the same as the " + "current topology parallelism. Not taking action.", newParallelism)); } PackingPlans.PackingPlan proposedPlan = buildNewPackingPlan(currentPlan, changeRequests, null, topology); sendUpdateRequest(topology, changeRequests, currentPlan, proposedPlan); }
Source:
public void refreshGeoRepDataForVolume(final GlusterVolumeEntity volume) { VDSGroup cluster = getClusterDao().get(volume.getClusterId()); discoverGeoRepDataForVolume(cluster, volume); List<GlusterGeoRepSession> geoRepSessions = getGeoRepDao().getGeoRepSessions(volume.getId()); refreshGeoRepSessionStatus(cluster, geoRepSessions); }

Target:
public void refreshGeoRepDataForVolume(final GlusterVolumeEntity volume) { if (volume == null) { throw new VdcBLLException(VdcBllErrors.GlusterVolumeGeoRepSyncFailed, "No volume information"); } VDSGroup cluster = getClusterDao().get(volume.getClusterId()); discoverGeoRepDataInCluster(cluster, volume.getName()); List<GlusterGeoRepSession> geoRepSessions = getGeoRepDao().getGeoRepSessions(volume.getId()); refreshGeoRepSessionStatus(cluster, geoRepSessions); }
Source:
public Response toResponse(final JerseyViolationException exception) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Object validation failure", exception); } final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); final Invocable invocable = exception.getInvocable(); final ImmutableList<String> errors = FluentIterable.from(exception.getConstraintViolations()) .transform(violation -> ConstraintMessage.getMessage(violation, invocable)).toList(); final int status = ConstraintMessage.determineStatus(violations, invocable); return Response.status(status) .entity(new ValidationErrorMessage(errors)) .build(); }

Target:
public Response toResponse(final JerseyViolationException exception) { LOGGER.debug("Object validation failure", exception); final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); final Invocable invocable = exception.getInvocable(); final ImmutableList<String> errors = FluentIterable.from(exception.getConstraintViolations()) .transform(violation -> ConstraintMessage.getMessage(violation, invocable)).toList(); final int status = ConstraintMessage.determineStatus(violations, invocable); return Response.status(status) .entity(new ValidationErrorMessage(errors)) .build(); }
Source:
public PostDonationCounselling createPostDonationCounsellingForDonation(Donation donation) { LOGGER.info("Creating post donation counselling for donation: " + donation); PostDonationCounselling existingCounselling = postDonationCounsellingRepository.findPostDonationCounsellingForDonation( donation); if (existingCounselling != null) { LOGGER.info("Returning existing counselling instead of creating a new PostDonationCounselling"); return existingCounselling; } PostDonationCounselling postDonationCounselling = new PostDonationCounselling(); postDonationCounselling.setDonation(donation); postDonationCounselling.setFlaggedForCounselling(true); postDonationCounsellingRepository.save(postDonationCounselling); return postDonationCounselling; }

Target:
public PostDonationCounselling createPostDonationCounsellingForDonation(Donation donation) { LOGGER.info("Creating post donation counselling for donation: " + donation); PostDonationCounselling existingCounselling = postDonationCounsellingRepository.findPostDonationCounsellingForDonation( donation); if (existingCounselling != null) { return existingCounselling; } PostDonationCounselling postDonationCounselling = new PostDonationCounselling(); postDonationCounselling.setDonation(donation); postDonationCounselling.setFlaggedForCounselling(Boolean.TRUE); postDonationCounselling.setIsDeleted(Boolean.FALSE); postDonationCounselling.setCreatedBy(utilController.getCurrentUser()); postDonationCounselling.setCreatedDate(dateGeneratorService.generateDate()); postDonationCounselling.setLastUpdated(dateGeneratorService.generateDate()); postDonationCounselling.setLastUpdatedBy(utilController.getCurrentUser()); postDonationCounsellingRepository.save(postDonationCounselling); return postDonationCounselling; }
Source:
private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) { Predicate<Set<?>> emptyList = list -> list != null && list.isEmpty(); if (emptyList.test(query.getComponentIds()) || emptyList.test(query.getComponentKeys()) || emptyList.test(query.getComponentUuids())) { return emptyList(); } return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit)); }

Target:
private static List<ComponentDto> selectByQueryImpl(DbSession session, @Nullable String organizationUuid, ComponentQuery query, int offset, int limit) { if (query.hasEmptySetOfComponents()) { return emptyList(); } return mapper(session).selectByQuery(organizationUuid, query, new RowBounds(offset, limit)); }
Source:
public void validateSourceDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); disk.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_SOURCE_STORAGE_DOMAIN_IS_NOT_VALID); }

Target:
public void validateSourceDomainValid() { DiskImage disk = new DiskImage(); initializeCommand(disk, VmEntityType.VM); initSrcStorageDomain(); initDestStorageDomain(StorageType.NFS); disk.setStorageIds(new ArrayList<>(Collections.singletonList(Guid.newGuid()))); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_SOURCE_STORAGE_DOMAIN_DOES_CONTAINS_THE_DISK); }
Source:
public long getNativeFinalizerPtr() { return 0; }

Target:
public long getNativeFinalizerPtr() { return nativeGetFinalizerMethodPtr(); }
Source:
public void showBadImagePopup(Integer errorCode) { String errorMessageForResult = getErrorMessageForResult(getContext(), errorCode); if (!StringUtils.isBlank(errorMessageForResult)) { DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), errorMessageForResult, () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, () -> { deleteThisPicture(); }); } }

Target:
public void showBadImagePopup(Integer errorCode) { String errorMessageForResult = getErrorMessageForResult(getContext(), errorCode); if (!StringUtils.isBlank(errorMessageForResult)) { DialogUtil.showAlertDialog(getActivity(), getString(R.string.warning), errorMessageForResult, () -> { uploadItem.setImageQuality(ImageUtils.IMAGE_KEEP); onNextButtonClicked(); }, () -> deleteThisPicture() ); } }
Source:
private <T> T update( T t ) throws Throwable { if( currentStage == t ) { readScenarioState( currentStage ); updateScenarioState( currentStage ); return t; } if( currentStage == null ) { ensureBeforeStepsAreExecuted(); } else { executeAfterStageMethods( currentStage ); readScenarioState( currentStage ); } updateScenarioState( t ); StageState stageState = getStageState( t ); if( !stageState.beforeStageCalled ) { stageState.beforeStageCalled = true; executeBeforeStageSteps( t ); } currentStage = t; return t; }

Target:
private <T> T update( T t ) throws Throwable { if( currentStage == t ) { return t; } if( currentStage == null ) { ensureBeforeStepsAreExecuted(); } else { executeAfterStageMethods( currentStage ); readScenarioState( currentStage ); } updateScenarioState( t ); StageState stageState = getStageState( t ); if( !stageState.beforeStageCalled ) { stageState.beforeStageCalled = true; executeBeforeStageSteps( t ); } currentStage = t; return t; }
Source:
public boolean isNeedToInitializeCache() { int quotaCount = getQuotaDAO().getQuotaCount(); int cacheCount = 0; for(Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { cacheCount += quotaMap.size(); } return cacheCount < quotaCount * MINIMUM_CACHE_FACTOR; }

Target:
public boolean isNeedToInitializeCache() { int quotaCount = getQuotaDAO().getQuotaCount(); int cacheCount = 0; lock.readLock().lock(); try { for(Map<Guid, Quota> quotaMap : storagePoolQuotaMap.values()) { cacheCount += quotaMap.size(); } } finally { lock.readLock().unlock(); } return cacheCount < quotaCount * MINIMUM_CACHE_FACTOR; }
Source:
public void getDefaultPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }

Target:
public void getDefaultPermissions_returnLoadedResults() { PermissionManager pm = user.getPermissionManager(); looperThread.closeAfterTest(pm); pm.getDefaultPermissions(new PermissionManager.Callback<RealmResults<Permission>>() { @Override public void onSuccess(RealmResults<Permission> permissions) { assertTrue(permissions.isLoaded()); assertInitialPermissions(permissions); looperThread.testComplete(); } @Override public void onError(ObjectServerError error) { fail(error.toString()); } }); }
Source:
public void run() { try { long clearIntervalNanos = randomizeClearInterval(); long iteration = 0; long lastClearTime = System.nanoTime(); while (!testContext.isStopped()) { long batchSleepNanos = randomizeBatchSleep(); int batchSize = randomizeBatchSize(); for (int i = 0; i < batchSize; i++) { int operation = randomizeOperation(); switch (operation) { case OPERATE_GET: operateGet(); break; case OPERATE_PUT: operatePut(); break; case OPERATE_UPDATE: operateUpdate(); break; case OPERATE_REMOVE: operateRemove(); break; } operations.incrementAndGet(); if (testContext.isStopped()) { return; } if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } iteration++; } if (System.nanoTime() - lastClearTime >= clearIntervalNanos) { log("Executing clear operation"); replicatedMap.clear(); } TimeUnit.NANOSECONDS.sleep(batchSleepNanos); if (System.nanoTime() - lastClearTime >= clearIntervalNanos) { log("Executing clear operation"); replicatedMap.clear(); } } } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void run() { long clearIntervalNanos = randomizeClearInterval(); long iteration = 0; long lastClearTime = System.nanoTime(); while (!testContext.isStopped()) { long batchSleepNanos = randomizeBatchSleep(); int batchSize = randomizeBatchSize(); for (int i = 0; i < batchSize; i++) { executeRandomOperation(); if (testContext.isStopped()) { return; } if (iteration % logFrequency == 0) { log.info(Thread.currentThread().getName() + " At iteration: " + iteration); } iteration++; if (iteration % performanceUpdateFrequency == 0) { operations.addAndGet(performanceUpdateFrequency); } } clearReplicatedMapIfNeeded(clearIntervalNanos, lastClearTime); try { TimeUnit.NANOSECONDS.sleep(batchSleepNanos); } catch (InterruptedException e) { throw new RuntimeException(e); } clearReplicatedMapIfNeeded(clearIntervalNanos, lastClearTime); } }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProgressStepId other = (ProgressStepId) obj; if (stepNumber != other.stepNumber) return false; return true; }

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ProgressStepId other = (ProgressStepId) obj; if (progress == null) { if (other.progress != null) return false; } else if (!progress.equals(other.progress)) return false; if (stepNumber != other.stepNumber) return false; return true; }
Source:
public List<Guid> getIdsOfHostsWithStatus(VDSStatus status) { return getCallsHandler().executeReadList("getIdsOfHostsWithStatus", createGuidMapper(), getCustomMapSqlParameterSource() .addValue("status", status.getValue())); }

Target:
public List<Guid> getIdsOfHostsWithStatus(VDSStatus status) { return getCallsHandler().executeReadList("GetIdsOfHostsWithStatus", createGuidMapper(), getCustomMapSqlParameterSource() .addValue("status", status.getValue())); }
Source:
public void testColorSeekBar() { int whenBrickPosition = 0; onBrickAtPosition(whenBrickPosition).checkShowsText(R.string.brick_when_started); int penColorBrickPosition = 1; onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber(initValue) .perform(click()); onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeLeftSlow()); onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeRightSlow()); onColorSeekbar().closeAndSaveChanges(); onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber((int) MAX_COLOR_SEEKBAR_VALUE); }

Target:
public void testColorSeekBar() { int whenBrickPosition = 0; onBrickAtPosition(whenBrickPosition).checkShowsText(R.string.brick_when_started); int penColorBrickPosition = 1; onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber(initValue) .perform(click()); onView(withId(colorRgbSeekbarId)) .perform(CustomSwipeAction.swipeRightSlow()); onColorSeekbar().closeAndSaveChanges(); onBrickAtPosition(penColorBrickPosition).onFormulaTextField(brickActionEditTextId) .checkShowsNumber((int) MAX_COLOR_SEEKBAR_VALUE); }
Source:
public byte[] apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { ObjectLoader loader = repo.open(tw.getObjectId(0)); ByteArrayOutputStream out = new ByteArrayOutputStream(); loader.copyTo(out); return Base64.encodeBase64(out.toByteArray()); } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }

Target:
public String apply(FileResource rsrc) throws ResourceNotFoundException, IOException { Project.NameKey project = rsrc.getRevision().getControl().getProject().getNameKey(); Repository repo = repoManager.openRepository(project); try { RevWalk rw = new RevWalk(repo); try { RevCommit commit = rw.parseCommit(ObjectId.fromString(rsrc.getRevision().getPatchSet() .getRevision().get())); TreeWalk tw = TreeWalk.forPath(rw.getObjectReader(), rsrc.getPatchKey().get(), commit.getTree().getId()); if (tw == null) { throw new ResourceNotFoundException(); } try { ObjectLoader loader = repo.open(tw.getObjectId(0)); return BaseEncoding.base64().encode(loader.getBytes()); } finally { tw.release(); } } finally { rw.release(); } } finally { repo.close(); } }
Source:
public void testIndexIdDataTypeDefaultValue() throws Exception { String tableName = "T_" + generateUniqueName(); String globalViewName = "V_" + generateUniqueName(); String globalViewIndexName = "GV_" + generateUniqueName(); try (Connection globalConn = getConnection()) { createBaseTable(SCHEMA1, tableName, true, 0, null, true); createView(globalConn, SCHEMA1, globalViewName, tableName); createViewIndex(globalConn, SCHEMA1, globalViewIndexName, globalViewName, "v1"); String sql = "SELECT " + VIEW_INDEX_ID_DATA_TYPE + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_SCHEM + " = '%s' AND " + TABLE_NAME + " = '%s' AND " + COLUMN_COUNT + " IS NOT NULL"; ResultSet rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, tableName)); if (rs.next()) { assertEquals(null, rs.getObject(1)); } else { fail(); } rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, globalViewName)); if (rs.next()) { assertEquals(null, rs.getObject(1)); } else { fail(); } rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, globalViewIndexName)); if (rs.next()) { assertEquals(QueryServicesOptions.DEFAULT_LONG_VIEW_INDEX_ENABLED, rs.getInt(1)); } else { fail(); } } }

Target:
public void testIndexIdDataTypeDefaultValue() throws Exception { String tableName = "T_" + generateUniqueName(); String globalViewName = "V_" + generateUniqueName(); String globalViewIndexName = "GV_" + generateUniqueName(); try (Connection globalConn = getConnection()) { createBaseTable(SCHEMA1, tableName, true, 0, null, true); createView(globalConn, SCHEMA1, globalViewName, tableName); createViewIndex(globalConn, SCHEMA1, globalViewIndexName, globalViewName, "v1"); String sql = "SELECT " + VIEW_INDEX_ID_DATA_TYPE + " FROM " + SYSTEM_CATALOG_NAME + " WHERE " + TABLE_SCHEM + " = '%s' AND " + TABLE_NAME + " = '%s' AND " + COLUMN_COUNT + " IS NOT NULL"; ResultSet rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, tableName)); if (rs.next()) { assertNull(rs.getObject(1)); } else { fail(); } rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, globalViewName)); if (rs.next()) { assertNull(rs.getObject(1)); } else { fail(); } rs = globalConn.createStatement().executeQuery(String.format(sql, SCHEMA1, globalViewIndexName)); if (rs.next()) { assertEquals(Types.BIGINT, rs.getInt(1)); } else { fail(); } } }
Source:
protected void subscribeActual(final MaybeObserver<? super Long> observer) { SequentialDisposable sd = new SequentialDisposable(); observer.onSubscribe(sd); sd.replace(scheduler.scheduleDirect(new Runnable() { @Override public void run() { observer.onSuccess(0L); } }, delay, unit)); }

Target:
protected void subscribeActual(final MaybeObserver<? super Long> observer) { TimerDisposable parent = new TimerDisposable(observer); observer.onSubscribe(parent); parent.setFuture(scheduler.scheduleDirect(parent, delay, unit)); }
Source:
public List<ReportMetadataJson> getReports() { if (reports != null) { return reports; } else if (serializedReports != null) { deserializeReports(); return reports; } return Collections.emptyList(); }

Target:
public List<ReportMetadataJson> getReports() { return reports; }
Source:
public static String generateResponseParser(final String structName, final ImmutableList<StructMember> variables) throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); for (int structMemberIndex = 0; structMemberIndex < variables.size(); structMemberIndex++) { outputBuilder.append(indent(2)); if (structMemberIndex > 0) { outputBuilder.append("} else "); } final StructMember currentStructMember = variables.get(structMemberIndex); outputBuilder.append("if (element_equal(child_node, \"").append(Helper.underscoreToCamel(currentStructMember.getName())).append("\")) {").append("\n"); outputBuilder.append(getParseStructMemberBlock(structName, currentStructMember)); } outputBuilder.append(indent(2)).append("}").append("\n"); return outputBuilder.toString(); }

Target:
public static String generateResponseParser(final String structName, final ImmutableList<StructMember> variables) throws ParseException { final StringBuilder outputBuilder = new StringBuilder(); for (int structMemberIndex = 0; structMemberIndex < variables.size(); structMemberIndex++) { outputBuilder.append(indent(2)); if (structMemberIndex > 0) { outputBuilder.append("} else "); } final StructMember currentStructMember = variables.get(structMemberIndex); outputBuilder.append("if (element_equal(child_node, \"").append(Helper.underscoreToCamel(currentStructMember.getName())).append("\")) {").append("\n"); outputBuilder.append(getParseStructMemberBlock(structName, currentStructMember)); } outputBuilder.append(indent(2)).append("} else {").append("\n"); outputBuilder.append(indent(3)).append("ds3_log_message(log, DS3_ERROR, \"Unknown element[%s]\\n\", child_node->name);").append("\n"); outputBuilder.append(indent(2)).append("}").append("\n"); return outputBuilder.toString(); }