auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void run(StreamApplication app) { try { ExecutionPlan plan = getExecutionPlan(app); List<StreamSpec> intStreams = plan.getIntermediateStreams(); if (!intStreams.isEmpty()) { if (coordination != null) { Latch initLatch = coordination.getLatch(1, LATCH_INIT); coordination.getLeaderElector().tryBecomeLeader(() -> { getStreamManager().createStreams(intStreams); initLatch.countDown(); }); initLatch.await(LATCH_TIMEOUT, TimeUnit.MINUTES); } else { getStreamManager().createStreams(intStreams); } } plan.getJobConfigs().forEach(jobConfig -> { log.info("Starting job StreamProcessor with config {}", jobConfig.getName(), jobConfig); Object taskFactory = TaskFactoryUtil.createTaskFactory(config, app, this); StreamProcessor processor = createStreamProcessor(jobConfig, taskFactory); processor.addLifeCycleAware(new LocalProcessorListener(processor)); processors.add(processor); processor.start(); }); appStatus = ApplicationStatus.Running; latch.await(); if (throwable.get() != null) { appStatus = ApplicationStatus.UnsuccessfulFinish; throw throwable.get(); } else { appStatus = ApplicationStatus.SuccessfulFinish; } } catch (Throwable t) { throw new SamzaException("Failed to run application", t); } finally { coordination.reset(); } }

Target:
public void run(StreamApplication app) { try { ExecutionPlan plan = getExecutionPlan(app); createStreams(plan.getIntermediateStreams()); if (plan.getJobConfigs().isEmpty()) { throw new SamzaException("No jobs to run."); } LocalProcessorListener listener = new LocalProcessorListener(); plan.getJobConfigs().forEach(jobConfig -> { log.info("Starting job StreamProcessor with config {}", jobConfig.getName(), jobConfig); StreamProcessor processor = createStreamProcessor(jobConfig, app, listener); processor.start(); processors.add(processor); }); appStatus = ApplicationStatus.Running; awaitComplete(); } catch (Throwable t) { appStatus = ApplicationStatus.UnsuccessfulFinish; throw new SamzaException("Failed to run application", t); } finally { if (coordination != null) { coordination.reset(); } } }
Source:
public String getServerType() { return strings.getString("glowstone.server-type.vanilla"); }

Target:
public String getServerType() { return "VANILLA"; }
Source:
void testRecursion() { Math f = new Math() { @Override public String powerOfTwo(int n) { return n == 0 ? 1 : 2 * powerOfTwo(n -1); } }; }

Target:
void testRecursion() { Math f = new Math() { @Override public int powerOfTwo(int n) { return n == 0 ? 1 : 2 * powerOfTwo(n -1); } }; }
Source:
private static boolean checkDistinguishedName(final String userName) { Name name = null; try { name = new LdapName(userName); } catch (final Exception e) { LOG.warn("Not a Valid Distinguished Name, setting the value from Certificate: {}", e.getLocalizedMessage()); LOG.trace("Exception checking DN: {}", e.getLocalizedMessage(), e); } return name == null ? false : true; }

Target:
private static boolean checkDistinguishedName(final String userName) { Name name = null; try { name = new LdapName(userName); } catch (final Exception e) { LOG.trace("Exception checking DN: {}", e.getLocalizedMessage(), e); } return name != null; }
Source:
protected void autoLoad() { if (SessionContext.isLoggedIn() && (entryId != 0 || (className != null && classPK != 0)) || (portletItemName != null && !portletItemName.equals(""))) { loadAsset(); } }

Target:
protected void autoLoad() { boolean hasClassName = className != null && classPK != 0; boolean hasPortletItemName = portletItemName != null && !"".equals(portletItemName); if (SessionContext.isLoggedIn() && (entryId != 0 || hasClassName || hasPortletItemName)) { loadAsset(); } }
Source:
public synchronized void writeSelf(File file, long pos) { try (FileOutputStream fos = new FileOutputStream(file, true); FileChannel fc = fos.getChannel();) { fc.position(pos); try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeInt(ATTRIB_TREE_MAGIC_NUMBER); List<String[]> list = new ArrayList<>(attributeList.size()); String[] prevFullAttribute = null, curFullAttribute = null; for (Attribute entry : this.attributeList) { curFullAttribute = (prevFullAttribute == null) ? entry.getFullAttribute() : encodeFullAttribute(prevFullAttribute, entry.getFullAttribute()); list.add(curFullAttribute); prevFullAttribute = curFullAttribute; } oos.writeObject(list); } } catch (IOException e) { e.printStackTrace(); } }

Target:
public synchronized void writeSelf(File file, long pos) { try (FileOutputStream fos = new FileOutputStream(file, true); FileChannel fc = fos.getChannel();) { fc.position(pos); try (ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeInt(ATTRIB_TREE_MAGIC_NUMBER); List<String[]> list = new ArrayList<>(attributeList.size()); String[] prevFullAttribute = null, curFullAttribute = null, curEncodedAttribute = null; for (Attribute entry : this.attributeList) { curFullAttribute = entry.getFullAttribute(); curEncodedAttribute = encodeFullAttribute(prevFullAttribute, entry.getFullAttribute()); list.add(curEncodedAttribute); prevFullAttribute = curFullAttribute; } oos.writeObject(list); } } catch (IOException e) { e.printStackTrace(); } }
Source:
public void sourceConfInit(FlowProcess<JobConf> flowProcess, Tap<JobConf, RecordReader, OutputCollector> tap, JobConf conf ) { if (conf.getBoolean(DelegateCombineFileInputFormat.USE_COMBINED_INPUT_FORMAT, false)) { DeprecatedInputFormatWrapper.setInputFormat(DelegateCombineFileInputFormat.class, conf); DelegateCombineFileInputFormat.setCombinedInputFormatDelegate(LzoTextInputFormat.class, conf); } else { conf.setInputFormat(DeprecatedLzoTextInputFormat.class); } }

Target:
public void sourceConfInit(FlowProcess<JobConf> flowProcess, Tap<JobConf, RecordReader, OutputCollector> tap, JobConf conf ) { DelegateCombineFileInputFormat.setDelegateInputFormat(conf, LzoTextInputFormat.class); }
Source:
public Block renderNotification(CompositeEvent eventNotification) throws NotificationException { try { velocityManager.getCurrentVelocityContext().put(EVENT_BINDING_NAME, eventNotification); PageNotificationEventDescriptor eventDescriptor = pageNotificationEventDescriptorContainer.getDescriptorByType( eventNotification.getEvents().get(0).getType()); if (eventDescriptor.getNotificationTemplate().isEmpty()) { return templateManager.execute("notification/default.vm"); } return new RawBlock(executeTemplate(eventDescriptor.getAuthorReference(), eventDescriptor.getNotificationTemplate()), Syntax.HTML_5_0); } catch (Exception e) { throw new NotificationException("Unable to render notification template.", e); } finally { velocityManager.getCurrentVelocityContext().remove(EVENT_BINDING_NAME); } }

Target:
public Block renderNotification(CompositeEvent eventNotification) throws NotificationException { try { velocityManager.getCurrentVelocityContext().put(EVENT_BINDING_NAME, eventNotification); PageNotificationEventDescriptor eventDescriptor = pageNotificationEventDescriptorManager.getDescriptorByType( eventNotification.getEvents().get(0).getType()); if (StringUtils.isBlank(eventDescriptor.getNotificationTemplate())) { String templateName = String.format("notification/%s.vm", eventDescriptor.getEventName().replaceAll("\\/", ".")); Template template = templateManager.getTemplate(templateName); return (template != null) ? templateManager.executeNoException(template) : templateManager.executeNoException("notification/default.vm"); } Template customTemplate = new StringTemplate( eventDescriptor.getNotificationTemplate(), Syntax.XWIKI_2_1, Syntax.PLAIN_1_0, eventDescriptor.getAuthorReference()); return templateManager.getXDOM(customTemplate); } catch (Exception e) { throw new NotificationException("Unable to render notification template.", e); } finally { velocityManager.getCurrentVelocityContext().remove(EVENT_BINDING_NAME); } }
Source:
private RemoteReplicaInfo getRemoteReplicaInfo(PartitionId partitionId, String hostName, String replicaPath) { RemoteReplicaInfo remoteReplicaInfo = null; for (PartitionId partitionId1 : partitionsToReplicate.keySet()) { if (partitionId.compareTo(partitionId1) == 0) { PartitionInfo partitionInfo = partitionsToReplicate.get(partitionId); for (RemoteReplicaInfo remoteReplicaInfo1 : partitionInfo.getRemoteReplicaInfo()) { if (remoteReplicaInfo1.getReplicaId().getReplicaPath().equals(replicaPath) && remoteReplicaInfo1 .getReplicaId().getDataNodeId().getHostname().equals(hostName)) { remoteReplicaInfo = remoteReplicaInfo1; } } } } if (remoteReplicaInfo == null) { replicationMetrics.unknownRemoteReplicaRequestCount.inc(); logger.error("ReplicaMetaDataRequest from unknown Replica ", hostName + ", with path ", replicaPath); } return remoteReplicaInfo; }

Target:
private RemoteReplicaInfo getRemoteReplicaInfo(PartitionId partitionId, String hostName, String replicaPath) { RemoteReplicaInfo foundRemoteReplicaInfo = null; PartitionInfo partitionInfo = partitionsToReplicate.get(partitionId); for (RemoteReplicaInfo remoteReplicaInfo : partitionInfo.getRemoteReplicaInfos()) { if (remoteReplicaInfo.getReplicaId().getReplicaPath().equals(replicaPath) && remoteReplicaInfo.getReplicaId() .getDataNodeId().getHostname().equals(hostName)) { foundRemoteReplicaInfo = remoteReplicaInfo; } } if (foundRemoteReplicaInfo == null) { replicationMetrics.unknownRemoteReplicaRequestCount.inc(); logger.error("ReplicaMetaDataRequest from unknown Replica {}, with path {}", hostName, replicaPath); } return foundRemoteReplicaInfo; }
Source:
protected Pair<Integer, String> exec(String hostname, ServiceType service, String... cmd) throws IOException { final String serviceUser = getServiceUser(service); final String[] commandPrefix = !Objects.equals(serviceUser, getServiceUser(ServiceType.HBASE_MASTER)) ? new String[] { "sudo", "-u", serviceUser } : new String[0]; final String command = StringUtils.join(ArrayUtils.addAll(commandPrefix, cmd), " "); LOG.info("Executing remote command: {}, hostname:{}", command, hostname); try (final AsyncConnection conn = ConnectionFactory.createAsyncConnection(getConf()).join()) { final AsyncAdmin admin = conn.getAdmin(); final ShellExecRequest req = ShellExecRequest.newBuilder() .setCommand(command) .build(); final ShellExecResponse resp; switch(service) { case HBASE_MASTER: resp = masterExec(admin, req); break; case HBASE_REGIONSERVER: final ServerName targetHost = resolveRegionServerName(admin, hostname); resp = regionServerExec(admin, req, targetHost); break; default: throw unsupportedServiceType(service); } LOG.info("Executed remote command, exit code:{} , output:{}", resp.getExitCode(), resp.getStdout()); return new Pair<>(resp.getExitCode(), resp.getStdout()); } }

Target:
protected Pair<Integer, String> exec(String hostname, ServiceType service, String... cmd) throws IOException { if (!supportedServices.contains(service)) { throw unsupportedServiceType(service); } final String command = StringUtils.join(cmd, " "); LOG.info("Executing remote command: {}, hostname:{}", command, hostname); try (final AsyncConnection conn = ConnectionFactory.createAsyncConnection(getConf()).join()) { final AsyncAdmin admin = conn.getAdmin(); final ShellExecRequest req = ShellExecRequest.newBuilder() .setCommand(command) .setAwaitResponse(false) .build(); final ShellExecResponse resp; switch(service) { case HBASE_MASTER: resp = masterExec(admin, req); break; case HBASE_REGIONSERVER: final ServerName targetHost = resolveRegionServerName(admin, hostname); resp = regionServerExec(admin, req, targetHost); break; default: throw new RuntimeException("should not happen"); } if (LOG.isDebugEnabled()) { LOG.debug("Executed remote command: {}, exit code:{} , output:{}", command, resp.getExitCode(), resp.getStdout()); } else { LOG.info("Executed remote command: {}, exit code:{}", command, resp.getExitCode()); } return new Pair<>(resp.getExitCode(), resp.getStdout()); } }
Source:
public State convertToState(int[] data, ComfoAirCommandType commandType) { if (commandType.getGetReplyDataPos()[0] < data.length) { return new DecimalType((((double) data[commandType.getGetReplyDataPos()[0]]) / 2) - 20); } else { return null; } }

Target:
public State convertToState(int[] data, ComfoAirCommandType commandType) { if (data == null || commandType == null) { logger.trace("\"DataTypeTemperature\" class \"convertToState\" method parameter: null"); return null; } else { if (commandType.getGetReplyDataPos()[0] < data.length) { return new DecimalType((((double) data[commandType.getGetReplyDataPos()[0]]) / 2) - 20); } else { return null; } } }
Source:
private static String getPartitionId(InetAddress overrideAddress, Request request, ProxyServer proxyServer) { return overrideAddress != null ? overrideAddress.toString() + "_" : "" + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); }

Target:
private static String getPartitionId(InetAddress overrideAddress, Request request, ProxyServer proxyServer) { return (overrideAddress != null ? overrideAddress.toString() + "_" : "") + request.getConnectionPoolPartitioning() .getPartitionKey(request.getUri(), proxyServer).toString(); }
Source:
public BasicInvocationStage visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { return invokeNext(ctx, command).handle((rCtx, rCommand, rv, t) -> { GetAllCommand getAllCommand = (GetAllCommand) rCommand; if (t != null) { if (t instanceof RpcException && performPartitionCheck(rCtx, getAllCommand)) { throw log.degradedModeKeysUnavailable(((GetAllCommand) rCommand).getKeys()); } else { throw t; } } if (performPartitionCheck(rCtx, getAllCommand)) { for (Object key : getAllCommand.getKeys()) { partitionHandlingManager.checkRead(key); } CacheTopology cacheTopology = stateTransferManager.getCacheTopology(); Map<Object, Object> result = ((Map<Object, Object>) rv); if (result.size() != getAllCommand.getKeys().size()) { Set<Object> missingKeys = new HashSet<>(getAllCommand.getKeys()); missingKeys.removeAll(result.keySet()); for (Iterator<Object> it = missingKeys.iterator(); it.hasNext(); ) { Object key = it.next(); if (InfinispanCollections.containsAny(transport.getMembers(), stateTransferManager.getCacheTopology().getReadConsistentHash().locateOwners(key))) { it.remove(); } } if (!missingKeys.isEmpty()) { throw log.degradedModeKeysUnavailable(missingKeys); } } } }); }

Target:
public BasicInvocationStage visitGetAllCommand(InvocationContext ctx, GetAllCommand command) throws Throwable { return invokeNext(ctx, command).handle((rCtx, rCommand, rv, t) -> { GetAllCommand getAllCommand = (GetAllCommand) rCommand; if (t != null) { if (t instanceof RpcException && performPartitionCheck(rCtx, getAllCommand)) { throw log.degradedModeKeysUnavailable(((GetAllCommand) rCommand).getKeys()); } else { throw t; } } if (performPartitionCheck(rCtx, getAllCommand)) { for (Object key : getAllCommand.getKeys()) { partitionHandlingManager.checkRead(key); } Map<Object, Object> result = ((Map<Object, Object>) rv); if (result.size() != getAllCommand.getKeys().size()) { Set<Object> missingKeys = new HashSet<>(getAllCommand.getKeys()); missingKeys.removeAll(result.keySet()); for (Iterator<Object> it = missingKeys.iterator(); it.hasNext(); ) { Object key = it.next(); if (InfinispanCollections.containsAny(transport.getMembers(), stateTransferManager.getCacheTopology().getReadConsistentHash().locateOwners(key))) { it.remove(); } } if (!missingKeys.isEmpty()) { throw log.degradedModeKeysUnavailable(missingKeys); } } } }); }
Source:
public boolean isValid(CruiseConfig preprocessedConfig) { for (PipelineConfig pipeline : preprocessedConfig.getAllPipelineConfigs()) { if(pipeline.materialConfigs().hasDependencyMaterial(pipelineConfig)){ Localizable.CurryableLocalizable message = LocalizedMessage.string("CANNOT_DELETE_PIPELINE_USED_AS_MATERIALS", pipelineConfig.name(), pipeline.name()); this.result.unprocessableEntity(message); return false; } } for (EnvironmentConfig environment : goConfigService.getEnvironments()) { if(environment.getPipelineNames().contains(pipelineConfig.name())){ Localizable.CurryableLocalizable message = LocalizedMessage.string("CANNOT_DELETE_PIPELINE_IN_ENVIRONMENT", pipelineConfig.name(), environment.name()); this.result.unprocessableEntity(message); return false; } } return true; }

Target:
public boolean isValid(CruiseConfig preprocessedConfig) { for (PipelineConfig pipeline : preprocessedConfig.getAllPipelineConfigs()) { if(pipeline.materialConfigs().hasDependencyMaterial(pipelineConfig)){ Localizable.CurryableLocalizable message = LocalizedMessage.string("CANNOT_DELETE_PIPELINE_USED_AS_MATERIALS", pipelineConfig.name(), String.format("%s (%s)", pipeline.name(), pipeline.getOriginDisplayName())); this.result.unprocessableEntity(message); return false; } } for (EnvironmentConfig environment : preprocessedConfig.getEnvironments()) { if(environment.getPipelineNames().contains(pipelineConfig.name())){ Localizable.CurryableLocalizable message = LocalizedMessage.string("CANNOT_DELETE_PIPELINE_IN_ENVIRONMENT", pipelineConfig.name(), environment.name()); this.result.unprocessableEntity(message); return false; } } return true; }
Source:
public void testSnapshotLocalPartitionNotEnoughSpace() throws Exception { final AtomicInteger throwCntr = new AtomicInteger(); IgniteEx ig = startGridWithCache(defaultCacheCfg.setAffinity(new ZeroPartitionAffinityFunction() .setPartitions(CACHE_PARTS_COUNT)), CACHE_KEYS_RANGE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ig.cache(DEFAULT_CACHE_NAME).put(i, 2 * i); GridCacheSharedContext<?, ?> cctx0 = ig.context().cache().context(); IgniteSnapshotManager mgr = cctx0.snapshotMgr(); mgr.ioFactory(new FileIOFactory() { @Override public FileIO create(File file, OpenOption... modes) throws IOException { FileIO fileIo = DFLT_IO_FACTORY.create(file, modes); if (file.getName().equals(IgniteSnapshotManager.partDeltaFileName(0))) return new FileIODecorator(fileIo) { @Override public int writeFully(ByteBuffer srcBuf) throws IOException { if (throwCntr.incrementAndGet() == 3) throw new IOException("Test exception. Not enough space."); return super.writeFully(srcBuf); } }; return fileIo; } }); IgniteInternalFuture<?> snpFut = startLocalSnapshotTask(cctx0.snapshotMgr(), (GridCacheDatabaseSharedManager)cctx0.database(), cctx0.localNodeId(), SNAPSHOT_NAME, F.asMap(CU.cacheId(DEFAULT_CACHE_NAME), null), cctx0.snapshotMgr().localSnapshotSender(SNAPSHOT_NAME)); snpFut.get(); }

Target:
public void testSnapshotLocalPartitionNotEnoughSpace() throws Exception { String err_msg = "Test exception. Not enough space."; AtomicInteger throwCntr = new AtomicInteger(); RandomAccessFileIOFactory ioFactory = new RandomAccessFileIOFactory(); IgniteEx ig = startGridWithCache(dfltCacheCfg.setAffinity(new ZeroPartitionAffinityFunction()), CACHE_KEYS_RANGE); for (int i = 0; i < CACHE_KEYS_RANGE; i++) ig.cache(DEFAULT_CACHE_NAME).put(i, 2 * i); GridCacheSharedContext<?, ?> cctx0 = ig.context().cache().context(); IgniteSnapshotManager mgr = snp(ig); mgr.ioFactory(new FileIOFactory() { @Override public FileIO create(File file, OpenOption... modes) throws IOException { FileIO fileIo = ioFactory.create(file, modes); if (file.getName().equals(IgniteSnapshotManager.partDeltaFileName(0))) return new FileIODecorator(fileIo) { @Override public int writeFully(ByteBuffer srcBuf) throws IOException { if (throwCntr.incrementAndGet() == 3) throw new IOException(err_msg); return super.writeFully(srcBuf); } }; return fileIo; } }); IgniteInternalFuture<?> snpFut = startLocalSnapshotTask(cctx0, SNAPSHOT_NAME, F.asMap(CU.cacheId(DEFAULT_CACHE_NAME), null), mgr.localSnapshotSender(SNAPSHOT_NAME)); assertThrowsAnyCause(log, snpFut::get, IOException.class, err_msg); }
Source:
private String getExpectedInstructorHomePageLink(InstructorAttributes instructor) { String googleId = instructor.isRegistered() ? instructor.googleId : "undefined"; return createUrl(Const.WebPageURIs.INSTRUCTOR_HOME_PAGE) .withUserId(googleId) .toAbsoluteString(); }

Target:
private String getExpectedInstructorHomePageLink(InstructorAttributes instructor) { String googleId = instructor.isRegistered() ? instructor.googleId : ""; return createUrl(Const.WebPageURIs.INSTRUCTOR_HOME_PAGE) .withUserId(googleId) .toAbsoluteString(); }
Source:
public void testWorkflowWriteWithoutOpening() throws Exception { DBObjectToVariantConverter converter = new DBObjectToVariantConverter(); VariantWrapper variantWrapper = new VariantWrapper( converter.convertToDataModelType(constructDbObject(VariantData.getVariantWithAnnotation()))); annotationParameters.setVepPath(getResource("/mockvep_writeToFile_delayed.pl").getAbsolutePath()); VepProcess vepAnnotationFileWriter = new VepProcess(annotationParameters, CHUNK_SIZE, VEP_TIMEOUT); exception.expect(IllegalStateException.class); exception.expectMessage(Matchers.contains(HINT_CALL_OPEN)); vepAnnotationFileWriter.write(getVariantInVepInputFormat(variantWrapper).getBytes()); }

Target:
public void testWorkflowWriteWithoutOpening() throws Exception { VepProcess vepAnnotationFileWriter = new VepProcess(annotationParameters, CHUNK_SIZE, VEP_TIMEOUT); exception.expect(IllegalStateException.class); vepAnnotationFileWriter.write(getVariantInVepInputFormat(VARIANT_WRAPPER).getBytes()); }
Source:
public void publishModel(int tenantId, String userName, long modelId) throws MLModelBuilderException { InputStream in = null; try { MLStorage storage = databaseService.getModelStorage(modelId); String storageType = storage.getType(); String storageLocation = storage.getLocation(); MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLInputAdapter inputAdapter = ioFactory.getInputAdapter(storageType + MLConstants.IN_SUFFIX); in = inputAdapter.read(new URI(storageLocation)); MLCoreServiceValueHolder valueHolder = MLCoreServiceValueHolder.getInstance(); String modelName = databaseService.getModel(tenantId, userName, modelId).getName(); String registryPath = File.separator + valueHolder.getModelRegistryLocation() + File.separator + modelName; RegistryOutputAdapter registryOutputAdapter = new RegistryOutputAdapter(); registryOutputAdapter.write(registryPath, in); } catch (Exception e) { throw new MLModelBuilderException("Failed to publish the model [id] " + modelId, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }

Target:
public void publishModel(int tenantId, String userName, long modelId) throws MLModelPublisherException { InputStream in = null; try { MLStorage storage = databaseService.getModelStorage(modelId); String storageType = storage.getType(); String storageLocation = storage.getLocation(); MLIOFactory ioFactory = new MLIOFactory(mlProperties); MLInputAdapter inputAdapter = ioFactory.getInputAdapter(storageType + MLConstants.IN_SUFFIX); in = inputAdapter.read(new URI(storageLocation)); if (in == null) { throw new MLModelPublisherException("Invalid model [id] " + modelId); } MLCoreServiceValueHolder valueHolder = MLCoreServiceValueHolder.getInstance(); String modelName = databaseService.getModel(tenantId, userName, modelId).getName(); String registryPath = File.separator + valueHolder.getModelRegistryLocation() + File.separator + modelName; RegistryOutputAdapter registryOutputAdapter = new RegistryOutputAdapter(); registryOutputAdapter.write(registryPath, in); } catch (Exception e) { throw new MLModelPublisherException("Failed to publish the model [id] " + modelId, e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { } } } }
Source:
public <X> X unwrap(final Clob value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } try { if ( CharacterStream.class.isAssignableFrom( type ) ) { if ( ClobImplementer.class.isInstance( value ) ) { return (X) ( (ClobImplementer) value ).getUnderlyingStream(); } else { return (X) new CharacterStreamImpl( DataHelper.extractString( value.getCharacterStream() ) ); } } else if (Clob.class.isAssignableFrom( type )) { final Clob clob = WrappedClob.class.isInstance( value ) ? ( (WrappedClob) value ).getWrappedClob() : value; return (X) clob; } else if ( String.class.isAssignableFrom( type ) ) { if ( ClobImplementer.class.isInstance( value ) ) { return (X) ( (ClobImplementer) value ).getUnderlyingStream().asString(); } else { return (X) DataHelper.extractString( value.getCharacterStream() ); } } } catch ( SQLException e ) { throw new HibernateException( "Unable to access clob stream", e ); } throw unknownUnwrap( type ); }

Target:
public <X> X unwrap(final Clob value, Class<X> type, WrapperOptions options) { if ( value == null ) { return null; } try { if ( CharacterStream.class.isAssignableFrom( type ) ) { if (value instanceof ClobImplementer) { return (X) ( (ClobImplementer) value ).getUnderlyingStream(); } else { return (X) new CharacterStreamImpl( DataHelper.extractString( value.getCharacterStream() ) ); } } else if (Clob.class.isAssignableFrom( type )) { final Clob clob = value instanceof WrappedClob ? ( (WrappedClob) value ).getWrappedClob() : value; return (X) clob; } else if ( String.class.isAssignableFrom( type ) ) { if (value instanceof ClobImplementer) { return (X) ( (ClobImplementer) value ).getUnderlyingStream().asString(); } else { return (X) DataHelper.extractString( value.getCharacterStream() ); } } } catch ( SQLException e ) { throw new HibernateException( "Unable to access clob stream", e ); } throw unknownUnwrap( type ); }
Source:
public static String desanitizeFromHtml(String sanitizedString) { if (sanitizedString == null) { return null; } return sanitizedString.replace("&lt;", "<") .replace("&gt;", ">") .replace("&quot;", "\"") .replace("&#x2f;", "/") .replace("&#39;", "'") .replace("&#34;", "\"") .replace("&amp;", "&"); }

Target:
public static String desanitizeFromHtml(String sanitizedString) { if (sanitizedString == null) { return null; } return sanitizedString.replace("&lt;", "<") .replace("&gt;", ">") .replace("&quot;", "\"") .replace("&#x2f;", "/") .replace("&#39;", "'") .replace("&amp;", "&"); }
Source:
protected void onBind() { super.onBind(); Scheduler.get().scheduleDeferred(() -> { addPluginActionButtons( actionButtonPluginHandler.getButtons(getProxy().getTargetHistoryToken()), false); addPluginActionButtons( actionButtonPluginHandler.getMenuItems(getProxy().getTargetHistoryToken()), false); }); registerHandler(getEventBus().addHandler(AddActionButtonEvent.getType(), event -> { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { List<ActionButtonDefinition<?>> pluginActionButtonList = new ArrayList<>(); pluginActionButtonList.add(event.getButtonDefinition()); addPluginActionButtons(pluginActionButtonList, false); } })); registerHandler(getEventBus().addHandler(AddKebabMenuListItemEvent.getType(), event -> { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { List<ActionButtonDefinition<?>> pluginActionButtonList = new ArrayList<>(); pluginActionButtonList.add(event.getButtonDefinition()); addPluginActionButtons(pluginActionButtonList, true); } })); }

Target:
protected void onBind() { super.onBind(); Scheduler.get().scheduleDeferred(() -> { addPluginActionButtons( actionButtonPluginHandler.getButtons(getProxy().getTargetHistoryToken()), false); addPluginActionButtons( actionButtonPluginHandler.getMenuItems(getProxy().getTargetHistoryToken()), true); }); registerHandler(getEventBus().addHandler(AddActionButtonEvent.getType(), event -> { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { List<ActionButtonDefinition<?>> pluginActionButtonList = new ArrayList<>(); pluginActionButtonList.add(event.getButtonDefinition()); addPluginActionButtons(pluginActionButtonList, false); } })); registerHandler(getEventBus().addHandler(AddKebabMenuListItemEvent.getType(), event -> { if (getProxy().getTargetHistoryToken().equals(event.getHistoryToken())) { List<ActionButtonDefinition<?>> pluginActionButtonList = new ArrayList<>(); pluginActionButtonList.add(event.getButtonDefinition()); addPluginActionButtons(pluginActionButtonList, true); } })); }
Source:
protected Subscription initSourceObject() { Subscription source = new Subscription(); source.setId("test_id"); source.setOwner(this.createOwner()); source.setProduct(this.createProduct()); source.setDerivedProduct(this.createProduct()); source.setProvidedProducts(this.createProducts()); source.setDerivedProvidedProducts(this.createProducts()); source.setQuantity(15L); source.setStartDate(new Date()); source.setEndDate(new Date()); source.setContractNumber("test_contact"); source.setAccountNumber("test_acc_num"); source.setModified(new Date()); source.setOrderNumber("test_order_num"); source.setUpstreamPoolId("test_pool_id"); source.setUpstreamEntitlementId("test_ent_id"); source.setUpstreamConsumerId("test_cons_id"); source.setCertificate(this.createCert()); source.setCdn(this.createCdn()); return source; }

Target:
protected Subscription initSourceObject() { Subscription source = new Subscription(); source.setId("test_id"); source.setOwner(this.ownerTest.initSourceObject()); source.setProduct(this.productTest.initSourceObject()); source.setDerivedProduct(this.productTest.initSourceObject()); source.setProvidedProducts(this.createProducts()); source.setDerivedProvidedProducts(this.createProducts()); source.setQuantity(15L); source.setStartDate(new Date()); source.setEndDate(new Date()); source.setContractNumber("test_contact"); source.setAccountNumber("test_acc_num"); source.setModified(new Date()); source.setCreated(new Date()); source.setUpdated(new Date()); source.setOrderNumber("test_order_num"); source.setUpstreamPoolId("test_pool_id"); source.setUpstreamEntitlementId("test_ent_id"); source.setUpstreamConsumerId("test_cons_id"); source.setCertificate(this.createCert()); source.setCdn(this.cdnTest.initSourceObject()); return source; }
Source:
public String toString() { return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", proxyType=" + proxy.getType() + ", inetSocketProxyAddress=" + proxy.getAddress() + '}'; }

Target:
public String toString() { String proxyType = proxy != null ? proxy.getType().toString() : null; String proxyAddress = proxy != null ? proxy.getAddress().toString() : null; return "GatewayConnectionConfig{" + "requestTimeout=" + requestTimeout + ", maxConnectionPoolSize=" + maxConnectionPoolSize + ", idleConnectionTimeout=" + idleConnectionTimeout + ", proxyType=" + proxyType + ", inetSocketProxyAddress=" + proxyAddress + '}'; }
Source:
public void testConvertToDataTypeWithoutStatsWithSampleIds() { uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantSourceEntryConverter converter; DBObject convertedMongo; VariantSourceEntry convertedFile; converter = new uk.ac.ebi.eva.commons.models.converters.data.DBObjectToVariantSourceEntryConverter( VariantStorageManager.IncludeSrc.FULL, new DBObjectToSamplesConverter(true, sampleIds) ); convertedFile = converter.convert(mongoFileWithIds); assertEquals(file, convertedFile); converter = new DBObjectToVariantSourceEntryConverter( VariantStorageManager.IncludeSrc.FULL, new DBObjectToSamplesConverter(true, sampleIds) ); convertedFile = converter.convert(mongoFileWithIds); assertEquals(file, convertedFile); }

Target:
public void testConvertToDataTypeWithoutStatsWithSampleIds() { DBObjectToVariantSourceEntryConverter converter; DBObject convertedMongo; VariantSourceEntry convertedFile; converter = new DBObjectToVariantSourceEntryConverter( new DBObjectToSamplesConverter(true, sampleIds) ); convertedFile = converter.convert(mongoFileWithIds); assertEquals(file, convertedFile); converter = new DBObjectToVariantSourceEntryConverter( new DBObjectToSamplesConverter(true, sampleIds) ); convertedFile = converter.convert(mongoFileWithIds); assertEquals(file, convertedFile); }
Source:
private Future<?> submitPublishingWork() { return this.publisherExecutor.submit(new Runnable() { @Override public void run() { Thread.currentThread().setName("DataServiceImpl:Submit"); if (!DataServiceImpl.this.dataTransportService.isConnected()) { logger.info("DataPublisherService not connected"); return; } try { DataMessage message = null; while ((message = DataServiceImpl.this.store.getNextMessage()) != null) { if (message.getQos() > 0) { if (DataServiceImpl.this.inFlightMsgIds.size() >= (Integer) DataServiceImpl.this.properties .get(MAX_IN_FLIGHT_MSGS_PROP_NAME)) { logger.warn("The configured maximum number of in-flight messages has been reached"); handleInFlightCongestion(); break; } } tryPublishInternal(message); } } catch (KuraConnectException e) { logger.info("DataPublisherService is not connected", e); } catch (KuraTooManyInflightMessagesException e) { logger.info("Too many in-flight messages", e); handleInFlightCongestion(); } catch (Exception e) { logger.error("Probably an unrecoverable exception", e); } } }); }

Target:
private void submitPublishingWork() { publisherEnabled.set(true); this.publisherExecutor.execute(new PublishManager()); }
Source:
public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Proxy type is not supported " + proxy.getType()); } this.proxy = proxy; return this; }

Target:
public GatewayConnectionConfig setProxy(ProxyOptions proxy) { if (proxy.getType() != ProxyOptions.Type.HTTP) { throw new IllegalArgumentException("Only http proxy type is supported."); } this.proxy = proxy; return this; }
Source:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; boolean recreatePage = false; for (AbstractTaskEditorSection section : sections) { if (!section.supportsRefreshing()) { recreatePage = true; break; } } if (recreatePage) { Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); for (AbstractTaskEditorSection section : sections) { section.dispose(); } sections.clear(); editorComposite.setMenu(menu); createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }

Target:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; boolean recreatePage = false; for (AbstractTaskEditorPart part : parts) { if (part.hasIncomingChanges() && !part.supportsRefreshing()) { recreatePage = true; break; } } if (recreatePage) { Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); for (Control control : editorComposite.getChildren()) { control.dispose(); } for (AbstractTaskEditorPart part : parts) { part.dispose(); getManagedForm().removePart(part); } parts.clear(); editorComposite.setMenu(menu); createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }
Source:
public void execute(JobExecutionContext jobContext) throws JobExecutionException { LOGGER.info("********* Starting the Summary Statistics Creation job. *********"); try { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); LOGGER.info("Getting all listings."); List<CertifiedProductDetailsDTO> allListings = certifiedProductDAO.findAll(); LOGGER.info("Completing getting all listings."); EmailStatistics emailBodyStats = emailStatisticsCreator.getStatistics(allListings); saveSummaryStatistics(emailBodyStats); Boolean generateCsv = Boolean.valueOf(jobContext.getMergedJobDataMap().getString("generateCsvFile")); if (generateCsv) { createSummaryStatisticsFile(allListings, jobContext); } } catch (Exception e) { LOGGER.error("Caught unexpected exception: " + e.getMessage(), e); } LOGGER.info("********* Completed the Summary Statistics Creation job. *********"); }

Target:
public void execute(JobExecutionContext jobContext) throws JobExecutionException { LOGGER.info("********* Starting the Summary Statistics Creation job. *********"); try { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); LOGGER.info("Getting all listings."); List<CertifiedProductDetailsDTO> allListings = certifiedProductDAO.findAll(); LOGGER.info("Completing getting all listings."); EmailStatistics emailBodyStats = emailStatisticsCreator.getStatistics(allListings); saveSummaryStatistics(emailBodyStats); createSummaryStatisticsFile(allListings, jobContext); } catch (Exception e) { LOGGER.error("Caught unexpected exception: " + e.getMessage(), e); } LOGGER.info("********* Completed the Summary Statistics Creation job. *********"); }
Source:
public static short byteArrayToShort(byte[] b) { return (short) (((b[0] << 8) & 0xFF00) | b[1] & 0x00FF); }

Target:
public static short byteArrayToShort(byte[] b) { if (b == null) throw new NullPointerException("Byte array cannot be null."); return (short) (((b[0] << 8) & 0xFF00) | b[1] & 0x00FF); }
Source:
public static int getVirtualBucket(int bucketCount, Path path) { return (hashBytes(0, wrappedBuffer(path.toString().getBytes())) & Integer.MAX_VALUE) % bucketCount; }

Target:
public static int getVirtualBucket(int bucketCount, Path path) { return (hashBytes(0, utf8Slice(path.toString())) & Integer.MAX_VALUE) % bucketCount; }
Source:
public void prepare(User user) { File newUserDirectory = getUserRepoDirectory(user); try { if (!newUserDirectory.exists()) { createUserRepo(user, newUserDirectory); createGitConfig(user); } } catch (SVNException e) { LOG.error("Error while prepare user {}'s repo", user.getUserName(), e); } }

Target:
public void prepare(User user) { File newUserDirectory = getUserRepoDirectory(user); try { if (!newUserDirectory.exists()) { createUserRepo(user, newUserDirectory); createGitHubConfig(user); } } catch (SVNException e) { LOG.error("Error while prepare user {}'s repo", user.getUserName(), e); } }
Source:
public Document getDocument() { return this.additionalProperties; }

Target:
public SearchDocument getDocument() { return this.additionalProperties; }
Source:
void refreshAccessToken(OAuth2Parameters parameters) throws OAuthProblemException, OAuthSystemException { OAuthClientRequest accessTokenRequest = OAuthClientRequest .tokenLocation(parameters.accessTokenUri) .setGrantType(GrantType.REFRESH_TOKEN) .setClientId(parameters.clientId) .setClientSecret(parameters.clientSecret) .setRefreshToken(parameters.refreshToken) .buildBodyMessage(); OAuthClient oAuthClient = getOAuthClient(); OAuthToken oAuthToken = oAuthClient.accessToken(accessTokenRequest, OAuthJSONAccessTokenResponse.class).getOAuthToken(); parameters.applyRetrievedAccessToken(oAuthToken.getAccessToken()); parameters.setAccessTokenIssuedTimeInProfile(TimeUtils.getCurrentTimeInSeconds()); String newRefreshToken = oAuthToken.getRefreshToken(); if (newRefreshToken!=null && newRefreshToken!=parameters.refreshToken) { parameters.setRefreshTokenInProfile(newRefreshToken); } }

Target:
void refreshAccessToken(OAuth2Parameters parameters) throws OAuthProblemException, OAuthSystemException { OAuthClientRequest accessTokenRequest = OAuthClientRequest .tokenLocation(parameters.accessTokenUri) .setGrantType(GrantType.REFRESH_TOKEN) .setClientId(parameters.clientId) .setClientSecret(parameters.clientSecret) .setRefreshToken(parameters.refreshToken) .buildBodyMessage(); OAuthClient oAuthClient = getOAuthClient(); OAuthToken oAuthToken = oAuthClient.accessToken(accessTokenRequest, OAuthJSONAccessTokenResponse.class).getOAuthToken(); parameters.applyRetrievedAccessToken(oAuthToken.getAccessToken()); parameters.setAccessTokenIssuedTimeInProfile(TimeUtils.getCurrentTimeInSeconds()); String newRefreshToken = oAuthToken.getRefreshToken(); if (newRefreshToken!=null && !newRefreshToken.equals(parameters.refreshToken)) { parameters.setRefreshTokenInProfile(newRefreshToken); } }
Source:
public Emailer(Props props) { super(props); this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); this.mailSender = props.getString("mail.sender", ""); int mailTimeout = props.getInt("mail.timeout.millis", 10000); EmailMessage.setTimeout(mailTimeout); int connectionTimeout = props.getInt("mail.connection.timeout.millis", 10000); EmailMessage.setConnectionTimeout(connectionTimeout); this.clientHostname = props.getString("jetty.hostname", "localhost"); if (props.getBoolean("jetty.use.ssl", true)) { this.scheme = "https"; this.clientPortNumber = props.getString("jetty.ssl.port"); } else { this.scheme = "http"; this.clientPortNumber = props.getString("jetty.port"); } testMode = props.getBoolean("test.mode", false); }

Target:
public Emailer(Props props) { super(props); this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); this.mailSender = props.getString("mail.sender", ""); int mailTimeout = props.getInt("mail.timeout.millis", 10000); EmailMessage.setTimeout(mailTimeout); int connectionTimeout = props.getInt("mail.connection.timeout.millis", 10000); EmailMessage.setConnectionTimeout(connectionTimeout); this.clientHostname = props.getString("jetty.hostname", "localhost"); if (props.getBoolean("jetty.use.ssl", true)) { this.scheme = HTTPS; this.clientPortNumber = props.getString("jetty.ssl.port"); } else { this.scheme = HTTP; this.clientPortNumber = props.getString("jetty.port"); } testMode = props.getBoolean("test.mode", false); }
Source:
protected boolean connectLunDisks(Guid hostId) { if (getVm().getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(getVm()); } List<LunDisk> lunDisks = DisksFilter.filterLunDisks(getVm().getDiskMap().values()); Set<String> connections = new HashSet<>(); for (LunDisk lunDisk : lunDisks) { LUNs lun = lunDisk.getLun(); lun.setLunConnections(new ArrayList<>(storageServerConnectionDao.getAllForLun(lun.getLUNId()))); if (lun.getLunConnections().isEmpty()) { log.error("The LUN connection list is empty and cannot be explicitly connected. It may be connected" + "already but its details is unknown", lun); } List<String> connectionIds = lun.getLunConnections() .stream() .map(c -> c.getId()) .collect(Collectors.toList()); boolean cacheUpdated = connections.addAll(connectionIds); if (cacheUpdated && !connect(hostId, lun)) { log.error("Failed to connect a LUN disk '{}' to VDSM '{}' skipping it", lun, hostId); return false; } } return true; }

Target:
protected boolean connectLunDisks(Guid hostId) { if (getVm().getDiskMap().isEmpty()) { vmHandler.updateDisksFromDb(getVm()); } List<LunDisk> lunDisks = DisksFilter.filterLunDisks(getVm().getDiskMap().values()); Set<String> connections = new HashSet<>(); for (LunDisk lunDisk : lunDisks) { LUNs lun = lunDisk.getLun(); lun.setLunConnections(new ArrayList<>(storageServerConnectionDao.getAllForLun(lun.getLUNId()))); if (lun.getLunConnections().isEmpty()) { continue; } List<String> connectionIds = lun.getLunConnections() .stream() .map(c -> c.getId()) .collect(Collectors.toList()); boolean cacheUpdated = connections.addAll(connectionIds); if (cacheUpdated && !connect(hostId, lun)) { log.error("Failed to connect a LUN disk '{}' to VDSM '{}' skipping it", lun, hostId); return false; } } return true; }
Source:
public boolean isRecord() throws JavaModelException { SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); if( TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL) { return CharOperation.equals(info.getSuperclassName(), RecordDeclaration.super_class); } return false; }

Target:
public boolean isRecord() throws JavaModelException { SourceTypeElementInfo info = (SourceTypeElementInfo) getElementInfo(); if( TypeDeclaration.kind(info.getModifiers()) == TypeDeclaration.CLASS_DECL) { return CharOperation.equals(info.getSuperclassName(), TypeConstants.CharArray_JAVA_LANG_RECORD); } return false; }
Source:
public void escapeFunctionWithDate() throws Exception { Parser.replaceProcessing("{fn week({d '2005-01-24'})}", true, false); }

Target:
public String escapeFunctionWithDate() throws Exception { return Parser.replaceProcessing(fnEscapeSQL, replaceProcessingEnabled, standardConformingStrings); }
Source:
private synchronized boolean setNextFilePartCopy() { if (filePartCopyIndexPointer + 1 >= prioritizedCopyIndexes.size()) return false; filePartCopyIndexPointer++; return true; }

Target:
private boolean setNextFilePartCopy() { if (filePartCopyIndexPointer + 1 >= prioritizedCopyIndexes.size()) return false; filePartCopyIndexPointer++; return true; }
Source:
private void refreshResources(GitResourceVariantTreeSubscriber subscriber, Collection<IFile> resources) { final IResource[] iResources = resources .toArray(new IResource[resources.size()]); try { subscriber.refresh(iResources, IResource.DEPTH_ONE, new NullProgressMonitor()); } catch (final CoreException e) { Activator .error(CoreText.GitSubscriberMergeContext_FailedRefreshSyncView, e); } }

Target:
private void refreshResources(GitResourceVariantTreeSubscriber subscriber, Collection<IFile> resources) { IResource[] iResources = resources.toArray(new IResource[resources .size()]); try { subscriber.refresh(iResources, IResource.DEPTH_ONE, new NullProgressMonitor()); } catch (final CoreException e) { Activator .logError( CoreText.GitSubscriberMergeContext_FailedRefreshSyncView, e); } }
Source:
private void validateRegistrationFields() { Bundle parameters = getRegistrationParameter(); if (parameters == null) { return; } showProgress(); final Map<String, String> parameterMap = new HashMap<>(); for (String key : parameters.keySet()) { parameterMap.put(key, parameters.getString(key)); } Call<JsonObject> validateRegistrationFields = loginService.validateRegistrationFields(parameterMap); validateRegistrationFields.enqueue(new ErrorHandlingCallback<JsonObject>(this) { @Override protected void onResponse(@NonNull JsonObject responseBody) { final Type stringMapType = new TypeToken<HashMap<String, String>>() { }.getType(); final HashMap<String, String> messageBody = new Gson().fromJson(responseBody.get("validation_decisions"), stringMapType); if (hasValidationError(messageBody)) { hideProgress(); } else { createAccount(parameters); } } @Override protected void onFailure(@NonNull Throwable error) { hideProgress(); RegisterActivity.this.showAlertDialog(null, ErrorUtils.getErrorMessage(error, RegisterActivity.this)); logger.error(error); } }); }

Target:
private void validateRegistrationFields() { Bundle parameters = getRegistrationParameters(); if (parameters == null) { return; } showProgress(); final Map<String, String> parameterMap = new HashMap<>(); for (String key : parameters.keySet()) { parameterMap.put(key, parameters.getString(key)); } Call<JsonObject> validateRegistrationFields = loginService.validateRegistrationFields(parameterMap); validateRegistrationFields.enqueue(new ErrorHandlingCallback<JsonObject>(this) { @Override protected void onResponse(@NonNull JsonObject responseBody) { final Type stringMapType = new TypeToken<HashMap<String, String>>() { }.getType(); final HashMap<String, String> messageBody = new Gson().fromJson(responseBody.get(ApiConstants.VALIDATION_DECISIONS), stringMapType); if (hasValidationError(messageBody)) { hideProgress(); } else { createAccount(parameters); } } @Override protected void onFailure(@NonNull Throwable error) { hideProgress(); RegisterActivity.this.showAlertDialog(null, ErrorUtils.getErrorMessage(error, RegisterActivity.this)); logger.error(error); } }); }