auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void initialize(Configuration config) { this.config = config; eventProcessorRegistry().registerHandlerInvoker(processorInfo.getName(), c -> sagaManager.get()); eventProcessorRegistry().registerTokenStore(processorInfo.getName(), c -> tokenStore.get()); eventProcessorRegistry().configureMessageMonitor(processorInfo.getName(), c -> (MessageMonitor<Message<?>>) messageMonitor.get()); eventProcessorRegistry().configureErrorHandler(processorInfo.getName(), c -> errorHandler.get()); eventProcessorRegistry().configureRollbackConfiguration(processorInfo.getName(), c -> rollbackConfiguration.get()); eventProcessorRegistry().configureTransactionManager(processorInfo.getName(), c -> transactionManager.get()); handlerInterceptors.forEach(i -> eventProcessorRegistry() .registerHandlerInterceptor(processorInfo.getName(), i)); if (processorInfo.isCreateNewProcessor()) { switch (processorInfo.getType()) { case TRACKING: eventProcessorRegistry().registerEventProcessor(processorInfo.getName(), this::buildTrackingEventProcessor); break; case SUBSCRIBING: eventProcessorRegistry().registerEventProcessor(processorInfo.getName(), this::buildSubscribingEventProcessor); break; default: throw new IllegalStateException("Unsupported event processor type."); } } }

Target:
public void initialize(Configuration config) { this.config = config; eventProcessingConfiguration().registerHandlerInvoker(processorInfo.getProcessingGroup(), c -> sagaManager.get()); eventProcessingConfiguration().registerTokenStore(processorInfo.getProcessingGroup(), c -> tokenStore.get()); eventProcessingConfiguration().configureMessageMonitor(processorInfo.getProcessingGroup(), c -> (MessageMonitor<Message<?>>) messageMonitor.get()); eventProcessingConfiguration().configureErrorHandler(processorInfo.getProcessingGroup(), c -> errorHandler.get()); eventProcessingConfiguration().configureRollbackConfiguration(processorInfo.getProcessingGroup(), c -> rollbackConfiguration.get()); eventProcessingConfiguration().configureTransactionManager(processorInfo.getProcessingGroup(), c -> transactionManager.get()); handlerInterceptors.forEach(i -> eventProcessingConfiguration() .registerHandlerInterceptor(processorInfo.getProcessingGroup(), i)); if (processorInfo.isCreateNewProcessor()) { switch (processorInfo.getType()) { case TRACKING: eventProcessingConfiguration().registerEventProcessor(processorInfo.getProcessingGroup(), this::buildTrackingEventProcessor); break; case SUBSCRIBING: eventProcessingConfiguration().registerEventProcessor(processorInfo.getProcessingGroup(), this::buildSubscribingEventProcessor); break; default: throw new IllegalStateException("Unsupported event processor type."); } } }
Source:
protected EmbeddedCacheManager createBackingEmbeddedCacheManager() throws IOException { if (configurationFileLocation != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ParserRegistry(Thread.currentThread().getContextClassLoader()) .parse(configurationFileLocation.getInputStream()); if(gcb != null) { configurationBuilderHolder.getGlobalConfigurationBuilder().read(gcb.build()); } if (builder != null) { configurationBuilderHolder.getDefaultConfigurationBuilder().read(builder.build()); } return createCacheManager(configurationBuilderHolder); } else { if (gcb == null) { if (logger.isDebugEnabled()) logger.debug("GlobalConfigurationBuilder is null. Using default new " + "instance."); gcb = new GlobalConfigurationBuilder(); gcb.globalJmxStatistics().allowDuplicateDomains(true); } if (builder == null) { if (logger.isDebugEnabled()) logger.debug("ConfigurationBuilder is null. Using default new instance."); builder = new ConfigurationBuilder(); } return createCacheManager(gcb, builder); } }

Target:
protected EmbeddedCacheManager createBackingEmbeddedCacheManager() throws IOException { if (configurationFileLocation != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ParserRegistry(Thread.currentThread().getContextClassLoader()) .parse(configurationFileLocation.getInputStream()); if(gcb != null) { configurationBuilderHolder.getGlobalConfigurationBuilder().read(gcb.build()); } if (builder != null) { configurationBuilderHolder.getDefaultConfigurationBuilder().read(builder.build()); } return new DefaultCacheManager(configurationBuilderHolder, true); } else { if (gcb == null) { if (logger.isDebugEnabled()) logger.debug("GlobalConfigurationBuilder is null. Using default new " + "instance."); gcb = new GlobalConfigurationBuilder(); gcb.globalJmxStatistics().allowDuplicateDomains(true); } if (builder == null) { if (logger.isDebugEnabled()) logger.debug("ConfigurationBuilder is null. Using default new instance."); builder = new ConfigurationBuilder(); } return new DefaultCacheManager(gcb.build(), builder.build()); } }
Source:
public Object getValueAt(int rowIndex, int columnIndex) { FormStatus form = forms.get(rowIndex); switch (columnIndex) { case TransferFormsTableView.SELECTED_CHECKBOX_COL: return form.isSelected(); case TransferFormsTableView.FORM_NAME_COL: return form.getFormName(); case TransferFormsTableView.PULL_COL: return form.isPullSelected(); case TransferFormsTableView.PUSH_COL: return form.isPushSelected(); case TransferFormsTableView.EXPORT_COL: return form.isExportSelected(); case TransferFormsTableView.DETAIL_BUTTON_COL: return detailButtons.computeIfAbsent(form, UI::buildDetailButton); default: throw new IllegalStateException("unexpected column choice"); } }

Target:
public Object getValueAt(int rowIndex, int columnIndex) { FormStatus form = forms.get(rowIndex); switch (columnIndex) { case TransferFormsTableView.SELECTED_CHECKBOX_COL: return form.isSelected(); case TransferFormsTableView.FORM_NAME_COL: return form.getFormName(); case TransferFormsTableView.PULL_COL: return forms.isPullSelected(form); case TransferFormsTableView.PUSH_COL: return forms.isPushSelected(form); case TransferFormsTableView.EXPORT_COL: return forms.isExportSelected(form); case TransferFormsTableView.DETAIL_BUTTON_COL: return detailButtons.computeIfAbsent(form, UI::buildDetailButton); default: throw new IllegalStateException("unexpected column choice"); } }
Source:
public static Timestamp getCurrentTimeOnDB(Connection conn, Calendar cal) throws SQLException, ConnectException { Statement stmt = conn.createStatement(); ResultSet rs; String query; String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) query = "select CURRENT_TIMESTAMP from dual"; else if ("Apache Derby".equals(dbProduct)) query = "values(CURRENT_TIMESTAMP)"; else query = "select CURRENT_TIMESTAMP "; try { rs = stmt.executeQuery(query); if (rs.next()) return rs.getTimestamp(1, cal); else throw new ConnectException("Unable to get current time from DB using query " + query + " on database " + dbProduct); } catch (SQLException e) { log.error("Failed to get current time from DB using query " + query + " on database " + dbProduct, e); throw e; } }

Target:
public static Timestamp getCurrentTimeOnDB(Connection conn, Calendar cal) throws SQLException, ConnectException { Statement stmt = conn.createStatement(); ResultSet rs = null; String query; String dbProduct = conn.getMetaData().getDatabaseProductName(); if ("Oracle".equals(dbProduct)) query = "select CURRENT_TIMESTAMP from dual"; else if ("Apache Derby".equals(dbProduct)) query = "values(CURRENT_TIMESTAMP)"; else query = "select CURRENT_TIMESTAMP;"; try { log.debug("executing query " + query + " to get current time from database"); rs = stmt.executeQuery(query); if (rs.next()) return rs.getTimestamp(1, cal); else throw new ConnectException("Unable to get current time from DB using query " + query + " on database " + dbProduct); } catch (SQLException e) { log.error("Failed to get current time from DB using query " + query + " on database " + dbProduct, e); throw e; } finally { if (rs != null) rs.close(); if (stmt != null) stmt.close(); } }
Source:
private void processExternallyManagedVms() { _externalVmsToAdd.clear(); for (VmInternalData vmInternalData : _runningVms.values()) { VM currentVmData = _vmDict.get(vmInternalData.getVmDynamic().getId()); if (currentVmData == null) { if (getDbFacade().getVmDao().get(vmInternalData.getVmDynamic().getId()) == null) { Guid vmId = vmInternalData.getVmDynamic().getId(); Map vmConfiguration = getVmInfo(vmId.toString())[0]; VmStatic vmStatic = new VmStatic(); vmStatic.setOrigin(OriginType.valueOf(Config.<String>GetValue(ConfigValues.OriginType))); vmStatic.setId(vmId); vmStatic.setQuotaId(null); vmStatic.setCreationDate(new Date()); vmStatic.setVdsGroupId(_vds.getVdsGroupId()); String vmNameOnHost = (String) vmConfiguration.get(VdsProperties.vm_name); String vmName = "external-" + vmNameOnHost; vmStatic.setName(vmName); vmStatic.setNumOfSockets(Integer.parseInt((String) vmConfiguration.get(VdsProperties.num_of_cpus))); vmStatic.setMemSizeMb(Integer.parseInt((String) vmConfiguration.get(VdsProperties.mem_size_mb))); vmStatic.setExternallyManaged(true); _externalVmsToAdd.add(vmStatic); log.infoFormat("VDS::UpdateVmRunTimeInfo: Importing VM {0} as {1}, as it is running on the on Host, but does not exist in the engine.", vmNameOnHost, vmName); } } } }

Target:
private void processExternallyManagedVms() { _externalVmsToAdd.clear(); List<String> vmsToQuery = new ArrayList<String>(); for (VmInternalData vmInternalData : _runningVms.values()) { VM currentVmData = _vmDict.get(vmInternalData.getVmDynamic().getId()); if (currentVmData == null) { if (getDbFacade().getVmStaticDao().get(vmInternalData.getVmDynamic().getId()) == null) { Guid vmId = vmInternalData.getVmDynamic().getId(); vmsToQuery.add(vmId.toString()); } } } if (!vmsToQuery.isEmpty()) { Map[] vmsInfo = getVmInfo(vmsToQuery); for (Map vmInfo : vmsInfo) { Guid vmId = Guid.createGuidFromString((String) vmInfo.get(VdsProperties.vm_guid)); VmStatic vmStatic = new VmStatic(); vmStatic.setId(vmId); vmStatic.setCreationDate(new Date()); vmStatic.setVdsGroupId(_vds.getVdsGroupId()); String vmNameOnHost = (String) vmInfo.get(VdsProperties.vm_name); String vmName = "external-" + vmNameOnHost; vmStatic.setName(vmName); vmStatic.setNumOfSockets(Integer.parseInt((String) vmInfo.get(VdsProperties.num_of_cpus))); vmStatic.setMemSizeMb(Integer.parseInt((String) vmInfo.get(VdsProperties.mem_size_mb))); vmStatic.setExternallyManaged(true); _externalVmsToAdd.add(vmStatic); log.infoFormat("Importing VM {0} as {1}, as it is running on the on Host, but does not exist in the engine.", vmNameOnHost, vmName); } } }
Source:
SafeHtml asTr() { return new SafeHtmlBuilder() .appendHtmlConstant("<tr>") .appendHtmlConstant("<td>").appendEscaped(event).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.node).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.start.toString()).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.getEnd()).appendHtmlConstant("</td>") .appendHtmlConstant("</tr>") .toSafeHtml(); }

Target:
SafeHtml asTr() { return new SafeHtmlBuilder() .appendHtmlConstant("<tr>") .appendHtmlConstant("<td>").appendEscaped(this.event).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.node).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.start.toString()).appendHtmlConstant("</td>") .appendHtmlConstant("<td>").appendEscaped(this.getEnd()).appendHtmlConstant("</td>") .appendHtmlConstant("</tr>") .toSafeHtml(); }
Source:
private void validate(String beforeReformat, String afterReformat) { String normalizedBefore = getNormalized(beforeReformat); String normalizedAfter = getNormalized(afterReformat); if (!normalizedBefore.equalsIgnoreCase(normalizedAfter)) { int minLen = Math.min(normalizedAfter.length(), normalizedBefore .length()); StringBuilder diffPos = new StringBuilder(); for (int i = 0; i < minLen; ++i) { if (Character.toUpperCase(normalizedBefore.charAt(i)) != Character .toUpperCase(normalizedAfter.charAt(i))) { break; } diffPos.append('-'); } diffPos.append('^'); StringBuilder msg = new StringBuilder(I18N.getString("orbisgis.core.ui.plugins.views.sqlConsole.codereformat.reformatFailed")); msg.append(_lineSep); msg.append(normalizedBefore); msg.append(_lineSep); msg.append(normalizedAfter); msg.append(_lineSep); msg.append(diffPos.toString()); msg.append(_lineSep); if (s_log.isInfoEnabled()) { s_log.info(msg.toString()); } throw new IllegalStateException(msg.toString()); } }

Target:
private void validate(String beforeReformat, String afterReformat) { String normalizedBefore = getNormalized(beforeReformat); String normalizedAfter = getNormalized(afterReformat); if (!normalizedBefore.equalsIgnoreCase(normalizedAfter)) { int minLen = Math.min(normalizedAfter.length(), normalizedBefore .length()); StringBuilder diffPos = new StringBuilder(); for (int i = 0; i < minLen; ++i) { if (Character.toUpperCase(normalizedBefore.charAt(i)) != Character .toUpperCase(normalizedAfter.charAt(i))) { break; } diffPos.append('-'); } diffPos.append('^'); StringBuilder msg = new StringBuilder(I18N.tr("Reformat failed, normalised strings differ")); msg.append(_lineSep); msg.append(normalizedBefore); msg.append(_lineSep); msg.append(normalizedAfter); msg.append(_lineSep); msg.append(diffPos.toString()); msg.append(_lineSep); if (s_log.isInfoEnabled()) { s_log.info(msg.toString()); } throw new IllegalStateException(msg.toString()); } }
Source:
public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); MPLog.d(LOGTAG, "MP FCM notification received: " + mixpanelPushNotification.getData().getMessage()); if (null != notification) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final int id = new Random().nextInt(Integer.MAX_VALUE); if (mixpanelPushNotification.getData().getTag() != null) { notificationManager.notify(mixpanelPushNotification.getData().getTag(), 0, notification); } else { notificationManager.notify(id, notification); } } }

Target:
public static void showPushNotification(Context context, Intent messageIntent, MixpanelPushNotification mixpanelPushNotification) { Notification notification = mixpanelPushNotification.createNotification(messageIntent); MixpanelNotificationData data = mixpanelPushNotification.getData(); String message = data == null ? "null" : data.getMessage(); MPLog.d(LOGTAG, "MP FCM notification received: " + message); if (null != notification) { final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); final int id = new Random().nextInt(Integer.MAX_VALUE); if (mixpanelPushNotification.getData().getTag() != null) { notificationManager.notify(mixpanelPushNotification.getData().getTag(), 0, notification); } else { notificationManager.notify(id, notification); } } }
Source:
public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) { try { List entities; if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.ASCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"asc\" }", first, pageSize, filters); } else if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.DESCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"desc\" }", first, pageSize, filters); } else { entities = searchService.findAll(null, first, pageSize, filters); } logger.info(entities.size() + " entities loaded!"); return entities; } catch (DataException e) { logger.error(e.getMessage()); return new LinkedList(); } }

Target:
public List load(int first, int pageSize, String sortField, SortOrder sortOrder, Map filters) { try { setRowCount(toIntExact(searchService.count(searchService.createCountQuery(filters)))); List entities; if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.ASCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"asc\" }", first, pageSize, filters); } else if (!Objects.equals(sortField, null) && Objects.equals(sortOrder, SortOrder.DESCENDING)) { entities = searchService.findAll("{\"" + sortField + "\":\"desc\" }", first, pageSize, filters); } else { entities = searchService.findAll(null, first, pageSize, filters); } logger.info(entities.size() + " entities loaded!"); return entities; } catch (DataException e) { logger.error(e.getMessage()); return new LinkedList(); } }
Source:
public Date getStartDate() { return startDate; }

Target:
public Date getStartDate() { return startDate == null ? null : new Date(startDate.getTime()); }
Source:
public static List<Map<String,String>> getAvailableMetadataFormats() { List<Map<String,String>> configs = new ArrayList<>(); String metaString = "oai.harvester.metadataformats."; Enumeration pe = Collections.enumeration( DSpaceServicesFactory.getInstance().getConfigurationService().getPropertyKeys("oai") ); while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); if (key.startsWith(metaString)) { String metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); String id = key.substring(metaString.length()); String label; String namespace = ""; if (metadataString.indexOf(',') != -1) { label = metadataString.substring(metadataString.indexOf(',') + 2); namespace = metadataString.substring(0, metadataString.indexOf(',')); } else { label = id + "(" + metadataString + ")"; } Map<String,String> config = new HashMap<>(); config.put("id", id); config.put("label", label); config.put("namespace", namespace); configs.add(config); } } return configs; }

Target:
public static List<Map<String,String>> getAvailableMetadataFormats() { List<Map<String,String>> configs = new ArrayList<>(); String metaString = "oai.harvester.metadataformats."; Enumeration pe = Collections.enumeration( DSpaceServicesFactory.getInstance().getConfigurationService() .getPropertyKeys("oai.harvester.metadataformats") ); while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); String metadataString = DSpaceServicesFactory.getInstance().getConfigurationService().getProperty(key); String id = key.substring(metaString.length()); String label; String namespace = ""; if (metadataString.indexOf(',') != -1) { label = metadataString.substring(metadataString.indexOf(',') + 2); namespace = metadataString.substring(0, metadataString.indexOf(',')); } else { label = id + "(" + metadataString + ")"; } Map<String,String> config = new HashMap<>(); config.put("id", id); config.put("label", label); config.put("namespace", namespace); configs.add(config); } return configs; }
Source:
protected boolean isTargetDirectoryForbidden() { File nuxeoHome = ConfigurationGenerator.retrieveNuxeoHome(); return Paths.get(directory).startsWith(nuxeoHome.toPath()); }

Target:
protected boolean isTargetDirectoryForbidden() { File nuxeoHome = ConfigurationGenerator.retrieveNuxeoHome(); return Paths.get(directory) .toAbsolutePath() .normalize() .startsWith(nuxeoHome.toPath().toAbsolutePath().normalize()); }
Source:
public InvocationStage toInvocationStage(Supplier<TimeoutException> timeoutSupplier) { if (notifier.isDone()) { return checkState(notifier.getNow(lockState), InvocationStage::completedNullStage, ExceptionSyncInvocationStage::new, timeoutSupplier); } return new SimpleAsyncInvocationStage(CompletionStages.continueOnExecutor(notifier.thenApplyAsync(state -> { Object rv = checkState(state, () -> null, throwable -> throwable, timeoutSupplier); if (rv != null) { throw (RuntimeException) rv; } return null; }, blockingExecutor), nonBlockingExecutor, this)); }

Target:
public InvocationStage toInvocationStage(Supplier<TimeoutException> timeoutSupplier) { if (notifier.isDone()) { return checkState(notifier.getNow(lockState), InvocationStage::completedNullStage, ExceptionSyncInvocationStage::new, timeoutSupplier); } return new SimpleAsyncInvocationStage(notifier.thenApplyAsync(state -> { Object rv = checkState(state, () -> null, throwable -> throwable, timeoutSupplier); if (rv != null) { throw (RuntimeException) rv; } return null; }, nonBlockingExecutor)); }
Source:
public void push() { if (Session.getCredentials().isLogged()) { Log.d(TAG, "execute push"); executePush(); } else { Log.d(TAG, "execute push fails, not logged"); } }

Target:
public void push() { if (Session.getCredentials().isDemoCredentials()) { Log.d(TAG, "execute push"); executeMockedPush(); } else { Log.d(TAG, "execute push fails, not logged"); } }
Source:
public void setVariable(final String identifier, final String content) { setVariable(identifier, content, null); }

Target:
public void setVariable(final String identifier, final String content) { Variable variable = getVariable(identifier); if (variable != null) { variable.setContent(content); fDirty = true; return; } this.addVariable(identifier, content, null); }
Source:
public Integer addGroup(String nameOfGroup) { ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { PreparedStatement statement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_GROUPS + "(" + Constants.GROUPS_GROUP_NAME + ")" + " VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS ); statement.setString(1, nameOfGroup); statement.executeUpdate(); results = statement.getGeneratedKeys(); int groupId = -1; if (results.next()) { groupId = results.getInt(1); } else { throw new Exception("Could not add group"); } return groupId; } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) results.close(); } catch (Exception e) { } } return null; }

Target:
public Integer addGroup(String nameOfGroup) { PreparedStatement queryStatement = null; ResultSet results = null; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "INSERT INTO " + Constants.DB_TABLE_GROUPS + "(" + Constants.GROUPS_GROUP_NAME + ")" + " VALUES (?)", PreparedStatement.RETURN_GENERATED_KEYS ); queryStatement.setString(1, nameOfGroup); queryStatement.executeUpdate(); results = queryStatement.getGeneratedKeys(); int groupId = -1; if (results.next()) { groupId = results.getInt(1); } else { throw new Exception("Could not add group"); } return groupId; } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return null; }
Source:
private CompletionStage<RestResponse> convertToJson(RestRequest restRequest) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = restRequest.contents(); ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(contents.rawContent(), UTF_8)); ConfigurationBuilder builder = builderHolder.getNamedConfigurationBuilders().values().iterator().next(); Configuration configuration = builder.build(); return CompletableFuture.completedFuture(responseBuilder .contentType(APPLICATION_JSON) .entity(JSON_WRITER.toJSON(configuration)) .build()); }

Target:
private CompletionStage<RestResponse> convertToJson(RestRequest restRequest) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); ContentSource contents = restRequest.contents(); ConfigurationBuilderHolder builderHolder = PARSER_REGISTRY.parse(new String(contents.rawContent(), UTF_8)); ConfigurationBuilder builder = builderHolder.getNamedConfigurationBuilders().values().iterator().next(); Configuration configuration = builder.build(); responseBuilder.contentType(APPLICATION_JSON) .entity(JSON_WRITER.toJSON(configuration)); return CompletableFuture.completedFuture(responseBuilder.build()); }
Source:
private void injectBootstrapper() throws InfrastructureException { String machineName = kubernetesMachine.getName(); LOG.debug( "Bootstrapping {}:{}. Creating folder for bootstrapper", runtimeIdentity, machineName); kubernetesMachine.exec("mkdir", "-p", BOOTSTRAPPER_DIR, bootstrapperLogsFolder); LOG.debug("Bootstrapping {}:{}. Downloading bootstrapper binary", runtimeIdentity, machineName); kubernetesMachine.exec( "curl", "-o", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE, bootstrapperBinaryUrl); kubernetesMachine.exec("chmod", "+x", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE); LOG.debug("Bootstrapping {}:{}. Creating config file", runtimeIdentity, machineName); List<String> filesToContatenate = new ArrayList<String>(); filesToContatenate.add("["); boolean firstOne = true; for (Installer installer : installers) { if (firstOne) { firstOne = false; } else { filesToContatenate.add(","); } filesToContatenate.add(GSON.toJson(installer)); } filesToContatenate.add("]"); int counter = 1; for (String fileToConcatenate : filesToContatenate) { kubernetesMachine.exec( "sh", "-c", "cat > " + BOOTSTRAPPER_DIR + CONFIG_FILE + "____" + counter + " << 'EOF'\n" + fileToConcatenate + "\nEOF"); counter++; } String generalConcatCommand = "cat "; for (int i = 1; i < counter; i++) { generalConcatCommand += BOOTSTRAPPER_DIR + CONFIG_FILE + "____" + i + " "; } generalConcatCommand += "> " + BOOTSTRAPPER_DIR + CONFIG_FILE; LOG.debug("Executing {}", "sh -c '" + generalConcatCommand + "'"); kubernetesMachine.exec("sh", "-c", generalConcatCommand); kubernetesMachine.exec("sh", "-c", "rm " + BOOTSTRAPPER_DIR + CONFIG_FILE + "____*"); }

Target:
private void injectBootstrapper() throws InfrastructureException { String machineName = kubernetesMachine.getName(); LOG.debug( "Bootstrapping {}:{}. Creating folder for bootstrapper", runtimeIdentity, machineName); kubernetesMachine.exec("mkdir", "-p", BOOTSTRAPPER_DIR, bootstrapperLogsFolder); LOG.debug("Bootstrapping {}:{}. Downloading bootstrapper binary", runtimeIdentity, machineName); kubernetesMachine.exec( "curl", "-o", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE, bootstrapperBinaryUrl); kubernetesMachine.exec("chmod", "+x", BOOTSTRAPPER_DIR + BOOTSTRAPPER_FILE); LOG.debug("Bootstrapping {}:{}. Creating config file", runtimeIdentity, machineName); kubernetesMachine.exec("sh", "-c", "rm " + BOOTSTRAPPER_DIR + CONFIG_FILE); List<String> contentsToContatenate = new ArrayList<String>(); contentsToContatenate.add("["); boolean firstOne = true; for (Installer installer : installers) { if (firstOne) { firstOne = false; } else { contentsToContatenate.add(","); } contentsToContatenate.add(GSON.toJson(installer)); } contentsToContatenate.add("]"); for (String content : contentsToContatenate) { kubernetesMachine.exec( "sh", "-c", "cat >> " + BOOTSTRAPPER_DIR + CONFIG_FILE + " << 'EOF'\n" + content + "\nEOF"); } }
Source:
public H2YearWeekFunction() { super("(select CONCAT(extract(year from DATE_TRUNC('week', x.y)), '-', iso_week(x.y)) from (values (?1)) x(y))"); }

Target:
public H2YearWeekFunction() { super("CONCAT(extract(year from DATE_TRUNC('week', ?1)), '-', iso_week(?1))"); }
Source:
private static void NonOperationalPoolTreatment(storage_pool pool) { boolean changeStatus = false; if (DbFacade.getInstance().getVdsDAO().getActiveVdsByPoolId(pool.getId()).size() > 0) { changeStatus = true; } if (changeStatus) { log.info("Moving data center " + pool.getname() + " with Id " + pool.getId() + " to status Problematic from status NotOperational on a one time basis to try to recover"); Backend.getInstance().runInternalAction( VdcActionType.SetStoragePoolStatus, new SetStoragePoolStatusParameters(pool.getId(), StoragePoolStatus.Problematic, AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_FROM_NON_OPERATIONAL)); synchronized (_nonOperationalPools) { _nonOperationalPools.remove(pool.getId()); } } }

Target:
private static void NonOperationalPoolTreatment(storage_pool pool) { boolean changeStatus = false; if (DbFacade.getInstance().getVdsDAO().getAllByPoolIdAndStatus(pool.getId(), VDSStatus.Up).size() > 0) { changeStatus = true; } if (changeStatus) { log.info("Moving data center " + pool.getname() + " with Id " + pool.getId() + " to status Problematic from status NotOperational on a one time basis to try to recover"); Backend.getInstance().runInternalAction( VdcActionType.SetStoragePoolStatus, new SetStoragePoolStatusParameters(pool.getId(), StoragePoolStatus.Problematic, AuditLogType.SYSTEM_CHANGE_STORAGE_POOL_STATUS_PROBLEMATIC_FROM_NON_OPERATIONAL)); synchronized (_nonOperationalPools) { _nonOperationalPools.remove(pool.getId()); } } }
Source:
public void testProgress() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = 100; Mockito.when(logger.isLoggable(any())).thenReturn(true); try (final Progress progress = new Progress(logger, "foo", totalCount)) { assertNotNull(progress.getLoggerThread()); while (progress.getLoggerThread().getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { progress.increment(); while (progress.getLoggerThread().getState() != Thread.State.WAITING) { TimeUnit.MILLISECONDS.sleep(10); } } } Mockito.verify(logger, times(totalCount)).log(any(), anyString(), any(Object[].class)); }

Target:
public void testProgress() throws InterruptedException { final Logger logger = Mockito.mock(Logger.class); final int totalCount = 100; Thread loggerThread = null; Mockito.when(logger.isLoggable(any())).thenReturn(true); try (final Progress progress = new Progress(logger, "foo", totalCount)) { assertNotNull(progress.getLoggerThread()); loggerThread = progress.getLoggerThread(); while (loggerThread.getState() != Thread.State.WAITING) { System.out.println("Waiting for the logger thread to reach the initial wait()"); TimeUnit.MILLISECONDS.sleep(10); } for (int i = 0; i < totalCount; i++) { progress.increment(); while (loggerThread.getState() != Thread.State.WAITING) { TimeUnit.MILLISECONDS.sleep(10); } } } System.out.println("Waiting for the logger thread to terminate"); int i = 0; while (i < 3 && loggerThread.getState() != Thread.State.TERMINATED) { TimeUnit.MILLISECONDS.sleep(10); i++; } Assert.assertSame(loggerThread.getState(), Thread.State.TERMINATED); Mockito.verify(logger, times(totalCount)).log(any(), anyString(), any(Object[].class)); }
Source:
default boolean hasParticipant(User user) { for (ChangeLogSet<? extends ChangeLogSet.Entry> c : getChangeSets()) { for (ChangeLogSet.Entry e : c) try { if (e.getAuthor() == user) return true; } catch (RuntimeException re) { Logger LOGGER = Logger.getLogger(RunWithSCM.class.getName()); LOGGER.log(Level.INFO, "Failed to determine author of changelog " + e.getCommitId() + "for " + ((RunT)this).getParent().getDisplayName() + ", " + ((RunT)this).getDisplayName(), re); } } return false; }

Target:
default boolean hasParticipant(User user) { for (ChangeLogSet<? extends ChangeLogSet.Entry> c : getChangeSets()) { for (ChangeLogSet.Entry e : c) { try { if (e.getAuthor() == user) { return true; } } catch (RuntimeException re) { Logger LOGGER = Logger.getLogger(RunWithSCM.class.getName()); LOGGER.log(Level.INFO, "Failed to determine author of changelog " + e.getCommitId() + "for " + ((RunT) this).getParent().getDisplayName() + ", " + ((RunT) this).getDisplayName(), re); } } } return false; }
Source:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { setClampHeight(1.0f); collectTote(); setClampHeight(0.0f); QuasarHelios.clamp.openControl.set(true); drive(nudge.get()); QuasarHelios.clamp.openControl.set(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); setClampHeight(0.0f); QuasarHelios.clamp.openControl.set(true); drive(nudge.get()); QuasarHelios.clamp.openControl.set(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); turn(90); drive(autoZoneDistance.get()); DriveCode.octocanumShifting.set(true); DriveCode.octocanumShifting.set(false); }

Target:
protected void runAutonomous() throws InterruptedException, AutonomousModeOverException { setClampHeight(1.0f); collectTote(); setClampHeight(0.0f); setClampOpen(true); drive(nudge.get()); setClampOpen(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); setClampHeight(0.0f); setClampOpen(true); drive(nudge.get()); setClampOpen(false); setClampHeight(1.0f); drive(toteDistance.get()); collectTote(); turn(90); drive(autoZoneDistance.get()); DriveCode.octocanumShifting.set(true); DriveCode.octocanumShifting.set(false); }
Source:
public void addOrUpdateAlert(final Alert alert) { LOGGER.info() .setMessage("This is a read only repository.") .log(); }

Target:
public void addOrUpdateAlert(final Alert alert) { throw new UnsupportedOperationException("This is a read only repository."); }
Source:
protected BasicNameValuePair addPair(QueryParam queryParam) { return new BasicNameValuePair(queryParam.name(), queryParam.value()); }

Target:
private BasicNameValuePair addPair(QueryParam queryParam) { return new BasicNameValuePair(queryParam.name(), queryParam.value()); }
Source:
public void end() { int c; synchronized (this) { c = count; } if (total == UNKNOWN && c > 0) { wakeUp(); } }

Target:
public void end() { if (total == UNKNOWN && getCount() > 0) { wakeUp(); } }
Source:
protected TextPresentation createPresentation(IRegion damage, IDocument document) { TextPresentation presentation = super.createPresentation(damage, document); IDocument doc = textViewer.getDocument(); URI uri = Server2ClientProtocolExtension.getUri(doc); if (uri == null) { return presentation; } Position[] returnedPositions = null; List<StyleRange> styleRanges = new ArrayList<>(); HighlightedPosition[] highlightedPositions; try { returnedPositions = doc.getPositions(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); } catch (BadPositionCategoryException e) { Activator.log(e); } if(returnedPositions == null) { return presentation; } highlightedPositions = Arrays.copyOf(returnedPositions, returnedPositions.length, HighlightedPosition[].class); int damageStartOffset = damage.getOffset(); int damageEndOffset = damageStartOffset + damage.getLength(); for(HighlightedPosition eachPosition : highlightedPositions) { if ((eachPosition.getOffset() + eachPosition.getLength()) >= damageStartOffset && eachPosition.getOffset() < damageEndOffset) { StyleRange range = eachPosition.createStyleRange(); styleRanges.add(range); } } StyleRange[] styleRangesArray = new StyleRange[styleRanges.size()]; styleRangesArray = styleRanges.toArray(styleRangesArray); presentation.replaceStyleRanges(styleRangesArray); return presentation; }

Target:
protected TextPresentation createPresentation(IRegion damage, IDocument document) { TextPresentation presentation = super.createPresentation(damage, document); IDocument doc = textViewer.getDocument(); URI uri = Server2ClientProtocolExtension.getUri(doc); if (uri == null) { return presentation; } Position[] returnedPositions = null; List<StyleRange> styleRanges = new ArrayList<>(); HighlightedPosition[] highlightedPositions; doc.addPositionCategory(PresentationReconcilerCPP.SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); try { returnedPositions = doc.getPositions(SEMANTIC_HIGHLIGHTING_POSITION_CATEGORY); } catch (BadPositionCategoryException e) { Activator.log(e); } if (returnedPositions == null) { return presentation; } highlightedPositions = Arrays.copyOf(returnedPositions, returnedPositions.length, HighlightedPosition[].class); int damageStartOffset = damage.getOffset(); int damageEndOffset = damageStartOffset + damage.getLength(); for (HighlightedPosition eachPosition : highlightedPositions) { if ((eachPosition.getOffset() + eachPosition.getLength()) >= damageStartOffset && eachPosition.getOffset() < damageEndOffset) { StyleRange range = eachPosition.createStyleRange(); styleRanges.add(range); } } StyleRange[] styleRangesArray = new StyleRange[styleRanges.size()]; styleRangesArray = styleRanges.toArray(styleRangesArray); presentation.replaceStyleRanges(styleRangesArray); return presentation; }
Source:
private Selection<ResourceBasedNode< ? >> getExplorerSelection() { final Selection<ResourceBasedNode< ? >> selection = (Selection<ResourceBasedNode< ? >>)projectExplorer.getSelection(); if (selection == null || selection.isEmpty() || selection.getHeadElement() instanceof HasStorablePath) { return selection; } else { return null; } }

Target:
private Selection<?> getExplorerSelection() { final Selection<?> selection = selectionAgent.getSelection(); if (selection == null || selection.isEmpty() || selection.getHeadElement() instanceof HasStorablePath) { return selection; } else { return null; } }
Source:
private void parseValue(String fieldName) { int chr = sr.read(); if (chr == QUOTATION_MARK) { int beginToken = sr.getPosition(); while (true) { chr = sr.read(); if (chr == BACKSLASH) { sr.read(); } else if (chr == QUOTATION_MARK) { break; } else if (chr == -1) { throw new IllegalArgumentException("EOF reached while reading JSON field name"); } } addParameter(fieldName, beginToken, sr.getPosition()-1, false, true); } else if (Character.isDigit(chr) || chr == '-') { sr.unreadLastCharacter(); int beginToken = sr.getPosition(); do { chr = sr.read(); if (chr == -1) { throw new IllegalArgumentException("Reached EOF while reading number"); } } while (Character.isDigit(chr) || (chr == '.') || (chr == 'e') || (chr == 'E') || (chr == '+') || (chr == '-')); sr.unreadLastCharacter(); addParameter(fieldName, beginToken, sr.getPosition()-1, true, false); } else if (chr == BEGIN_OBJECT) { sr.unreadLastCharacter(); parseObject(); } else if (chr == BEGIN_ARRAY) { parseArray(fieldName); } else if (chr == END_ARRAY) { sr.unreadLastCharacter(); } else if (chr == 't' || chr == 'T') { sr.unreadLastCharacter(); parseToken("true"); } else if (chr == 'f' || chr == 'F') { sr.unreadLastCharacter(); parseToken("false"); } else if (chr == 'n' || chr == 'N') { sr.unreadLastCharacter(); parseToken("null"); } else if (chr == -1) { throw new IllegalArgumentException("EOF reached prematurely"); } else { throw new IllegalArgumentException("Unknown value type at position " + sr.getPosition()); } }

Target:
private void parseValue(String fieldName) { int chr = sr.read(); if (chr == QUOTATION_MARK) { int beginToken = sr.getPosition(); readEscapedString(); addParameter(fieldName, beginToken, sr.getPosition()-1, false, true); } else if (Character.isDigit(chr) || chr == '-') { sr.unreadLastCharacter(); int beginToken = sr.getPosition(); do { chr = sr.read(); if (chr == -1) { throw new IllegalArgumentException("Reached EOF while reading number"); } } while (Character.isDigit(chr) || (chr == '.') || (chr == 'e') || (chr == 'E') || (chr == '+') || (chr == '-')); sr.unreadLastCharacter(); addParameter(fieldName, beginToken, sr.getPosition()-1, true, false); } else if (chr == BEGIN_OBJECT) { sr.unreadLastCharacter(); parseObject(); } else if (chr == BEGIN_ARRAY) { parseArray(fieldName); } else if (chr == END_ARRAY) { sr.unreadLastCharacter(); } else if (chr == 't' || chr == 'T') { sr.unreadLastCharacter(); parseToken("true"); } else if (chr == 'f' || chr == 'F') { sr.unreadLastCharacter(); parseToken("false"); } else if (chr == 'n' || chr == 'N') { sr.unreadLastCharacter(); parseToken("null"); } else if (chr == -1) { throw new IllegalArgumentException("EOF reached prematurely"); } else { throw new IllegalArgumentException("Unknown value type at position " + sr.getPosition()); } }
Source:
public static void main(String[] args) throws InterruptedException { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClientBuilder() .connectionString(connectionString) .buildClient(); QueueProperties queueProperties = administrationClient.getQueue("<<queue-name>>"); System.out.printf("Before update queue properties status :[%s], Max Delivery count :[%d]. %n" , queueProperties.getStatus(), queueProperties.getMaxDeliveryCount()); queueProperties.setStatus(EntityStatus.DISABLED); queueProperties.setMaxDeliveryCount(9); QueueProperties updatedQueueProperties = administrationClient.updateQueue(queueProperties); System.out.printf("After update queue properties status :[%s], Max Delivery count :[%d]. %n" , updatedQueueProperties.getStatus(), updatedQueueProperties.getMaxDeliveryCount()); }

Target:
public static void main(String[] args) { String connectionString = "Endpoint={fully-qualified-namespace};SharedAccessKeyName={policy-name};" + "SharedAccessKey={key}"; ServiceBusAdministrationClient client = new ServiceBusAdministrationClientBuilder() .connectionString(connectionString) .buildClient(); QueueProperties properties = client.getQueue("<<queue-name>>"); System.out.printf("Before queue properties LockDuration: [%d seconds], Max Delivery count: [%d].%n", properties.getLockDuration().getSeconds(), properties.getMaxDeliveryCount()); properties.setMaxDeliveryCount(10).setLockDuration(Duration.ofSeconds(60)); QueueProperties updatedProperties = client.updateQueue(properties); System.out.printf("After queue properties LockDuration: [%d seconds], Max Delivery count: [%d].%n", updatedProperties.getLockDuration().getSeconds(), updatedProperties.getMaxDeliveryCount()); }
Source:
public void setValues(LinkedFile linkedFile) { description.set(linkedFile.getDescription()); link.setValue(linkedFile.getLink()); selectedExternalFileType.setValue(null); Optional<ExternalFileType> fileType = externalFileTypes.fromLinkedFile(linkedFile, false); if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } }

Target:
public void setValues(LinkedFile linkedFile) { description.set(linkedFile.getDescription()); if (linkedFile.isOnlineLink()) { link.setValue(linkedFile.getLink()); } else { link.setValue(relativize(Paths.get(linkedFile.getLink()))); } selectedExternalFileType.setValue(null); Optional<ExternalFileType> fileType = externalFileTypes.fromLinkedFile(linkedFile, false); if (fileType.isPresent() && !(fileType.get() instanceof UnknownExternalFileType)) { selectedExternalFileType.setValue(fileType.get()); } else if ((linkedFile.getLink() != null) && (!linkedFile.getLink().isEmpty())) { setExternalFileTypeByExtension(linkedFile.getLink()); } }
Source:
public void run() throws IOException, InterruptedException { String jobName = System.getenv(AbstractProcessJob.JOB_NAME_ENV); _logger.info("Running job " + jobName); String tokenFile = System.getenv(HADOOP_TOKEN_FILE_LOCATION); UserGroupInformation proxyUser = HadoopSecureWrapperUtils.setupProxyUser(_jobProps, tokenFile, _logger); proxyUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runCopyTdToHdfs(); return null; } }); }

Target:
public void run() throws IOException, InterruptedException { String jobName = System.getenv(AbstractProcessJob.JOB_NAME_ENV); _logger.info("Running job " + jobName); if (HadoopSecureWrapperUtils.shouldProxy(_jobProps)) { String tokenFile = System.getenv(HADOOP_TOKEN_FILE_LOCATION); UserGroupInformation proxyUser = HadoopSecureWrapperUtils.setupProxyUser(_jobProps, tokenFile, _logger); proxyUser.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { runCopyTdToHdfs(); return null; } }); } else { runCopyTdToHdfs(); } }
Source:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && (!formatString.contains("{}") && formatString.contains("%")); }

Target:
private static boolean isProbablyLog4jFormatterLogger(MethodInvocationTree mit, String formatString) { return mit.symbol().owner().type().is(ORG_APACHE_LOGGING_LOG4J_LOGGER) && !formatString.contains("{}") && formatString.contains("%"); }
Source:
public void testAlreadyCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false, NEVER_SKIP)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3 | WebSocketExtension.RSV1, Unpooled.wrappedBuffer(payload)); encoderChannel.writeOutbound(frame); BinaryWebSocketFrame newFrame = encoderChannel.readOutbound(); assertNotNull(newFrame); assertNotNull(newFrame.content()); assertEquals(WebSocketExtension.RSV3 | WebSocketExtension.RSV1, newFrame.rsv()); assertEquals(300, newFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; newFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); newFrame.release(); }

Target:
public void testAlreadyCompressedFrame() { EmbeddedChannel encoderChannel = new EmbeddedChannel(new PerFrameDeflateEncoder(9, 15, false)); byte[] payload = new byte[300]; random.nextBytes(payload); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(true, WebSocketExtension.RSV3 | WebSocketExtension.RSV1, Unpooled.wrappedBuffer(payload)); assertTrue(encoderChannel.writeOutbound(frame)); BinaryWebSocketFrame newFrame = encoderChannel.readOutbound(); assertNotNull(newFrame); assertNotNull(newFrame.content()); assertEquals(WebSocketExtension.RSV3 | WebSocketExtension.RSV1, newFrame.rsv()); assertEquals(300, newFrame.content().readableBytes()); byte[] finalPayload = new byte[300]; newFrame.content().readBytes(finalPayload); assertArrayEquals(finalPayload, payload); newFrame.release(); }
Source:
private void forwardMessage(FirebaseMessage o) { Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody(o); try { getProcessor().process(exchange); } catch (Exception e) { throw new FirebaseException("Message forwarding failed", e); } finally { if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException()); } } }

Target:
private void forwardMessage(FirebaseMessage o) { Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody(o); try { getProcessor().process(exchange); } catch (Exception e) { exchange.setException(new RuntimeCamelException("Message forwarding failed", e)); } finally { if (exchange.getException() != null) { getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException()); } } }
Source:
public static RegistrationRequest getNewInstance(String json) { RegistrationRequest request = new RegistrationRequest(); try { JsonObject o = new JsonParser().parse(json).getAsJsonObject(); if (o.has("name")) request.setName(o.get("name").getAsString()); if (o.has("description")) request.setDescription(o.get("description").getAsString()); JsonObject config = o.get("configuration").getAsJsonObject(); GridNodeConfiguration configuration = new JsonToBeanConverter().convert(GridNodeConfiguration.class, config); request.setConfiguration(configuration); if (o.has("id")) request.configuration.id = o.get("id").getAsString(); JsonArray capabilities = o.get("capabilities").getAsJsonArray(); for (int i = 0; i < capabilities.size(); i++) { DesiredCapabilities cap = new JsonToBeanConverter() .convert(DesiredCapabilities.class, capabilities.get(i)); request.capabilities.add(cap); } return request; } catch (JsonSyntaxException e) { return null; } }

Target:
public static RegistrationRequest getNewInstance(String json) throws JsonSyntaxException { RegistrationRequest request = new RegistrationRequest(); JsonObject o = new JsonParser().parse(json).getAsJsonObject(); if (o.has("name")) { request.setName(o.get("name").getAsString()); } if (o.has("description")) { request.setDescription(o.get("description").getAsString()); } JsonObject config = o.get("configuration").getAsJsonObject(); GridNodeConfiguration configuration = new JsonToBeanConverter().convert(GridNodeConfiguration.class, config); request.setConfiguration(configuration); if (o.has("id")) { request.configuration.id = o.get("id").getAsString(); } JsonArray capabilities = o.get("capabilities").getAsJsonArray(); for (int i = 0; i < capabilities.size(); i++) { DesiredCapabilities cap = new JsonToBeanConverter() .convert(DesiredCapabilities.class, capabilities.get(i)); request.capabilities.add(cap); } return request; }