auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected int ensureCumulatives(int high) { if (allValid) { return highToBitmap.size(); } else if (compare(high, firstHighNotValid) < 0) { int position = binarySearch(sortedHighs, high); if (position >= 0) { return position + 1; } else { int insertionPosition = -position - 1; return insertionPosition; } } else { SortedMap<Integer, BitmapDataProvider> tailMap = highToBitmap.tailMap(firstHighNotValid, true); int indexOk = highToBitmap.size() - tailMap.size(); Iterator<Entry<Integer, BitmapDataProvider>> it = tailMap.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, BitmapDataProvider> e = it.next(); int currentHigh = e.getKey(); if (compare(currentHigh, high) > 0) { break; } else if (e.getValue().isEmpty()) { if (latestAddedHigh != null && latestAddedHigh.getKey().intValue() == currentHigh) { latestAddedHigh = null; } it.remove(); } else { ensureOne(e, currentHigh, indexOk); indexOk++; } } if (highToBitmap.isEmpty() || indexOk == highToBitmap.values().size()) { allValid = true; } return indexOk; } }

Target:
protected int ensureCumulatives(int high) { if (allValid) { return highToBitmap.size(); } else if (compare(high, firstHighNotValid) < 0) { int position = binarySearch(sortedHighs, high); if (position >= 0) { return position + 1; } else { int insertionPosition = -position - 1; return insertionPosition; } } else { SortedMap<Integer, BitmapDataProvider> tailMap = highToBitmap.tailMap(firstHighNotValid, true); int indexOk = highToBitmap.size() - tailMap.size(); Iterator<Entry<Integer, BitmapDataProvider>> it = tailMap.entrySet().iterator(); while (it.hasNext()) { Entry<Integer, BitmapDataProvider> e = it.next(); int currentHigh = e.getKey(); if (compare(currentHigh, high) > 0) { break; } else if (e.getValue().isEmpty()) { if (latestAddedHigh != null && latestAddedHigh.getKey().intValue() == currentHigh) { latestAddedHigh = null; } it.remove(); } else { ensureOne(e, currentHigh, indexOk); indexOk++; } } if (highToBitmap.isEmpty() || indexOk == highToBitmap.size()) { allValid = true; } return indexOk; } }
Source:
public void setAndGetAttachmentsTest() throws Exception { String attachmentName = "attachment_1.txt"; MutableDocumentRevision rev_1Mut = new MutableDocumentRevision(); rev_1Mut.body = bodyOne; BasicDocumentRevision rev_1 = datastore.createDocumentFromRevision(rev_1Mut); File f = TestUtils.loadFixture("fixture/" + attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); BasicDocumentRevision newRevision = null; try { MutableDocumentRevision rev1_mut = rev_1.mutableCopy(); rev1_mut.attachments.put(attachmentName, att); newRevision = datastore.updateDocumentFromRevision(rev1_mut); } catch (ConflictException ce) { Assert.fail("ConflictException thrown: " + ce); } FileInputStream fis = null; try { byte[] expectedSha1 = Misc.getSha1((fis = new FileInputStream(f))); SavedAttachment savedAtt = (SavedAttachment) datastore.getAttachment(newRevision, attachmentName); Assert.assertArrayEquals(expectedSha1, savedAtt.key); SavedAttachment savedAtt2 = (SavedAttachment) datastore.attachmentsForRevision (newRevision).get(0); Assert.assertArrayEquals(expectedSha1, savedAtt2.key); } catch (FileNotFoundException fnfe) { Assert.fail("FileNotFoundException thrown " + fnfe); } finally { if (fis != null) { fis.close(); } } }

Target:
public void setAndGetAttachmentsTest() throws Exception { String attachmentName = "attachment_1.txt"; MutableDocumentRevision rev_1Mut = new MutableDocumentRevision(); rev_1Mut.body = bodyOne; BasicDocumentRevision rev_1 = datastore.createDocumentFromRevision(rev_1Mut); File f = TestUtils.loadFixture("fixture/"+attachmentName); Attachment att = new UnsavedFileAttachment(f, "text/plain"); BasicDocumentRevision newRevision = null; try { MutableDocumentRevision rev1_mut = rev_1.mutableCopy(); rev1_mut.attachments.put(attachmentName, att); newRevision = datastore.updateDocumentFromRevision(rev1_mut); } catch (ConflictException ce){ Assert.fail("ConflictException thrown: "+ce); } FileInputStream fis = null; try { byte[] expectedSha1 = Misc.getSha1((fis = new FileInputStream(f))); SavedAttachment savedAtt = (SavedAttachment) datastore.getAttachment(newRevision, attachmentName); Assert.assertArrayEquals(expectedSha1, savedAtt.key); SavedAttachment savedAtt2 = (SavedAttachment) datastore.attachmentsForRevision (newRevision).get(0); Assert.assertArrayEquals(expectedSha1, savedAtt2.key); } catch (FileNotFoundException fnfe) { Assert.fail("FileNotFoundException thrown " + fnfe); } finally { IOUtils.closeQuietly(fis); } }
Source:
public ClientCacheSqlFieldsQueryRequest(BinaryRawReaderEx reader) { super(reader); String schema = reader.readString(); int pageSize = reader.readInt(); reader.readInt(); String sql = reader.readString(); Object[] args = PlatformCache.readQueryArgs(reader); JdbcStatementType stmtType = JdbcStatementType.fromOrdinal(reader.readByte()); boolean distributedJoins = reader.readBoolean(); boolean loc = reader.readBoolean(); boolean replicatedOnly = reader.readBoolean(); boolean enforceJoinOrder = reader.readBoolean(); boolean collocated = reader.readBoolean(); boolean lazy = reader.readBoolean(); int timeout = (int) reader.readLong(); includeFieldNames = reader.readBoolean(); SqlFieldsQuery qry = stmtType == JdbcStatementType.ANY_STATEMENT_TYPE ? new SqlFieldsQuery(sql) : new SqlFieldsQueryEx(sql,stmtType == JdbcStatementType.SELECT_STATEMENT_TYPE); qry.setSchema(schema) .setPageSize(pageSize) .setArgs(args) .setDistributedJoins(distributedJoins) .setLocal(loc) .setReplicatedOnly(replicatedOnly) .setEnforceJoinOrder(enforceJoinOrder) .setCollocated(collocated) .setLazy(lazy); if (timeout >= 0) { qry.setTimeout(timeout, TimeUnit.MILLISECONDS); } this.qry = qry; }

Target:
public ClientCacheSqlFieldsQueryRequest(BinaryRawReaderEx reader) { super(reader); String schema = reader.readString(); int pageSize = reader.readInt(); reader.readInt(); String sql = reader.readString(); Object[] args = PlatformCache.readQueryArgs(reader); JdbcStatementType stmtType = JdbcStatementType.fromOrdinal(reader.readByte()); boolean distributedJoins = reader.readBoolean(); boolean loc = reader.readBoolean(); boolean replicatedOnly = reader.readBoolean(); boolean enforceJoinOrder = reader.readBoolean(); boolean collocated = reader.readBoolean(); boolean lazy = reader.readBoolean(); int timeout = (int) reader.readLong(); includeFieldNames = reader.readBoolean(); SqlFieldsQuery qry = stmtType == JdbcStatementType.ANY_STATEMENT_TYPE ? new SqlFieldsQuery(sql) : new SqlFieldsQueryEx(sql,stmtType == JdbcStatementType.SELECT_STATEMENT_TYPE); qry.setSchema(schema) .setPageSize(pageSize) .setArgs(args) .setDistributedJoins(distributedJoins) .setLocal(loc) .setReplicatedOnly(replicatedOnly) .setEnforceJoinOrder(enforceJoinOrder) .setCollocated(collocated) .setLazy(lazy); if (timeout >= 0) qry.setTimeout(timeout, TimeUnit.MILLISECONDS); this.qry = qry; }
Source:
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); LOGGER.warn("Unexpected error handling request.", cause); String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } }

Target:
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) { ZipkinHttpCollector.metrics.incrementMessagesDropped(); String message = cause.getMessage() != null ? cause.getMessage() : ""; if (cause instanceof IllegalArgumentException) { return HttpResponse.of(BAD_REQUEST, MediaType.ANY_TEXT_TYPE, message); } else { LOGGER.warn("Unexpected error handling request.", cause); return HttpResponse.of(INTERNAL_SERVER_ERROR, MediaType.ANY_TEXT_TYPE, message); } }
Source:
public void shouldRejectNotValidAuthorizationString() throws Exception { SecurityDomain securityDomainMock = mock(SecurityDomain.class); BasicAuthenticator basicAuthenticator = new BasicAuthenticator(securityDomainMock, "ApplicationRealm"); restServer = RestServerHelper.defaultRestServer().withAuthenticator(basicAuthenticator).start(this.getTestName()); ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%s", restServer.getPort(), "default", "test")) .method(HttpMethod.GET) .header(HttpHeader.AUTHORIZATION, "Invalid string") .send(); ResponseAssertion.assertThat(response).isUnauthorized(); }

Target:
public void shouldRejectNotValidAuthorizationString() throws Exception { SecurityDomain securityDomainMock = mock(SecurityDomain.class); BasicAuthenticator basicAuthenticator = new BasicAuthenticator(securityDomainMock, "ApplicationRealm"); restServer = RestServerHelper.defaultRestServer().withAuthenticator(basicAuthenticator).start(TestResourceTracker.getCurrentTestShortName()); ContentResponse response = client .newRequest(String.format("http://localhost:%d/rest/%s/%s", restServer.getPort(), "default", "test")) .method(HttpMethod.GET) .header(HttpHeader.AUTHORIZATION, "Invalid string") .send(); ResponseAssertion.assertThat(response).isUnauthorized(); }
Source:
public void processLti(HttpServletRequest request, HttpServletResponse response) throws IOException { for (Object e : request.getParameterMap().entrySet()) { Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e; String name = entry.getKey(); for (String value : entry.getValue()) { M_log.debug(name + " = " + value); } } if(appExtSecurePropertiesFile!=null) { ltiKey = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_KEY); ltiSecret = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_SECRET); ltiUrl = request.getRequestURL().toString(); M_log.debug("ltiKey: " + ltiKey); M_log.debug("ltiSecret: " + ltiSecret); M_log.debug("ltiUrl: " + ltiUrl); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); return; } if(RequestSignatureUtils.verifySignature(request, ltiKey, ltiSecret, ltiUrl)){ doRequest(request, response); return; } doError(request, response, "Missing required parameter: Launch type or version is incorrect."); return; }

Target:
public void processLti(HttpServletRequest request, HttpServletResponse response) throws IOException { for (Object e : request.getParameterMap().entrySet()) { Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e; String name = entry.getKey(); for (String value : entry.getValue()) { M_log.debug(name + " = " + value); } } if(appExtSecurePropertiesFile!=null) { ltiKey = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_KEY); ltiSecret = appExtSecurePropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_SECRET); if(appExtPropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_URL) != null){ ltiUrl = appExtPropertiesFile.getProperty(SectionUtilityToolFilter.PROPERTY_LTI_URL); } else{ ltiUrl = request.getRequestURL().toString(); } M_log.debug("ltiKey: " + ltiKey); M_log.debug("ltiSecret: " + ltiSecret); M_log.debug("ltiUrl: " + ltiUrl); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); M_log.error("Failed to load system properties(sectionsToolProps.properties) for SectionsTool"); return; } if(RequestSignatureUtils.verifySignature(request, ltiKey, ltiSecret, ltiUrl)){ doRequest(request, response); return; } doError(request, response, "Missing required parameter: Launch type or version is incorrect."); return; }
Source:
protected String[] customCommandLineValidation() { final List<String> errorMsgs = new ArrayList<>(); if (SCATTER_COUNT < 1) { errorMsgs.add("SCATTER_COUNT must be greater than 0."); } if (BREAK_BANDS_AT_MULTIPLES_OF < 0) { errorMsgs.add("BREAK_BANDS_AT_MULTIPLES_OF must be greater than or equal to 0."); } if ((SECOND_INPUT == null || SECOND_INPUT.isEmpty()) && ACTION.takesSecondInput) { errorMsgs.add("SECOND_INPUT was not provided but action " + ACTION + " requires a second input."); } if ((SECOND_INPUT != null && !SECOND_INPUT.isEmpty()) && !ACTION.takesSecondInput) { errorMsgs.add("SECOND_INPUT was provided but action " + ACTION + " doesn't take a second input."); } if(COUNT_OUTPUT != null && OUTPUT_VALUE == Output.NONE) { errorMsgs.add("COUNT_OUTPUT was provided but OUTPUT_VALUE is set to NONE."); } if(COUNT_OUTPUT == null && OUTPUT_VALUE != Output.NONE) { errorMsgs.add("OUTPUT_VALUE is set to "+OUTPUT_VALUE+" but COUNT_OUTPUT was not provided."); } return errorMsgs.isEmpty() ? null : errorMsgs.toArray(new String[errorMsgs.size()]); }

Target:
protected String[] customCommandLineValidation() { final List<String> errorMsgs = new ArrayList<>(); if (SCATTER_COUNT < 1) { errorMsgs.add("SCATTER_COUNT must be greater than 0."); } if (BREAK_BANDS_AT_MULTIPLES_OF < 0) { errorMsgs.add("BREAK_BANDS_AT_MULTIPLES_OF must be greater than or equal to 0."); } if ((SECOND_INPUT == null || SECOND_INPUT.isEmpty()) && ACTION.takesSecondInput) { errorMsgs.add("SECOND_INPUT was not provided but action " + ACTION + " requires a second input."); } if ((SECOND_INPUT != null && !SECOND_INPUT.isEmpty()) && !ACTION.takesSecondInput) { errorMsgs.add("SECOND_INPUT was provided but action " + ACTION + " doesn't take a second input."); } if (COUNT_OUTPUT != null && OUTPUT_VALUE == Output.NONE) { errorMsgs.add("COUNT_OUTPUT was provided but OUTPUT_VALUE is set to NONE."); } return errorMsgs.isEmpty() ? null : errorMsgs.toArray(new String[errorMsgs.size()]); }
Source:
public List<String> listObjectNames( String bucketName, String objectNamePrefix, String delimiter, long maxResults) throws IOException { logger.atFine().log( "listObjectNames(%s, %s, %s, %s)", bucketName, objectNamePrefix, delimiter, maxResults); PageState pageState = new PageState(false); listStorageObjectsAndPrefixes( bucketName, objectNamePrefix, delimiter, false, maxResults, pageState); List<String> objectNames = new ArrayList<>(pageState.getPrefixes().size()); objectNames.addAll(pageState.getPrefixes()); ; for (StorageObject obj : pageState.getListedObjects()) { objectNames.add(obj.getName()); } return objectNames; }

Target:
public List<String> listObjectNames( String bucketName, String objectNamePrefix, String delimiter, long maxResults) throws IOException { logger.atFine().log( "listObjectNames(%s, %s, %s, %s)", bucketName, objectNamePrefix, delimiter, maxResults); List<StorageObject> listedObjects = new ArrayList<>(); List<String> listedPrefixes = new ArrayList<>(); listStorageObjectsAndPrefixes( bucketName, objectNamePrefix, delimiter, false, maxResults, listedObjects, listedPrefixes); List<String> objectNames = listedPrefixes; for (StorageObject obj : listedObjects) { objectNames.add(obj.getName()); } return objectNames; }
Source:
public void start(AbstractProject project, boolean newInstance) { logger.debug("Start project: {}", project); super.start(project, newInstance); initializeTriggerOnEvents(); this.myProject = project; try { if (PluginImpl.getInstance() != null) { PluginImpl.getInstance().addListener(this); } else { logger.warn("The plugin instance could not be found! Project will not be triggered!", project.getFullDisplayName()); } } catch (IllegalStateException e) { logger.error("I am too early!", e); } if (dynamicTriggerConfiguration) { gerritTriggerTimerTask = new GerritTriggerTimerTask(this); } if (allowTriggerMissedPatches) { for (GerritProject p : gerritProjects) { GerritProjectList.addProject(p); } } }

Target:
public void start(AbstractProject project, boolean newInstance) { logger.debug("Start project: {}", project); super.start(project, newInstance); initializeTriggerOnEvents(); this.myProject = project; try { if (PluginImpl.getInstance() != null) { PluginImpl.getInstance().addListener(this); } else { logger.warn("The plugin instance could not be found! Project will not be triggered!", project.getFullDisplayName()); } } catch (IllegalStateException e) { logger.error("I am too early!", e); } if (dynamicTriggerConfiguration) { gerritTriggerTimerTask = new GerritTriggerTimerTask(this); } GerritProjectList.removeTriggerFromProjectList(this); if (allowTriggeringUnreviewedPatches) { for (GerritProject p : gerritProjects) { GerritProjectList.addProject(p, this); } } }
Source:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e2) { ; } try { ret = (String) value; } catch (ClassCastException e) { ; } return ret; }

Target:
public String getStringValue() { String ret = null; try { ret = (String) defaultValue; } catch (ClassCastException e) { ; } try { ret = (String) value; } catch (ClassCastException e) { ; } return ret; }
Source:
public Evidence createEvidence(final CallbackProperties properties, final Subject subject) { LOG.debug("SamlCallbackHandler.createEvidence() -- Begin"); final String evAssertionID = properties.getEvidenceID(); final List<AttributeStatement> statements = createEvidenceStatements(properties); return wrapperEvidence(new WrapperEvidenceParameter(evAssertionID, properties, statements, subject)); }

Target:
public Evidence createEvidence(final CallbackProperties properties, final Subject subject) { LOG.debug("SamlCallbackHandler.createEvidence() -- Begin"); final List<AttributeStatement> statements = createEvidenceStatements(properties); return buildEvidence(properties, statements, subject); }
Source:
private void buildOpenExistingRepresentationsMenu(final IMenuManager menu, final DSemanticDiagram designerDiag, final EditPart editpart, final EObject designerObj) { final EObject semantic = ((DSemanticDecorator) designerObj).getTarget(); if (semantic != null) { final Session session = SessionManager.INSTANCE.getSession(semantic); if (session != null) { final IMenuManager navigateManager = (IMenuManager) menu.find("navigateMenu"); navigateManager.remove("open"); final MenuManager openMenuManager = new MenuManager("Open", MENU_OPEN_REPRESENTATION_ID); if (menu.getItems() != null) { menu.insertBefore(menu.getItems()[FIRST_ITEM_INDEX].getId(), openMenuManager); } else { menu.add(openMenuManager); } contributeToPopupMenu(openMenuManager, null); final TransactionalEditingDomain transDomain = TransactionUtil.getEditingDomain(designerDiag); final Collection<DRepresentation> otherRepresentations = DialectManager.INSTANCE.getRepresentations(semantic, session); for (final DRepresentation representation : otherRepresentations) { if (!EcoreUtil.equals(designerDiag, representation) && isFromActiveViewpoint(session, representation)) { openMenuManager.add(buildOpenRepresentationAction(session, representation, editpart, transDomain)); } } if (designerObj instanceof DRepresentationElement) { buildOpenableRepresentationsMenu(openMenuManager, designerObj, session, editpart, transDomain); } } } }

Target:
private void buildOpenExistingRepresentationsMenu(final IMenuManager menu, final DSemanticDiagram designerDiag, final EditPart editpart, final EObject designerObj) { final EObject semantic = ((DSemanticDecorator) designerObj).getTarget(); if (semantic != null) { final Session session = SessionManager.INSTANCE.getSession(semantic); if (session != null) { final IMenuManager navigateManager = (IMenuManager) menu.find("navigateMenu"); navigateManager.remove("open"); final MenuManager openMenuManager = new MenuManager("Open", MENU_OPEN_REPRESENTATION_ID); if (!menu.isEmpty()) { menu.insertBefore(menu.getItems()[0].getId(), openMenuManager); } else { menu.add(openMenuManager); } contributeToPopupMenu(openMenuManager, null); final TransactionalEditingDomain transDomain = TransactionUtil.getEditingDomain(designerDiag); final Collection<DRepresentation> otherRepresentations = DialectManager.INSTANCE.getRepresentations(semantic, session); for (final DRepresentation representation : otherRepresentations) { if (!EcoreUtil.equals(designerDiag, representation) && isFromActiveViewpoint(session, representation)) { openMenuManager.add(buildOpenRepresentationAction(session, representation, editpart, transDomain)); } } if (designerObj instanceof DRepresentationElement) { buildOpenableRepresentationsMenu(openMenuManager, designerObj, session, editpart, transDomain); } } } }
Source:
public Application call(Application originalApplication, Application updatedApplication) { boolean isChaosMonkeyEnabled = isChaosMonkeyEnabled(updatedApplication); if (isChaosMonkeyEnabled(originalApplication) == isChaosMonkeyEnabled) { return updatedApplication; } Object rawPermissions = updatedApplication.details().get("permissions"); if (!(rawPermissions instanceof Map)) { log.warn("No permissions config found on application '{}'", updatedApplication.getName()); return updatedApplication; } @SuppressWarnings("unchecked") Map<String, List<String>> permissionsMap = (Map<String, List<String>>) rawPermissions; if (isChaosMonkeyEnabled) { List<String> readPermissions = permissionsMap.get("READ"); if (!readPermissions.contains(properties.getUserRole())) { log.info("Chaos Monkey READ permissions applied for '{}'", updatedApplication.getName()); readPermissions.add(properties.getUserRole()); } List<String> writePermissions = permissionsMap.get("WRITE"); if (!writePermissions.contains(properties.getUserRole())) { log.info("Chaos Monkey WRITE permissions applied for '{}'", updatedApplication.getName()); writePermissions.add(properties.getUserRole()); } } else { log.info( "Revoking Chaos Monkey READ and WRITE permissions for '{}'", updatedApplication.getName()); permissionsMap.get("READ").remove(properties.getUserRole()); permissionsMap.get("WRITE").remove(properties.getUserRole()); } return updatedApplication; }

Target:
public Application call(Application originalApplication, Application updatedApplication) { boolean isChaosMonkeyEnabled = isChaosMonkeyEnabled(updatedApplication); if (isChaosMonkeyEnabled(originalApplication) == isChaosMonkeyEnabled) { return updatedApplication; } Object rawPermissions = updatedApplication.details().get("permissions"); if (!(rawPermissions instanceof Map)) { log.warn("No permissions config found on application '{}'", updatedApplication.getName()); return updatedApplication; } @SuppressWarnings("unchecked") Map<String, List<String>> permissionsMap = (Map<String, List<String>>) rawPermissions; if (permissionsMap.isEmpty()) { return updatedApplication; } if (isChaosMonkeyEnabled) { List<String> readPermissions = permissionsMap.computeIfAbsent("READ", k -> new ArrayList<>()); if (!readPermissions.contains(properties.getUserRole())) { log.info("Chaos Monkey READ permissions applied for '{}'", updatedApplication.getName()); readPermissions.add(properties.getUserRole()); } List<String> writePermissions = permissionsMap.get("WRITE"); if (!writePermissions.contains(properties.getUserRole())) { log.info("Chaos Monkey WRITE permissions applied for '{}'", updatedApplication.getName()); writePermissions.add(properties.getUserRole()); } } else { log.info( "Revoking Chaos Monkey READ and WRITE permissions for '{}'", updatedApplication.getName()); permissionsMap.get("READ").remove(properties.getUserRole()); permissionsMap.get("WRITE").remove(properties.getUserRole()); } return updatedApplication; }
Source:
public void sendIntervalsImmediately() { NetworkUtils.setConnectionTimeout(2000); NetworkUtils.cancelTransferAfter(2000); task.run(); NetworkUtils.setConnectionTimeout(12000); }

Target:
public void sendIntervalsImmediately() { NetworkUtils.setConnectionTimeout(2000); NetworkUtils.cancelTransferAfter(2000); task.run(); NetworkUtils.setConnectionTimeout(NetworkUtils.DEFAULT_TIMEOUT); }
Source:
public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if (representationDescription.getEndUserDocumentation() != null && !StringUtil.isEmpty(representationDescription.getEndUserDocumentation())) { userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }

Target:
public void setBrowserInput(final Viewpoint viewpoint, final RepresentationDescription representationDescription) { if (browser != null && representationDescription != null && viewpoint != null) { String userDocumentation; if (!StringUtil.isEmpty(representationDescription.getEndUserDocumentation())) { userDocumentation = representationDescription.getEndUserDocumentation(); } else { userDocumentation = viewpoint.getEndUserDocumentation(); } String content = null; if (containsHTMLDocumentation(userDocumentation)) { content = getContentWhenHtml(userDocumentation, representationDescription.eResource().getURI()); } else { content = getContentWhenNoHtml(userDocumentation); } browser.setText(content); } else if (browser != null) { browser.setText("<br><br><center><b>" + Messages.ViewpointsSelectionWizardPage_documentation_title + "</b></center>"); } }
Source:
public void close() throws Exception { Exception exception = null; for ( AutoCloseable closeable : closeables ) { try { closeable.close(); } catch ( Exception e ) { if ( exception == null ) { exception = e; } if ( exception != e ) { exception = Exceptions.combine( exception, e ); } } } if ( exception != null ) { throw exception; } }

Target:
public void close() { IOUtils.closeAll( RuntimeException.class, closeables.toArray( new AutoCloseable[closeables.size()] ) ); }
Source:
public void readData(ObjectDataInput in) throws IOException { type = PermissionType.getType(in.readUTF()); name = in.readUTF(); principal = in.readUTF(); int endpointsSize = in.readInt(); if (endpointsSize != 0) { Set<String> endpoints = new HashSet<>(); for (int i = 0; i < endpointsSize; i++) { endpoints.add(in.readUTF()); } this.endpoints = endpoints; } int actionsSize = in.readInt(); if (actionsSize != 0) { Set<String> actions = new HashSet<>(); for (int i = 0; i < actionsSize; i++) { actions.add(in.readUTF()); } this.actions = actions; } }

Target:
public void readData(ObjectDataInput in) throws IOException { type = PermissionType.getType(in.readUTF()); name = in.readUTF(); principal = in.readUTF(); int endpointsSize = in.readInt(); if (endpointsSize != 0) { Set<String> endpoints = createHashSet(endpointsSize); for (int i = 0; i < endpointsSize; i++) { endpoints.add(in.readUTF()); } this.endpoints = endpoints; } int actionsSize = in.readInt(); if (actionsSize != 0) { Set<String> actions = createHashSet(actionsSize); for (int i = 0; i < actionsSize; i++) { actions.add(in.readUTF()); } this.actions = actions; } }
Source:
public static Configuration grabConfig(String content) { try { content = content.replaceAll("(?i)(?m)^[ \t]*includeConfig.*", ""); final Path nextflowDir = Files.createTempDirectory("nextflow"); final Path tempFile = Paths.get(nextflowDir.toString(), "nextflow.config"); Files.write(tempFile, content.getBytes(StandardCharsets.UTF_8)); final Configuration configuration = grabConfig(tempFile.toFile()); Files.deleteIfExists(tempFile); Files.deleteIfExists(nextflowDir); return configuration; } catch (IOException e) { throw new NextflowParsingException("unable to parse nexflow config"); } }

Target:
public static Configuration grabConfig(String content) { Path nextflowDir = null; try { String newContent = content.replaceAll("(?i)(?m)^[ \t]*includeConfig.*", ""); nextflowDir = Files.createTempDirectory("nextflow"); final Path tempFile = Paths.get(nextflowDir.toString(), "nextflow.config"); Files.write(tempFile, newContent.getBytes(StandardCharsets.UTF_8)); return grabConfig(tempFile.toFile()); } catch (IOException e) { throw new NextflowParsingException("unable to parse nexflow config"); } finally { if (nextflowDir != null) { FileUtils.deleteQuietly(nextflowDir.toFile()); } } }
Source:
private FeedbackResponseCommentAttributes getCommentFromDatastore(String jsonId, DataBundle bundle) { FeedbackResponseCommentAttributes comment = bundle.feedbackResponseComments.get(jsonId); String questionId = null; try { int qnNumber = Integer.parseInt(comment.feedbackQuestionId); questionId = fqLogic.getFeedbackQuestion( comment.feedbackSessionName, comment.courseId, qnNumber).getId(); } catch (NumberFormatException e) { questionId = comment.feedbackQuestionId; } comment.feedbackResponseId.replaceFirst(comment.feedbackQuestionId, questionId); return frcLogic.getFeedbackResponseComment(comment.feedbackResponseId, comment.commentGiver, comment.createdAt); }

Target:
private FeedbackResponseCommentAttributes getCommentFromDatastore(String jsonId, DataBundle bundle) { FeedbackResponseCommentAttributes comment = bundle.feedbackResponseComments.get(jsonId); return frcLogic.getFeedbackResponseComment(comment.feedbackResponseId, comment.commentGiver, comment.createdAt); }
Source:
public void testExecuteAsyncNullTable() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(null); groupRequest.setNesting(Arrays.asList("os", "device", "version")); queryExecutor.executeAsync(groupRequest); }

Target:
public void testExecuteAsyncNullTable() throws Exception { GroupRequest groupRequest = new GroupRequest(); groupRequest.setTable(null); groupRequest.setNesting(Arrays.asList("os", "device", "version")); try { queryExecutor.executeAsync(groupRequest); } catch (QueryStoreException e) { assertEquals(QueryStoreException.ErrorCode.INVALID_REQUEST, e.getErrorCode()); throw e; } }
Source:
protected HttpConnection httpOpen(String method, URL u, AcceptEncoding acceptEncoding) throws IOException { if (method == null || u == null || acceptEncoding == null) { throw new NullPointerException(); } final Proxy proxy = HttpSupport.proxyFor(proxySelector, u); HttpConnection conn = connectionFactory.create(u, proxy); if (!sslVerify && "https".equals(u.getProtocol())) { HttpSupport.disableSslVerify(conn); } conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); if (acceptEncoding == AcceptEncoding.GZIP) { conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP); } conn.setRequestProperty(HDR_PRAGMA, "no-cache"); if (UserAgent.get() != null) { conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get()); } int timeOut = getTimeout(); if (timeOut != -1) { int effTimeOut = timeOut * 1000; conn.setConnectTimeout(effTimeOut); conn.setReadTimeout(effTimeOut); } StringBuilder cookieHeaderValue = new StringBuilder(); for (HttpCookie cookie : relevantCookies) { if (!cookie.hasExpired()) { if (cookieHeaderValue.length() > 0) { cookieHeaderValue.append(";"); } cookieHeaderValue.append(cookie.toString()); } } if (cookieHeaderValue.length() >= 0) { conn.setRequestProperty(HDR_COOKIE, cookieHeaderValue.toString()); } if (this.headers != null && !this.headers.isEmpty()) { for (Map.Entry<String, String> entry : this.headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); } authMethod.configureRequest(conn); return conn; }

Target:
protected HttpConnection httpOpen(String method, URL u, AcceptEncoding acceptEncoding) throws IOException { if (method == null || u == null || acceptEncoding == null) { throw new NullPointerException(); } final Proxy proxy = HttpSupport.proxyFor(proxySelector, u); HttpConnection conn = connectionFactory.create(u, proxy); if (!sslVerify && "https".equals(u.getProtocol())) { HttpSupport.disableSslVerify(conn); } conn.setInstanceFollowRedirects(false); conn.setRequestMethod(method); conn.setUseCaches(false); if (acceptEncoding == AcceptEncoding.GZIP) { conn.setRequestProperty(HDR_ACCEPT_ENCODING, ENCODING_GZIP); } conn.setRequestProperty(HDR_PRAGMA, "no-cache"); if (UserAgent.get() != null) { conn.setRequestProperty(HDR_USER_AGENT, UserAgent.get()); } int timeOut = getTimeout(); if (timeOut != -1) { int effTimeOut = timeOut * 1000; conn.setConnectTimeout(effTimeOut); conn.setReadTimeout(effTimeOut); } StringBuilder cookieHeaderValue = new StringBuilder(); for (HttpCookie cookie : relevantCookies) { if (!cookie.hasExpired()) { if (cookieHeaderValue.length() > 0) { cookieHeaderValue.append(';'); } cookieHeaderValue.append(cookie.toString()); } } if (cookieHeaderValue.length() >= 0) { conn.setRequestProperty(HDR_COOKIE, cookieHeaderValue.toString()); } if (this.headers != null && !this.headers.isEmpty()) { for (Map.Entry<String, String> entry : this.headers.entrySet()) conn.setRequestProperty(entry.getKey(), entry.getValue()); } authMethod.configureRequest(conn); return conn; }
Source:
public void createOrUpdateCounter(Class<?> clazz, String key, String metricName, long value) { Map<String, Metric> metricMap = getMetricsForKey(key); if (!metricMap.containsKey(metricName)) { Counter counter = _metricRegistry.counter(MetricRegistry.name(clazz, key, metricName)); counter.inc(value); metricMap.put(metricName, counter); } else { Metric metric = metricMap.get(metricName); if (metric instanceof Counter) { ((Counter) metric).inc(value); } } }

Target:
public synchronized void createOrUpdateCounter(Class<?> clazz, String key, String metricName, long value) { validateArguments(clazz, key, metricName); String fullMetricName = MetricRegistry.name(clazz, key, metricName); Counter counter = _metricRegistry.getCounters().get(fullMetricName); if (counter == null) { counter = _metricRegistry.counter(fullMetricName); } counter.inc(value); }
Source:
public static void readPlayerNames() { final File folder = new File(State.getDefaultSaveDir()); for (final File file : folder.listFiles()) { if (file.isDirectory()) { continue; } final String fileName = removeExtension(file.getName()); State.getSaveGames().add(fileName); } }

Target:
public static void readPlayerNames() { try { final File folder = new File(State.getDefaultSaveDir()); for (final File file : folder.listFiles()) { if (file.isDirectory()) { continue; } final String fileName = removeExtension(file.getName()); State.getSaveGames().add(fileName); } } catch (NullPointerException e) { OBSERVABLE.notify(GameObserver.Category.ERROR, GameObserver.Error.NULLPOINTEREXCEPTION, "SaveGame.readPlayerNames()", e.getMessage()); } }
Source:
public void testListDeploymentEmpty() throws Exception { final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup); server.enqueue(new MockResponse().setResponseCode(404)); List<Deployment> deployments = deploymentApi.list(); assertTrue(deployments.size() == 0); }

Target:
public void testListDeploymentEmpty() throws Exception { final DeploymentApi deploymentApi = api.getDeploymentApi(resourceGroup); server.enqueue(new MockResponse().setResponseCode(404)); List<Deployment> deployments = deploymentApi.list(); assertTrue(deployments.size() == 0); assertSent(server, "GET", "/subscriptions/" + subscriptionId + "/resourcegroups/" + resourceGroup + "/providers/microsoft.resources/deployments?api-version=2016-02-01"); }
Source:
private void preRenderUpdate(RenderingStage renderingStage) { resetStats(); currentRenderingStage = renderingStage; if (currentRenderingStage == RenderingStage.MONO || currentRenderingStage == RenderingStage.LEFT_EYE) { isFirstRenderingStageForCurrentFrame = true; } else { isFirstRenderingStageForCurrentFrame = false; } if (isFirstRenderingStageForCurrentFrame) { timeSmoothedMainLightIntensity = TeraMath.lerp(timeSmoothedMainLightIntensity, getMainLightIntensityAt(playerCamera.getPosition()), secondsSinceLastFrame); playerCamera.update(secondsSinceLastFrame); renderableWorld.update(); renderableWorld.generateVBOs(); secondsSinceLastFrame = 0; displayResolutionDependentFBOs.update(); millisecondsSinceRenderingStart += secondsSinceLastFrame * 1000; } if (currentRenderingStage != RenderingStage.MONO) { playerCamera.updateFrustum(); } renderableWorld.queueVisibleChunks(isFirstRenderingStageForCurrentFrame); if (requestedTaskListRefresh) { List<Node> orderedNodes = renderGraph.getNodesInTopologicalOrder(); renderTaskListGenerator.generateFrom(orderedNodes); requestedTaskListRefresh = false; } }

Target:
private void preRenderUpdate(RenderingStage renderingStage) { resetStats(); currentRenderingStage = renderingStage; if (currentRenderingStage == RenderingStage.MONO || currentRenderingStage == RenderingStage.LEFT_EYE) { isFirstRenderingStageForCurrentFrame = true; } else { isFirstRenderingStageForCurrentFrame = false; } if (isFirstRenderingStageForCurrentFrame) { timeSmoothedMainLightIntensity = TeraMath.lerp(timeSmoothedMainLightIntensity, getMainLightIntensityAt(playerCamera.getPosition()), secondsSinceLastFrame); playerCamera.update(secondsSinceLastFrame); renderableWorld.update(); renderableWorld.generateVBOs(); secondsSinceLastFrame = 0; displayResolutionDependentFBOs.update(); millisecondsSinceRenderingStart += secondsSinceLastFrame * 1000; } if (currentRenderingStage != RenderingStage.MONO) { playerCamera.updateFrustum(); } renderableWorld.queueVisibleChunks(isFirstRenderingStageForCurrentFrame); if (requestedTaskListRefresh) { List<Node> orderedNodes = renderGraph.getNodesInTopologicalOrder(); renderPipelineTaskList = renderTaskListGenerator.generateFrom(orderedNodes); requestedTaskListRefresh = false; } }
Source:
public boolean isOpen() { return fileChannel.isOpen(); }

Target:
public boolean isOpen() { return open; }
Source:
public void onMessage(MessageHolderWithTokens message) { try { logger.debug("receiving tokens from queue, triggering Notification Dispatcher class to pick the right sender"); dequeueEvent.fire(message); } catch (DispatchInitiationException e) { throw e; } catch (Exception e) { logger.error("NotificationDispatcher or PushNotificationSender unexpectedly failed, the message won't be redelivered", e); } }

Target:
public void onMessage(MessageHolderWithTokens message) { try { logger.trace("receiving tokens from queue, triggering Notification Dispatcher class to pick the right sender"); dequeueEvent.fire(message); } catch (DispatchInitiationException e) { throw e; } catch (Exception e) { logger.error("NotificationDispatcher or PushNotificationSender unexpectedly failed, the message won't be redelivered", e); } }
Source:
public Object fromBytes(byte[] bytes) throws ConversionException { if (bytes == null || bytes.length == 0) { return null; } try { JsonNode root = unmarshallingMapper.readTree(bytes); String typeName = root.fieldNames().next(); JsonNode value = root.get(typeName); if (value.isArray()) { String className = value.get(0).asText(); return mapper.treeToValue(value,Class.forName(className)); } if (typeName.equals("String")) { return value.asText(); } else if (typeName.equals("Long")) { return value.asLong(); } else if (typeName.equals("Integer")) { return value.asInt(); } else if (typeName.equals("BigDecimal")) { return value.decimalValue(); } else if (typeName.equals("Double")) { return value.doubleValue(); } else if (typeName.equals("Float")) { return value.doubleValue(); } else if (typeName.equals("Boolean")) { return value.asBoolean(); } else if (typeName.equals("byte[]")) { return value.binaryValue(); } else if (typeName.equals("char[]")) { return value.asText().toCharArray(); } else if (typeName.equals("DateTime")) { return new DateTime(value.get("millis").asLong()); } else if (typeName.equals("DefaultTuple")) { return jsonBytesToTupleConverter.convert(value.binaryValue()); } String className = value.get("@class") == null ? null : value.get("@class").asText(); if (className != null) { return mapper.treeToValue(value, Class.forName(className)); } return jsonBytesToTupleConverter.convert(bytes); } catch (Exception e) { throw new SmartJsonConversionException(e.getMessage(), e); } }

Target:
public Object fromBytes(byte[] bytes) throws ConversionException { if (bytes == null || bytes.length == 0) { return null; } try { JsonNode root = unmarshallingMapper.readTree(bytes); String typeName = root.fieldNames().next(); JsonNode value = root.get(typeName); if (value.isArray()) { String className = value.get(0).asText(); return mapper.treeToValue(value, this.beanClassLoader.loadClass(className)); } if (typeName.equals("String")) { return value.asText(); } else if (typeName.equals("Long")) { return value.asLong(); } else if (typeName.equals("Integer")) { return value.asInt(); } else if (typeName.equals("BigDecimal")) { return value.decimalValue(); } else if (typeName.equals("Double")) { return value.doubleValue(); } else if (typeName.equals("Float")) { return value.doubleValue(); } else if (typeName.equals("Boolean")) { return value.asBoolean(); } else if (typeName.equals("byte[]")) { return value.binaryValue(); } else if (typeName.equals("char[]")) { return value.asText().toCharArray(); } else if (typeName.equals("DateTime")) { return new DateTime(value.get("millis").asLong()); } else if (typeName.equals("DefaultTuple")) { return jsonBytesToTupleConverter.convert(value.binaryValue()); } String className = value.get("@class") == null ? null : value.get("@class").asText(); if (className != null) { return mapper.treeToValue(value, Class.forName(className)); } return jsonBytesToTupleConverter.convert(bytes); } catch (Exception e) { throw new SmartJsonConversionException(e.getMessage(), e); } }
Source:
public void asyncGetCube(int cubeX, int cubeY, int cubeZ, @Nonnull Requirement req, @Nonnull Consumer<Cube> callback) { Cube cube = getLoadedCube(cubeX, cubeY, cubeZ); if (req == Requirement.LOAD_CACHED || (cube != null && req.compareTo(Requirement.GENERATE) <= 0)) { callback.accept(cube); return; } if (cube == null) { AsyncWorldIOExecutor.queueCubeLoad(worldServer, cubeIO, this, cubeX, cubeY, cubeZ, loaded -> { Column col = getLoadedChunk(cubeX, cubeZ); onCubeLoaded(loaded, col); loaded = postCubeLoadAttempt(cubeX, cubeY, cubeZ, loaded, col, req); callback.accept(loaded); }); } }

Target:
public void asyncGetCube(int cubeX, int cubeY, int cubeZ, @Nonnull Requirement req, @Nonnull Consumer<Cube> callback) { Cube cube = getLoadedCube(cubeX, cubeY, cubeZ); if (req == Requirement.LOAD_CACHED || (cube != null && req.compareTo(Requirement.GENERATE) <= 0)) { callback.accept(cube); return; } if (cube == null) { AsyncWorldIOExecutor.queueCubeLoad(worldServer, cubeIO, this, cubeX, cubeY, cubeZ, loaded -> { Column col = getLoadedChunk(cubeX, cubeZ); if(col != null) { onCubeLoaded(loaded, col); } loaded = postCubeLoadAttempt(cubeX, cubeY, cubeZ, loaded, col, req); callback.accept(loaded); }); } }
Source:
public void getDiffStatistics() { statistics.setFileNumDiff(records.size()); for (Map.Entry<String, List<CheckstyleRecord>> entry : records.entrySet()) { final List<CheckstyleRecord> list = entry.getValue(); for (CheckstyleRecord rec : list) { if (rec.getIndex() == CheckstyleReportsParser.BASE_REPORT_INDEX) { statistics.addSeverityRecordRemoved(rec.getSeverity()); statistics.addModuleRecordRemoved(rec.getSource()); } else if (rec.getIndex() == CheckstyleReportsParser.PATCH_REPORT_INDEX) { statistics.addSeverityRecordAdded(rec.getSeverity()); statistics.addModuleRecordAdded(rec.getSource()); } else { throw new AssertionError(); } statistics.incrementUniqueMessageCount(rec.getIndex()); } } }

Target:
public void getDiffStatistics() { statistics.setFileNumDiff(records.size()); for (Map.Entry<String, List<CheckstyleRecord>> entry : records.entrySet()) { final List<CheckstyleRecord> list = entry.getValue(); for (CheckstyleRecord rec : list) { if (rec.getIndex() == CheckstyleReportsParser.BASE_REPORT_INDEX) { statistics.addSeverityRecordRemoved(rec.getSeverity()); statistics.addModuleRecordRemoved(rec.getSource()); } else { statistics.addSeverityRecordAdded(rec.getSeverity()); statistics.addModuleRecordAdded(rec.getSource()); } statistics.incrementUniqueMessageCount(rec.getIndex()); } } }
Source:
public static ClientSettings getClientSettingsFromConnectionStringBuilder(ConnectionStringBuilder builder) { TokenProvider tokenProvider = null; if (builder.getAuthentication() != null) { if (builder.getAuthentication().replace(" ", "").equalsIgnoreCase(ConnectionStringBuilder.MANAGED_IDENTITY_AUTHENTICATION.replace(" ", ""))) { tokenProvider = new ManagedIdentityTokenProvider(); } } else if (builder.getSharedAccessSignatureToken() == null) { tokenProvider = new SharedAccessSignatureTokenProvider(builder.getSasKeyName(), builder.getSasKey(), SecurityConstants.DEFAULT_SAS_TOKEN_VALIDITY_IN_SECONDS); } else { tokenProvider = new SharedAccessSignatureTokenProvider(builder.getSharedAccessSignatureToken(), Instant.MAX); } return new ClientSettings(tokenProvider, builder.getRetryPolicy(), builder.getOperationTimeout(), builder.getTransportType()); }

Target:
public static ClientSettings getClientSettingsFromConnectionStringBuilder(ConnectionStringBuilder builder) { TokenProvider tokenProvider = null; String authentication = builder.getAuthentication(); if (authentication != null) { if (authentication.equalsIgnoreCase(ConnectionStringBuilder.MANAGED_IDENTITY_AUTHENTICATION_WITH_SPACE) || authentication.equalsIgnoreCase(ConnectionStringBuilder.MANAGED_IDENTITY_AUTHENTICATION_WITHOUT_SPACE)) { tokenProvider = new ManagedIdentityTokenProvider(); } } else if (builder.getSharedAccessSignatureToken() == null) { tokenProvider = new SharedAccessSignatureTokenProvider(builder.getSasKeyName(), builder.getSasKey(), SecurityConstants.DEFAULT_SAS_TOKEN_VALIDITY_IN_SECONDS); } else { tokenProvider = new SharedAccessSignatureTokenProvider(builder.getSharedAccessSignatureToken(), Instant.MAX); } return new ClientSettings(tokenProvider, builder.getRetryPolicy(), builder.getOperationTimeout(), builder.getTransportType()); }
Source:
public void install() { List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); String osMajorVersion = getMachine().getOsDetails().getVersion(); osMajorVersion = osMajorVersion.indexOf(".") > 0 ? osMajorVersion.substring(0, osMajorVersion.indexOf('.')) : osMajorVersion; String epelVersion = Strings.nullToEmpty(CENTOS_VERSION_TO_EPEL_VERSION.get(osMajorVersion)); String osArchitecture = getMachine().getOsDetails().getArch(); List<String> commands = ImmutableList.<String>builder() .add(chainGroup("which yum", sudo("yum -y update ca-certificates"), sudo("rpm -Uvh " + format("<LINK_4>", osMajorVersion, osArchitecture, epelVersion)))) .add(ifExecutableElse0("zypper", chainGroup( ok(sudo("zypper --non-interactive addrepo <LINK_2> erlang_sles_11")), ok(sudo("zypper --non-interactive addrepo <LINK_0> erlang_suse_11")), ok(sudo("zypper --non-interactive addrepo <LINK_1> erlang_suse_12")), ok(sudo("zypper --non-interactive addrepo <LINK_3> erlang_suse_13"))))) .add(installPackage( ImmutableMap.of( "apt", "erlang-nox erlang-dev", "port", "erlang@"+getErlangVersion()+"+ssl"), "erlang")) .addAll(commandsToDownloadUrlsAs(urls, saveAs)) .add(installExecutable("tar")) .add(format("tar xvzf %s",saveAs)) .build(); newScript(INSTALLING). failOnNonZeroResultCode(). body.append(commands).execute(); }

Target:
public void install() { List<String> urls = resolver.getTargets(); String saveAs = resolver.getFilename(); String osMajorVersion = getMachine().getOsDetails().getVersion(); if (Strings.isNullOrEmpty(osMajorVersion)) { osMajorVersion = "7"; } else { osMajorVersion = osMajorVersion.indexOf(".") > 0 ? osMajorVersion.substring(0, osMajorVersion.indexOf('.')) : osMajorVersion; if (!CENTOS_VERSION_TO_EPEL_VERSION.keySet().contains(osMajorVersion)) { osMajorVersion = "7"; } } String epelVersion = CENTOS_VERSION_TO_EPEL_VERSION.get(osMajorVersion); String osArchitecture = getMachine().getOsDetails().getArch(); if (Strings.isNullOrEmpty(osArchitecture)) { osArchitecture = "x86_64"; } List<String> commands = ImmutableList.<String>builder() .add(chainGroup("which yum", sudo("yum -y update ca-certificates"), sudo("rpm -Uvh " + format("<LINK_4>", osMajorVersion, osArchitecture, epelVersion)))) .add(ifExecutableElse0("zypper", chainGroup( ok(sudo("zypper --non-interactive addrepo <LINK_2> erlang_sles_11")), ok(sudo("zypper --non-interactive addrepo <LINK_0> erlang_suse_11")), ok(sudo("zypper --non-interactive addrepo <LINK_1> erlang_suse_12")), ok(sudo("zypper --non-interactive addrepo <LINK_3> erlang_suse_13"))))) .add(installPackage( ImmutableMap.of( "apt", "erlang-nox erlang-dev", "port", "erlang@"+getErlangVersion()+"+ssl"), "erlang")) .addAll(commandsToDownloadUrlsAs(urls, saveAs)) .add(installExecutable("tar")) .add(format("tar xvzf %s",saveAs)) .build(); newScript(INSTALLING). failOnNonZeroResultCode(). body.append(commands).execute(); }