auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public final void testAlterTableUnsetProperty() throws Exception { executeDDL("table2_ddl.sql", "table2.tbl", "ALTY"); String tableName = IdentifierUtil.buildFQName(getCurrentDatabase(), "alty"); assertTrue(catalog.existsTable(tableName)); TableDesc tableDesc = catalog.getTableDesc(tableName); TableMeta tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 3); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); assertEquals(tableMeta.getProperty("text.delimiter"), "\\u002b"); executeDDL("alter_table_unset_property_delimiter.sql", null); tableDesc = catalog.getTableDesc(tableName); tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 2); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); executeDDL("alter_table_unset_not_exists_property.sql", null); tableDesc = catalog.getTableDesc(tableName); tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 2); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); }

Target:
public final void testAlterTableUnsetProperty() throws Exception { executeDDL("table2_ddl.sql", "table2.tbl", "ALTY"); String tableName = IdentifierUtil.buildFQName(getCurrentDatabase(), "alty"); assertTrue(catalog.existsTable(tableName)); TableDesc tableDesc = catalog.getTableDesc(tableName); TableMeta tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 3); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); assertEquals(tableMeta.getProperty("text.delimiter"), "\\u002b"); executeDDL("alter_table_unset_property_delimiter.sql", null); tableDesc = catalog.getTableDesc(tableName); tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 2); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); assertFalse(tableMeta.getPropertySet().containsKey("text.delimiter")); executeDDL("alter_table_unset_not_exists_property.sql", null); tableDesc = catalog.getTableDesc(tableName); tableMeta = tableDesc.getMeta(); assertEquals(tableMeta.getPropertySet().size(), 2); assertNotNull(tableMeta.getProperty("timezone")); assertNotNull(tableMeta.getProperty("text.null")); assertFalse(tableMeta.getPropertySet().containsKey("text.delimiter")); }
Source:
public void updated(Dictionary config) throws ConfigurationException { if (config != null) { String ip = (String) config.get("ip"); if (StringUtils.isNotBlank(ip)) { if (!ip.equals(FritzboxBinding.ip)) { FritzboxBinding.ip = ip; conditionalDeActivate(); try { Scheduler sched = StdSchedulerFactory .getDefaultScheduler(); JobDetail job = newJob(ReconnectJob.class) .withIdentity("Reconnect", "FritzBox").build(); CronTrigger trigger = newTrigger() .withIdentity("Reconnect", "FritzBox") .withSchedule( CronScheduleBuilder .cronSchedule("0 0 0 * * ?")) .build(); sched.scheduleJob(job, trigger); logger.debug("Scheduled a daily reconnection to FritzBox on " + ip + ":" + MONITOR_PORT); } catch (SchedulerException e) { logger.warn("Could not create daily reconnection job", e); } } } String password = (String) config.get("password"); if (StringUtils.isNotBlank(password)) { FritzboxBinding.password = password; } } }

Target:
public void updated(Dictionary config) throws ConfigurationException { if (config != null) { String ip = (String) config.get("ip"); if (StringUtils.isNotBlank(ip)) { if (!ip.equals(FritzboxBinding.ip)) { FritzboxBinding.ip = ip; conditionalDeActivate(); try { Scheduler sched = StdSchedulerFactory .getDefaultScheduler(); JobDetail job = newJob(ReconnectJob.class) .withIdentity("Reconnect", "FritzBox").build(); CronTrigger trigger = newTrigger() .withIdentity("Reconnect", "FritzBox") .withSchedule( CronScheduleBuilder .cronSchedule("0 0 0 * * ?")) .build(); sched.scheduleJob(job, trigger); logger.debug("Scheduled a daily reconnection to FritzBox on {}:{}", ip, MONITOR_PORT); } catch (SchedulerException e) { logger.warn("Could not create daily reconnection job", e); } } } String password = (String) config.get("password"); if (StringUtils.isNotBlank(password)) { FritzboxBinding.password = password; } } }
Source:
public void init() { broker = LdapFactory.getInstance(getProfileName()); context.put(ExtensionProperties.AUTHOR, "oVirt"); context.put(ExtensionProperties.EXTENSION_NAME, "Provisional Authentication (LbapBroker code based)"); context.put(ExtensionProperties.LICENSE, "ASL 2.0"); context.put(ExtensionProperties.HOME, "<LINK_0>"); context.put(ExtensionProperties.VERSION, "1.0"); }

Target:
public void init() { broker = LdapFactory.getInstance(getProfileName()); context.put(ExtensionProperties.AUTHOR, "The oVirt Project"); context.put(ExtensionProperties.EXTENSION_NAME, "Internal Kerberos/LDAP authentication (Built-in)"); context.put(ExtensionProperties.LICENSE, "ASL 2.0"); context.put(ExtensionProperties.HOME, "<LINK_0>"); context.put(ExtensionProperties.VERSION, "N/A"); }
Source:
public void endWindow() { super.endWindow(); updatedKeyStorage.endWindow(); }

Target:
public void endWindow() { super.endWindow(); if (useUpdatedKeyStorage()) { updatedKeyStorage.endWindow(); } }
Source:
protected boolean canCreateOrUpdateUser(DocumentModel userDoc) { NuxeoPrincipal principal = new NuxeoPrincipalImpl((String) userDoc.getProperty(SCHEMA_NAME, USERNAME_COLUMN)); principal.setModel(userDoc); List<String> adminGroups = userManager.getAdministratorsGroups(); for (String adminGroup : adminGroups) { if (principal.getAllGroups().contains(adminGroup)) { return false; } } return true; }

Target:
protected boolean canCreateOrUpdateUser(DocumentModel userDoc) { NuxeoPrincipal principal = new NuxeoPrincipalImpl((String) userDoc.getProperty(SCHEMA_NAME, USERNAME_COLUMN)); principal.setModel(userDoc); return userManager.getAdministratorsGroups().stream().noneMatch(principal.getAllGroups()::contains); }
Source:
public void testInvalidIV() throws Exception { Assume.assumeTrue(Openssl.getLoadingFailureReason() == null); Openssl cipher = Openssl.getInstance("AES/CTR/NoPadding"); Assert.assertTrue(cipher != null); final byte[] invalidIV = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11}; try { cipher.init(Openssl.ENCRYPT_MODE, key, invalidIV); Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown."); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Wrong IV length.")); throw e; } }

Target:
public void testInvalidIV() throws Exception { Assume.assumeTrue(Openssl.getLoadingFailureReason() == null); Openssl cipher = Openssl.getInstance(CipherTransformation.AES_CTR_NOPADDING.getName()); Assert.assertNotNull(cipher); final byte[] invalidIV = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x11}; try { cipher.init(Openssl.ENCRYPT_MODE, key, invalidIV); Assert.fail("java.security.InvalidAlgorithmParameterException should be thrown."); } catch (Exception e) { Assert.assertTrue(e.getMessage().contains("Wrong IV length.")); throw e; } }
Source:
public void setAssignmentsInfo(AssignmentsInfo info) { ParsedAssignmentsInfo assignmentsInfo = ParsedAssignmentsInfo.of(info); List<InitializedOutputVariable> outputs = assignmentsInfo.createInitializedOutputVariables( getId(), variableScope); if (outputs.isEmpty()) { return; } if (outputs.size() > 1) { throw new IllegalArgumentException("Output Associations should be at most 1 in Catch Events"); } InitializedOutputVariable output = outputs.get(0); DataOutput dataOutput = output.getDataOutput(); event.getDataOutputs().add(dataOutput); event.getOutputSet().getDataOutputRefs().add(dataOutput); this.addItemDefinition(dataOutput.getItemSubjectRef()); DataOutputAssociation dataOutputAssociation = output.getDataOutputAssociation(); if (dataOutputAssociation != null) { event.getDataOutputAssociation().add(dataOutputAssociation); } }

Target:
public void setAssignmentsInfo(AssignmentsInfo info) { ParsedAssignmentsInfo assignmentsInfo = ParsedAssignmentsInfo.of(info); List<InitializedOutputVariable> outputs = assignmentsInfo.createInitializedOutputVariables( getId(), variableScope); if (outputs.isEmpty()) { return; } if (outputs.size() > 1) { throw new IllegalArgumentException("Output Associations should be at most 1 in Catch Events"); } InitializedOutputVariable output = outputs.get(0); DataOutput dataOutput = output.getDataOutput(); event.getDataOutputs().add(dataOutput); getOutputSet().getDataOutputRefs().add(dataOutput); this.addItemDefinition(dataOutput.getItemSubjectRef()); DataOutputAssociation dataOutputAssociation = output.getDataOutputAssociation(); if (dataOutputAssociation != null) { event.getDataOutputAssociation().add(dataOutputAssociation); } }
Source:
public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip, File directory) throws IOException { String[] parts = toolpath.split(":"); String path = parts[0]; String tag = (parts.length > 1) ? parts[1] : "master"; Workflow workflow = getDockstoreWorkflowByPath(path); Optional<WorkflowVersion> first = workflow.getWorkflowVersions().stream().filter(foo -> foo.getName().equalsIgnoreCase(tag)) .findFirst(); if (first.isPresent()) { Long versionId = first.get().getId(); byte[] arbitraryURL = SwaggerUtility .getArbitraryURL("/workflows/" + workflow.getId() + "/zip/" + versionId, new GenericType<byte[]>() { }, workflowsApi.getApiClient()); File zipFile = new File(zipFilename(workflow)); FileUtils.writeByteArrayToFile(zipFile, arbitraryURL, false); if (unzip) { SwaggerUtility.unzipFile(zipFile, directory); } return new File(directory, first.get().getWorkflowPath()); } else { throw new RuntimeException("version not found"); } }

Target:
public File downloadTargetEntry(String toolpath, ToolDescriptor.TypeEnum type, boolean unzip, File directory) throws IOException { String[] parts = toolpath.split(":"); String path = parts[0]; String tag = (parts.length > 1) ? parts[1] : "master"; Workflow workflow = getDockstoreWorkflowByPath(path); Optional<WorkflowVersion> first = workflow.getWorkflowVersions().stream().filter(foo -> foo.getName().equalsIgnoreCase(tag)) .findFirst(); if (!first.isPresent()) { first = workflow.getWorkflowVersions().stream().max(Comparator.comparing(WorkflowVersion::getLastModified)); } if (first.isPresent()) { Long versionId = first.get().getId(); byte[] arbitraryURL = SwaggerUtility .getArbitraryURL("/workflows/" + workflow.getId() + "/zip/" + versionId, new GenericType<byte[]>() { }, workflowsApi.getApiClient()); File zipFile = new File(zipFilename(workflow)); FileUtils.writeByteArrayToFile(zipFile, arbitraryURL, false); if (unzip) { SwaggerUtility.unzipFile(zipFile, directory); } return new File(directory, first.get().getWorkflowPath()); } else { throw new RuntimeException("version not found"); } }
Source:
public void fillInRepo() throws Exception { final File sourceSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/snapshots" ).getAbsoluteFile(); final URL snapshotsRootUrl = new URL( snapshots.getLocalUrl() ); final File snapshotsRoot = new File( snapshotsRootUrl.toURI() ).getAbsoluteFile(); copyDirectory( sourceSnapshotsRoot, snapshotsRoot ); final File sourceReleasesRoot = new File( getBasedir(), "src/test/resources/reposes/releases" ); final URL releaseRootUrl = new URL( releases.getLocalUrl() ); final File releasesRoot = new File( releaseRootUrl.toURI() ); copyDirectory( sourceReleasesRoot, releasesRoot ); final File sourceApacheSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/apache-snapshots" ); final URL apacheSnapshotsRootUrl = new URL( apacheSnapshots.getLocalUrl() ); final File apacheSnapshotsRoot = new File( apacheSnapshotsRootUrl.toURI() ); copyDirectory( sourceApacheSnapshotsRoot, apacheSnapshotsRoot ); ResourceStoreRequest root = new ResourceStoreRequest( RepositoryItemUid.PATH_ROOT ); snapshots.expireCaches( root ); releases.expireCaches( root ); apacheSnapshots.expireCaches( root ); ( (MavenProxyRepository) apacheSnapshots ).setRemoteUrl( "http://localhost:" + super.getContainer().getContext().get( PROXY_SERVER_PORT )+"/apache-snapshots/" ); ( (MavenProxyRepository) apacheSnapshots ).setDownloadRemoteIndexes( false ); nexusConfiguration.saveConfiguration(); waitForTasksToStop(); }

Target:
public void fillInRepo() throws Exception { final File sourceSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/snapshots" ).getAbsoluteFile(); final URL snapshotsRootUrl = new URL( snapshots.getLocalUrl() ); final File snapshotsRoot = new File( snapshotsRootUrl.toURI() ).getAbsoluteFile(); copyDirectory( sourceSnapshotsRoot, snapshotsRoot ); final File sourceReleasesRoot = new File( getBasedir(), "src/test/resources/reposes/releases" ); final URL releaseRootUrl = new URL( releases.getLocalUrl() ); final File releasesRoot = new File( releaseRootUrl.toURI() ); copyDirectory( sourceReleasesRoot, releasesRoot ); final File sourceApacheSnapshotsRoot = new File( getBasedir(), "src/test/resources/reposes/apache-snapshots" ); final URL apacheSnapshotsRootUrl = new URL( apacheSnapshots.getLocalUrl() ); final File apacheSnapshotsRoot = new File( apacheSnapshotsRootUrl.toURI() ); copyDirectory( sourceApacheSnapshotsRoot, apacheSnapshotsRoot ); ResourceStoreRequest root = new ResourceStoreRequest( RepositoryItemUid.PATH_ROOT ); snapshots.expireCaches( root ); releases.expireCaches( root ); apacheSnapshots.expireCaches( root ); ( (MavenProxyRepository) apacheSnapshots ).setRemoteUrl( "http://localhost:" + super.getContainer().getContext().get( PROXY_SERVER_PORT )+"/apache-snapshots/" ); ( (MavenProxyRepository) apacheSnapshots ).setDownloadRemoteIndexes( false ); nexusConfiguration.saveConfiguration(); wairForAsyncEventsToCalmDown(); waitForTasksToStop(); }
Source:
public void sendRequest(final Exchange exchange, final Request request) { Request requestToSend = request; if (isBertEnabled) { Request firstRequest = request; if (isTransparentBlockwiseHandlingEnabled()) { BlockOption block2 = request.getOptions().getBlock2(); if (block2 != null && block2.getNum() > 0) { LOGGER.fine("outbound request contains block2 option, creating random-access blockwise status"); addRandomAccessBlock2Status(exchange, request); handleRandomBlockAccess(exchange, request, block2.getNum()); } else if (requiresBlockwise(request)) { ByteBuffer requestBuilder = ByteBuffer.allocate(bertStepSize * BERT_INT_BLOCK_SIZE); boolean hasNextBlock = true; KeyUri key = getKey(exchange, request); firstRequest = startBlockwiseUpload(exchange, request); requestBuilder.put(firstRequest.getPayload()); Block1BlockwiseStatus status = getBlock1Status(key); for (int i = 1; ((i < bertStepSize) && (hasNextBlock)); i++) { status.setCurrentNum(i); requestToSend = status.getNextRequestBlock(); requestBuilder.put(requestToSend.getPayload()); hasNextBlock = requestToSend.getOptions().getBlock1().isM(); } firstRequest.setPayload(getBody(requestBuilder)); firstRequest.getOptions().setBlock1(BERT_SZX, hasNextBlock, 0); exchange.setCurrentRequest(firstRequest); lower().sendRequest(exchange, firstRequest); } else { exchange.setCurrentRequest(requestToSend); lower().sendRequest(exchange, requestToSend); } } else { exchange.setCurrentRequest(requestToSend); lower().sendRequest(exchange, requestToSend); } } else { super.sendRequest(exchange, requestToSend); } }

Target:
public void sendRequest(final Exchange exchange, final Request request) { Request requestToSend = request; if (isBertEnabled) { if (isTransparentBlockwiseHandlingEnabled()) { BlockOption block2 = request.getOptions().getBlock2(); if (block2 != null && block2.getNum() > 0) { LOGGER.fine("outbound request contains block2 option, creating random-access blockwise status"); addRandomAccessBlock2Status(exchange, request); handleRandomBlockAccess(exchange, request, block2.getNum()); } else if (requiresBlockwise(request)) { ByteBuffer requestBuilder = ByteBuffer.allocate(bertStepSize * BERT_INT_BLOCK_SIZE); boolean hasNextBlock = true; KeyUri key = getKey(exchange, request); Request firstRequest = startBlockwiseUpload(exchange, request); requestBuilder.put(firstRequest.getPayload()); Block1BlockwiseStatus status = getBlock1Status(key); for (int i = 1; ((i < bertStepSize) && (hasNextBlock)); i++) { status.setCurrentNum(i); requestToSend = status.getNextRequestBlock(); requestBuilder.put(requestToSend.getPayload()); hasNextBlock = requestToSend.getOptions().getBlock1().isM(); } firstRequest.setPayload(getBody(requestBuilder)); firstRequest.getOptions().setBlock1(BERT_SZX, hasNextBlock, 0); exchange.setCurrentRequest(firstRequest); lower().sendRequest(exchange, firstRequest); } else { exchange.setCurrentRequest(requestToSend); lower().sendRequest(exchange, requestToSend); } } else { exchange.setCurrentRequest(requestToSend); lower().sendRequest(exchange, requestToSend); } } else { super.sendRequest(exchange, requestToSend); } }
Source:
Location location() default BOTH; enum Location { ACTIVE, PASSIVE, NONE, BOTH }

Target:
Location location() default BOTH; enum Location { ACTIVE, PASSIVE, BOTH, NONE }
Source:
public Transcriber(String roomName, TranscriptionService service) { if (!service.supportsStreamRecognition()) { throw new IllegalArgumentException("Currently only services which" + " support streaming recognition are supported"); } this.transcriptionService = service; addTranscriptionListener(this.transcript); this.roomName = roomName; }

Target:
public Transcriber(String roomName, TranscriptionService service) { if (!service.supportsStreamRecognition()) { throw new IllegalArgumentException( "Currently only services which support streaming " + "recognition are supported"); } this.transcriptionService = service; addTranscriptionListener(this.transcript); this.roomName = roomName; }
Source:
public CabSearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); SearchView.SearchAutoComplete mSearchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); if (ApiUtil.hasHoneyComb()) { mSearchSrcTextView.setCustomSelectionActionModeCallback(new CallbackWrapper()); } initLayoutAttributes(attrs, defStyleAttr); }

Target:
public CabSearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); SearchView.SearchAutoComplete searchSrcTextView = (SearchAutoComplete) findViewById(R.id.search_src_text); if (ApiUtil.hasHoneyComb()) { searchSrcTextView.setCustomSelectionActionModeCallback(new CallbackWrapper()); } initLayoutAttributes(attrs, defStyleAttr); }
Source:
public void setFilters(String filterSequence) { char[][] filters= filterSequence != null && filterSequence.length() > 0 ? splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { fExtraResourceFileFilters= null; fExtraResourceFolderFilters= null; } else { int fileCount= 0, folderCount= 0; for (char[] f : filters) { if (f.length == 0) continue; if (f[f.length - 1] == '/') folderCount++; else fileCount++; } fExtraResourceFileFilters= new char[fileCount][]; fExtraResourceFolderFilters= new String[folderCount]; for (char[] f : filters) { if (f.length == 0) continue; if (f[f.length - 1] == '/') fExtraResourceFolderFilters[--folderCount]= new String(subarray(f, 0, f.length - 1)); else fExtraResourceFileFilters[--fileCount]= f; } } }

Target:
public void setFilters(String filterSequence) { char[][] filters= filterSequence != null && filterSequence.length() > 0 ? splitAndTrimOn(',', filterSequence.toCharArray()) : null; if (filters == null) { fExtraResourceFileFilters= null; fExtraResourceFolderFilters= null; } else { int fileCount= 0, folderCount= 0; for (char[] filter : filters) { if (filter.length == 0) continue; if (filter[filter.length - 1] == '/') folderCount++; else fileCount++; } fExtraResourceFileFilters= new char[fileCount][]; fExtraResourceFolderFilters= new String[folderCount]; for (char[] filter : filters) { if (filter.length == 0) continue; if (filter[filter.length - 1] == '/') fExtraResourceFolderFilters[--folderCount]= new String(subarray(filter, 0, filter.length - 1)); else fExtraResourceFileFilters[--fileCount]= filter; } } }
Source:
NewUserTagNameDialog() { super(new JFrame(NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text")), NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text"), true); initComponents(); String test = ""; this.display(); }

Target:
NewUserTagNameDialog() { super(new JFrame(NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text")), NbBundle.getMessage(NewUserTagNameDialog.class, "NewUserTagNameDialog.title.text"), true); initComponents(); this.display(); }
Source:
@Override public String toString() { StringBuilder builder = new StringBuilder(); if (value instanceof String) { builder.append(name).append(" = \"").append(value).append('"'); } else if (value instanceof Option) { Option optionValue = (Option) value; builder.append('(').append(name).append(").").append(optionValue.toString()); } else if (value instanceof List) { builder.append(name).append(" = [\n"); List<Option> optionList = (List<Option>) value; for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : ""; appendIndented(builder, optionList.get(i).toString() + endl); } builder.append(']'); } else { throw new IllegalStateException("Unknown value type " + value.getClass().getCanonicalName()); } return builder.toString(); }

Target:
@Override public String toString() { StringBuilder builder = new StringBuilder(); if (value instanceof String) { String stringValue = (String) value; builder.append(name).append(" = \"").append(escape(stringValue)).append('"'); } else if (value instanceof Option) { Option optionValue = (Option) value; builder.append('(').append(name).append(").").append(optionValue.toString()); } else if (value instanceof List) { builder.append(name).append(" = [\n"); List<Option> optionList = (List<Option>) value; for (int i = 0, count = optionList.size(); i < count; i++) { String endl = (i < count - 1) ? "," : ""; appendIndented(builder, optionList.get(i).toString() + endl); } builder.append(']'); } else { throw new IllegalStateException("Unknown value type " + value.getClass().getCanonicalName()); } return builder.toString(); }
Source:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for (Entry<FactoryContainer, Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }

Target:
public Map<FactoryContainer, Attributes> getEnabledContainers() { Map<FactoryContainer, Attributes> map = new LinkedHashMap<>(); synchronized(_path) { for (Map.Entry<FactoryContainer, Attributes> entry : getReversed(_path.entrySet())) { Attributes attr = entry.getValue(); if (attr.isEnabled()) { Attributes attrClone = new Attributes(attr); map.put(entry.getKey(), attrClone); } } } return map; }
Source:
public boolean canUseLocalCache() { boolean brokerSwitch; try { brokerSwitch = canSwitchToBroker(); } catch (DeveloperAuthenticationException e){ Logger.w( TAG, e.getMessage(), "", ADALError.DEVELOPER_BROKER_PERMISSIONS_MISSING); brokerSwitch = false; } if (!brokerSwitch) { Logger.v(TAG, "It does not use broker"); return true; } String packageName = mContext.getPackageName(); if (verifySignature(packageName)) { Logger.v(TAG, "Broker installer can use local cache"); return true; } return false; }

Target:
public boolean canUseLocalCache() { boolean brokerSwitch; try { brokerSwitch = canSwitchToBroker(); } catch (final UsageAuthenticationException e) { Logger.w( TAG, e.getMessage(), "", ADALError.DEVELOPER_BROKER_PERMISSIONS_MISSING); brokerSwitch = false; } if (!brokerSwitch) { Logger.v(TAG, "It does not use broker"); return true; } String packageName = mContext.getPackageName(); if (verifySignature(packageName)) { Logger.v(TAG, "Broker installer can use local cache"); return true; } return false; }
Source:
private void connectReceiver(ActiveMQProtonRemotingConnection protonRemotingConnection, Session session, AMQPSessionContext sessionContext, Queue queue, Symbol... capabilities) { if (logger.isDebugEnabled()) { logger.debug("Connecting inbound for " + queue); } { Receiver checkRec = receivers.get(queue); if (checkRec != null) { logger.debug("Receiver for queue " + queue + " already exists, just giving up"); return; } } if (session == null) { logger.debug("session is null"); return; } Receiver receiver = session.receiver(queue.getName().toString() + UUIDGenerator.getInstance().generateStringUUID()); Target target = new Target(); target.setAddress(queue.getAddress().toString()); receiver.setTarget(target); Source source = new Source(); source.setAddress(queue.getName().toString()); receiver.setSource(source); if (capabilities != null) { source.setCapabilities(capabilities); } receivers.put(queue, receiver); protonRemotingConnection.getAmqpConnection().runLater(() -> { receiver.open(); protonRemotingConnection.getAmqpConnection().flush(); try { sessionContext.addReceiver(receiver); } catch (Exception e) { error(e); } }); }

Target:
private void connectReceiver(ActiveMQProtonRemotingConnection protonRemotingConnection, Session session, AMQPSessionContext sessionContext, Queue queue, Symbol... capabilities) { if (logger.isDebugEnabled()) { logger.debug("Connecting inbound for " + queue); } if (session == null) { logger.debug("session is null"); return; } protonRemotingConnection.getAmqpConnection().runLater(() -> { if (receivers.contains(queue)) { logger.debug("Receiver for queue " + queue + " already exists, just giving up"); return; } receivers.add(queue); Receiver receiver = session.receiver(queue.getName().toString() + UUIDGenerator.getInstance().generateStringUUID()); receiver.setSenderSettleMode(SenderSettleMode.UNSETTLED); receiver.setReceiverSettleMode(ReceiverSettleMode.FIRST); Target target = new Target(); target.setAddress(queue.getAddress().toString()); receiver.setTarget(target); Source source = new Source(); source.setAddress(queue.getAddress().toString()); receiver.setSource(source); if (capabilities != null) { source.setCapabilities(capabilities); } receiver.open(); protonRemotingConnection.getAmqpConnection().flush(); try { sessionContext.addReceiver(receiver); } catch (Exception e) { error(e); } }); }
Source:
public ManagedTimestampService createManagedTimestampService( KeyValueService rawKvs, Optional<TableReference> tableReferenceOverride, boolean initializeAsync) { if (initializeAsync) { log.warn("Asynchronous initialization not implemented, will initialize synchronousy."); } Preconditions.checkArgument( rawKvs instanceof ConnectionManagerAwareDbKvs, "DbAtlasDbFactory expects a raw kvs of type ConnectionManagerAwareDbKvs, found %s", rawKvs.getClass()); ConnectionManagerAwareDbKvs dbkvs = (ConnectionManagerAwareDbKvs) rawKvs; return PersistentTimestampServiceImpl.create(createTimestampBoundStore(tableReferenceOverride, dbkvs)); }

Target:
public ManagedTimestampService createManagedTimestampService( KeyValueService rawKvs, Optional<TableReference> tableReferenceOverride, boolean initializeAsync) { if (initializeAsync) { log.warn("Asynchronous initialization not implemented, will initialize synchronously."); } Preconditions.checkArgument( !tableReferenceOverride .map(AtlasDbConstants.DB_TIMELOCK_TIMESTAMP_TABLE::equals) .orElse(false), "Cannot specify the DB TimeLock timestamp table as a timestamp table override!"); Preconditions.checkArgument( rawKvs instanceof ConnectionManagerAwareDbKvs, "DbAtlasDbFactory expects a raw kvs of type ConnectionManagerAwareDbKvs, found %s", rawKvs.getClass()); ConnectionManagerAwareDbKvs dbkvs = (ConnectionManagerAwareDbKvs) rawKvs; return PersistentTimestampServiceImpl.create(createTimestampBoundStore(tableReferenceOverride, dbkvs)); }
Source:
private boolean hasEnoughLag(Interval target, Interval maxInterval) { if ((target.getStartMillis() + minDataLagMs) > maxInterval.getStartMillis()) { return false; } else { return true; } }

Target:
private boolean hasEnoughLag(Interval target, Interval maxInterval) { return minDataLagMs <= (maxInterval.getStartMillis() - target.getStartMillis()); }
Source:
public Mono<AccessToken> authenticateToManagedIdentityEnpoint(String msiEndpoint, String msiSecret, String clientId, String[] scopes) { String resource = ScopeUtil.scopesToResource(scopes); HttpURLConnection connection = null; try { StringBuilder urlStringBuilder = new StringBuilder(String.format("%s?resource=%s&api-version=2017-09-01", msiEndpoint, resource)); if (clientId != null) { urlStringBuilder.append("&"); urlStringBuilder.append("client_id"); urlStringBuilder.append("="); urlStringBuilder.append(clientId); } URL url = new URL(urlStringBuilder.toString()); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Secret", msiSecret); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return adapter.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(e); } finally { if (connection != null) { connection.disconnect(); } } }

Target:
public Mono<AccessToken> authenticateToManagedIdentityEnpoint(String msiEndpoint, String msiSecret, String clientId, String[] scopes) { String resource = ScopeUtil.scopesToResource(scopes); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); try { payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Secret", msiSecret); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; return adapter.deserialize(result, MSIToken.class, SerializerEncoding.JSON); } catch (IOException e) { return Mono.error(e); } finally { if (connection != null) { connection.disconnect(); } } }
Source:
protected Map<String, Pair<String, String>> getSharedLocks() { List<Disk> disksToLock = getVmPluggedDisks(); if (!disksToLock.isEmpty()) { Map<String, Pair<String, String>> sharedLockMap = new HashMap<String, Pair<String, String>>(disksToLock.size()); for (Disk disk : disksToLock) { sharedLockMap.put(disk.getId().toString(), LockMessagesMatchUtil.DISK); } } return null; }

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { List<Disk> disksToLock = getVmPluggedDisks(); if (!disksToLock.isEmpty()) { Map<String, Pair<String, String>> sharedLockMap = new HashMap<String, Pair<String, String>>(disksToLock.size()); for (Disk disk : disksToLock) { sharedLockMap.put(disk.getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.DISK, getDiskSharedLockMessage())); } } return null; }
Source:
public static void main(String[] args) { try { boolean isHeadless = false; Path homePath = null; for (String arg : args) { if (arg.startsWith(HOME_ARG)) { homePath = Paths.get(arg.substring(HOME_ARG.length())); } else if (arg.equals(LOCAL_ARG)) { homePath = Paths.get(""); } else if (arg.equals(HEADLESS_ARG)) { isHeadless = true; } } if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } Collection<EngineSubsystem> subsystemList; if (isHeadless) { subsystemList = Lists.newArrayList(new HeadlessGraphics(), new HeadlessTimer(), new HeadlessAudio(), new HeadlessInput()); } else { subsystemList = Lists.<EngineSubsystem>newArrayList(new LwjglGraphics(), new LwjglTimer(), new LwjglAudio(), new LwjglInput()); } TerasologyEngine engine = new TerasologyEngine(subsystemList); try { engine.init(); if (isHeadless) { engine.run(new StateHeadlessSetup()); } else { engine.run(new StateMainMenu()); } } finally { try { engine.dispose(); } catch (Exception e) { e.printStackTrace(); } } } catch (Throwable t) { if (!GraphicsEnvironment.isHeadless()) { Path logDirectory = Paths.get("."); try { logDirectory = PathManager.getInstance().getLogPath(); } catch (Exception e) { } Path logPath = logDirectory.resolve("Terasology.log"); CrashReporter.report(t, logPath); } } System.exit(0); }

Target:
public static void main(String[] args) { try { boolean isHeadless = false; Path homePath = null; for (String arg : args) { if (arg.startsWith(HOME_ARG)) { homePath = Paths.get(arg.substring(HOME_ARG.length())); } else if (arg.equals(LOCAL_ARG)) { homePath = Paths.get(""); } else if (arg.equals(HEADLESS_ARG)) { isHeadless = true; } } if (homePath != null) { PathManager.getInstance().useOverrideHomePath(homePath); } else { PathManager.getInstance().useDefaultHomePath(); } Collection<EngineSubsystem> subsystemList; if (isHeadless) { subsystemList = Lists.newArrayList(new HeadlessGraphics(), new HeadlessTimer(), new HeadlessAudio(), new HeadlessInput()); } else { subsystemList = Lists.<EngineSubsystem>newArrayList(new LwjglGraphics(), new LwjglTimer(), new LwjglAudio(), new LwjglInput()); } TerasologyEngine engine = new TerasologyEngine(subsystemList); try { engine.init(); if (isHeadless) { engine.run(new StateHeadlessSetup()); } else { engine.run(new StateMainMenu()); } } finally { try { engine.dispose(); } catch (Exception e) { e.printStackTrace(); } } } catch (RuntimeException | IOException e) { if (!GraphicsEnvironment.isHeadless()) { Path logPath = Paths.get("."); try { Path gameLogPath = PathManager.getInstance().getLogPath(); if (gameLogPath != null) { logPath = gameLogPath; } } catch (Exception eat) { } Path logFile = logPath.resolve("Terasology.log"); CrashReporter.report(e, logFile); } } System.exit(0); }
Source:
public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { final Map<String, Object> m = new HashMap<>(); m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals(); final List<Map<String, Object>> intermediates = new ArrayList<>(); for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) { final Map<String, Object> intermediate = new HashMap<>(); intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString()); intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName()); intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); intermediates.add(intermediate); } m.put(GraphSONTokens.INTERMEDIATE, intermediates); if (strategyTraversals.isEmpty()) m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); else m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1())); jsonGenerator.writeObject(m); }

Target:
public void serialize(final TraversalExplanation traversalExplanation, final JsonGenerator jsonGenerator, final SerializerProvider serializerProvider) throws IOException { final Map<String, Object> m = new HashMap<>(); m.put(GraphSONTokens.ORIGINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); final List<Pair<TraversalStrategy, Traversal.Admin<?, ?>>> strategyTraversals = traversalExplanation.getStrategyTraversals(); final List<Map<String, Object>> intermediates = new ArrayList<>(); for (final Pair<TraversalStrategy, Traversal.Admin<?, ?>> pair : strategyTraversals) { final Map<String, Object> intermediate = new HashMap<>(); intermediate.put(GraphSONTokens.STRATEGY, pair.getValue0().toString()); intermediate.put(GraphSONTokens.CATEGORY, pair.getValue0().getTraversalCategory().getSimpleName()); intermediate.put(GraphSONTokens.TRAVERSAL, getStepsAsList(pair.getValue1())); intermediates.add(intermediate); } m.put(GraphSONTokens.INTERMEDIATE, intermediates); if (strategyTraversals.isEmpty()) m.put(GraphSONTokens.FINAL, getStepsAsList(traversalExplanation.getOriginalTraversal())); else m.put(GraphSONTokens.FINAL, getStepsAsList(strategyTraversals.get(strategyTraversals.size() - 1).getValue1())); jsonGenerator.writeObject(m); }
Source:
private void addMetricsCacheClientTasksOnWakeUp() { Runnable task = new Runnable() { @Override public void run() { TopologyMaster.PublishMetrics publishMetrics; synchronized (publishMetricsCommunicator) { publishMetrics = publishMetricsCommunicator.poll(); } while (publishMetrics != null) { LOG.info(String.format("%d Metrics, %d Exceptions to send to MetricsCache", publishMetrics.getMetricsCount(), publishMetrics.getExceptionsCount())); LOG.fine("Publish Metrics sending to MetricsCache: " + publishMetrics.toString()); sendMessage(publishMetrics); synchronized (publishMetricsCommunicator) { publishMetrics = publishMetricsCommunicator.poll(); } } } }; getNIOLooper().addTasksOnWakeup(task); }

Target:
private void addMetricsCacheClientTasksOnWakeUp() { Runnable task = new Runnable() { @Override public void run() { TopologyMaster.PublishMetrics publishMetrics; while (true) { synchronized (publishMetricsCommunicator) { publishMetrics = publishMetricsCommunicator.poll(); } if (publishMetrics == null) { break; } LOG.info(String.format("%d Metrics, %d Exceptions to send to MetricsCache", publishMetrics.getMetricsCount(), publishMetrics.getExceptionsCount())); LOG.fine("Publish Metrics sending to MetricsCache: " + publishMetrics.toString()); sendMessage(publishMetrics); } } }; getNIOLooper().addTasksOnWakeup(task); }
Source:
public void fillZeroRecords(final ContextAccumulator fullContextAccumulator, final int contextSize) { final String padding = StringUtil.repeatCharNTimes('N', contextSize); for (Map.Entry<String,AlignmentAccumulator[]> fullContext : fullContextAccumulator.artifactMap.entrySet()) { final String context = fullContext.getKey(); final char centralBase = context.charAt(contextSize); final String key = padding + centralBase + padding; final AlignmentAccumulator[] zeroAlignmentAccumulators = this.artifactMap.get(key); final AlignmentAccumulator[] fullAlignmentAccumulators = fullContext.getValue(); for (int i=0; i < fullAlignmentAccumulators.length; i++) { zeroAlignmentAccumulators[i].mergeCounts(fullContext.getValue()[i]); } } }

Target:
public void fillZeroRecords(final ContextAccumulator fullContextAccumulator, final int contextSize) { final String padding = StringUtil.repeatCharNTimes('N', contextSize); for (Map.Entry<String,AlignmentAccumulator[]> fullContext : fullContextAccumulator.artifactMap.entrySet()) { final String fullContextKey = fullContext.getKey(); final char centralBase = fullContextKey.charAt(contextSize); final String zeroContextKey = padding + centralBase + padding; final AlignmentAccumulator[] zeroAlignmentAccumulators = this.artifactMap.get(zeroContextKey); final AlignmentAccumulator[] fullAlignmentAccumulators = fullContext.getValue(); for (int i=0; i < fullAlignmentAccumulators.length; i++) { zeroAlignmentAccumulators[i].merge(fullAlignmentAccumulators[i]); } } }
Source:
public void beforeTest() { reset(tx); elide = mock(Elide.class); user = mock(User.class); asyncQuery = mock(AsyncQuery.class); graphQLParser = mock(GraphQLParser.class); TransactionRegistry transactionRegistry = mock(TransactionRegistry.class); DataStore dataStore = mock(DataStore.class); AuditLogger auditLogger = mock(AuditLogger.class); ElideSettings settings = mock(ElideSettings.class); EntityDictionary dictionary = mock(EntityDictionary.class); EntityProjection projection = EntityProjection.builder().type(AsyncQuery.class).build(); when(asyncQuery.getRequestId()).thenReturn(UUID.randomUUID().toString()); when(asyncQuery.getQueryType()).thenReturn(QueryType.GRAPHQL_V1_0); when(elide.getTransactionRegistry()).thenReturn(transactionRegistry); when(elide.getAuditLogger()).thenReturn(auditLogger); when(elide.getDataStore()).thenReturn(dataStore); when(elide.getElideSettings()).thenReturn(settings); when(settings.getDictionary()).thenReturn(dictionary); when(dataStore.beginTransaction()).thenReturn(tx); when(graphQLParser.parse(any())).thenReturn(projection); }

Target:
public void beforeTest() { dataStore = new HashMapDataStore(AsyncQuery.class.getPackage()); Map<String, Class<? extends Check>> map = new HashMap<>(); map.put(AsyncQueryInlineChecks.AsyncQueryOwner.PRINCIPAL_IS_OWNER, AsyncQueryInlineChecks.AsyncQueryOwner.class); map.put(AsyncQueryInlineChecks.AsyncQueryAdmin.PRINCIPAL_IS_ADMIN, AsyncQueryInlineChecks.AsyncQueryAdmin.class); map.put(AsyncQueryInlineChecks.AsyncQueryStatusValue.VALUE_IS_CANCELLED, AsyncQueryInlineChecks.AsyncQueryStatusValue.class); map.put(AsyncQueryInlineChecks.AsyncQueryStatusQueuedValue.VALUE_IS_QUEUED, AsyncQueryInlineChecks.AsyncQueryStatusQueuedValue.class); elide = new Elide( new ElideSettingsBuilder(dataStore) .withEntityDictionary(new EntityDictionary(map)) .withAuditLogger(new Slf4jLogger()) .build()); user = mock(User.class); }
Source:
public void importProject(final CompleteCallback callback, MutableProjectConfig projectConfig) { final Path path = !isNullOrEmpty(projectConfig.getPath()) ? Path.valueOf(projectConfig.getPath()) : !isNullOrEmpty(projectConfig.getName()) ? Path.valueOf(projectConfig.getName()).makeAbsolute() : null; checkState(path != null, "Import path is undefined"); startImport(path, projectConfig.getSource()) .then( arg -> { if (callback != null) { callback.onCompleted(); } }) .catchError( arg -> { if (callback != null) { callback.onFailure(arg.getCause()); } }); }

Target:
public void importProject(final CompleteCallback callback, MutableProjectConfig projectConfig) { final Path path = !isNullOrEmpty(projectConfig.getPath()) ? Path.valueOf(projectConfig.getPath()) : !isNullOrEmpty(projectConfig.getName()) ? Path.valueOf(projectConfig.getName()).makeAbsolute() : null; checkState(path != null, "Import path is undefined"); startImport(path, projectConfig.getSource()) .then( project -> { if (callback != null) { callback.onCompleted(); } }) .catchError( error -> { if (callback != null) { callback.onFailure(error.getCause()); } }); }
Source:
public static String createWebsequenceUrl(String style, String content) { style = StringUtils.defaultString(style, "default"); OutputStreamWriter writer = null; BufferedReader reader = null; try { String query = new StringBuilder() .append("style=") .append(style) .append("&message=") .append(URLEncoder.encode(content, "UTF-8")) .append("&apiVersion=1") .toString(); URL url = new URL("<LINK_1>"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(query); writer.flush(); StringBuilder response = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { response.append(line); } writer.close(); reader.close(); String json = response.toString(); int start = json.indexOf("?png="); int end = json.indexOf("\"", start); if (start != -1 && end != -1) { return "<LINK_0>" + json.substring(start, end); } } catch (IOException e) { throw new RuntimeException("Failed to get proper response from websequencediagrams.com"); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); } return ""; }

Target:
public static String createWebsequenceUrl(String style, String content) { style = StringUtils.defaultString(style, "default"); OutputStreamWriter writer = null; BufferedReader reader = null; String webSeqUrl = ""; try { String query = new StringBuilder() .append("style=") .append(style) .append("&message=") .append(URLEncoder.encode(content, "UTF-8")) .append("&apiVersion=1") .toString(); URL url = new URL(WEBSEQ_URL); URLConnection conn = url.openConnection(); conn.setDoOutput(true); writer = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8); writer.write(query); writer.flush(); StringBuilder response = new StringBuilder(); reader = new BufferedReader( new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)); String line; while ((line = reader.readLine()) != null) { response.append(line); } writer.close(); reader.close(); String json = response.toString(); int start = json.indexOf("?png="); int end = json.indexOf("\"", start); if (start != -1 && end != -1) { webSeqUrl = WEBSEQ_URL + "/" + json.substring(start, end); } } catch (IOException e) { throw new RuntimeException("Failed to get proper response from websequencediagrams.com", e); } finally { IOUtils.closeQuietly(writer); IOUtils.closeQuietly(reader); } return webSeqUrl; }
Source:
public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String site = getUrl(updatesite); String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator("downloadable '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }

Target:
public FormValidation updateNow() throws IOException { List<JSONObject> jsonList = new ArrayList<>(); boolean toolInstallerMetadataExists = false; for (UpdateSite updatesite : Jenkins.getActiveInstance().getUpdateCenter().getSiteList()) { String site = updatesite.getMetadataUrlForDownloadable(url); if (site == null) { return FormValidation.warning("The update site " + site + " does not look like an update center"); } String jsonString; try { jsonString = loadJSONHTML(new URL(site + ".html?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))); toolInstallerMetadataExists = true; } catch (Exception e) { LOGGER.log(Level.FINE, "Could not load json from " + site, e ); continue; } JSONObject o = JSONObject.fromObject(jsonString); if (signatureCheck) { FormValidation e = updatesite.getJsonSignatureValidator(signatureValidatorPrefix +" '"+id+"'").verifySignature(o); if (e.kind!= Kind.OK) { LOGGER.log(Level.WARNING, "signature check failed for " + site, e ); continue; } } jsonList.add(o); } if (jsonList.size() == 0 && toolInstallerMetadataExists) { return FormValidation.warning("None of the tool installer metadata passed the signature check"); } else if (!toolInstallerMetadataExists) { LOGGER.log(Level.WARNING, "No tool installer metadata found for " + id); return FormValidation.ok(); } JSONObject reducedJson = reduce(jsonList); return load(reducedJson.toString(), System.currentTimeMillis()); }