auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Set<WorkflowVersion> updateWorkflowPath(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Workflow to modify.", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "Workflow with updated information", required = true) Workflow workflow){ Workflow c = workflowDAO.findById(workflowId); Set<WorkflowVersion> versions = c.getVersions(); for(WorkflowVersion version : versions){ version.setWorkflowPath(workflow.getDefaultWorkflowPath()); } return versions; }

Target:
public Workflow updateWorkflowPath(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Workflow to modify.", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "Workflow with updated information", required = true) Workflow workflow){ Workflow c = workflowDAO.findById(workflowId); Helper.checkEntry(c); Helper.checkUser(user, c); Set<WorkflowVersion> versions = c.getVersions(); for(WorkflowVersion version : versions){ version.setWorkflowPath(workflow.getDefaultWorkflowPath()); } return c; }
Source:
public int compareTo(HealthReport o) { return (Integer.compare(this.score, o.score)); }

Target:
public int compareTo(HealthReport o) { return Integer.compare(this.score, o.score); }
Source:
public void updateAllStackConfigsByCrn(String envCrn) { String accountId = Crn.fromString(envCrn).getAccountId(); if (accountId == null) { throw new NotFoundException(String.format("No account id found for crn '%s'", envCrn)); } Environment environment = environmentService .findByResourceCrnAndAccountIdAndArchivedIsFalse(envCrn, accountId). orElseThrow(() -> new NotFoundException( String.format("No environment found with crn '%s'", envCrn))); String userCrn = ThreadBasedUserCrnProvider.getUserCrn(); reactorFlowManager .triggerStackConfigUpdatesFlow(environment, userCrn); }

Target:
public void updateAllStackConfigsByCrn(String envCrn) { String accountId = Crn.safeFromString(envCrn).getAccountId(); Environment environment = environmentService .findByResourceCrnAndAccountIdAndArchivedIsFalse(envCrn, accountId). orElseThrow(() -> new NotFoundException( String.format("No environment found with crn '%s'", envCrn))); String userCrn = ThreadBasedUserCrnProvider.getUserCrn(); reactorFlowManager .triggerStackConfigUpdatesFlow(environment, userCrn); }
Source:
public void setServerBootSource(@Nonnull ServerCreateBuilder builder, @Nonnull Openstack os) throws JCloudsCloud.ProvisioningFailedException { final List<String> matchingIds = getDescriptor().findMatchingIds(os, name); final String id = selectIdFromListAndLogProblems(matchingIds, name, "Images"); if (createNewVolume) { final BlockDeviceMappingBuilder volumeBuilder = Builders.blockDeviceMapping() .sourceType(BDMSourceType.IMAGE) .destinationType(BDMDestType.VOLUME) .uuid(id) .volumeSize(volumeSize) .deleteOnTermination(true) .bootIndex(0); builder.blockDevice(volumeBuilder.build()); } else { builder.image(id); } }

Target:
public void setServerBootSource(@Nonnull ServerCreateBuilder builder, @Nonnull Openstack os) throws JCloudsCloud.ProvisioningFailedException { final List<String> matchingIds = getDescriptor().findMatchingIds(os, name); final String id = selectIdFromListAndLogProblems(matchingIds, name, "Images"); if (volumeSize != null && volumeSize > 0) { final BlockDeviceMappingBuilder volumeBuilder = Builders.blockDeviceMapping() .sourceType(BDMSourceType.IMAGE) .destinationType(BDMDestType.VOLUME) .uuid(id) .volumeSize(volumeSize) .deleteOnTermination(true) .bootIndex(0); builder.blockDevice(volumeBuilder.build()); } else { builder.image(id); } }
Source:
public void editTargetPassword() throws Exception { final String VALUE = RandomStringUtils.randomAlphanumeric(5); ModelNodeResult defaultValueResult = operations.readAttribute(JMS_BRIDGE_ADDRESS, TARGET_PASSWORD_IDENTIFIER); defaultValueResult.assertSuccess(); ModelNode defaultValue = defaultValueResult.value(); try { new ConfigChecker.Builder(client, JMS_BRIDGE_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, TARGET_PASSWORD_IDENTIFIER, VALUE) .verifyFormSaved() .verifyAttribute(TARGET_PASSWORD_IDENTIFIER, VALUE); } finally { operations.writeAttribute(JMS_BRIDGE_ADDRESS, TARGET_PASSWORD_IDENTIFIER, defaultValue); } }

Target:
public void editTargetPassword() throws Exception { final String VALUE = RandomStringUtils.randomAlphanumeric(5); ModelNodeResult origValueResult = operations.readAttribute(JMS_BRIDGE_ADDRESS, TARGET_PASSWORD_IDENTIFIER, ReadAttributeOption.NOT_INCLUDE_DEFAULTS); origValueResult.assertSuccess(); ModelNode origValue = origValueResult.value(); try { new ConfigChecker.Builder(client, JMS_BRIDGE_ADDRESS) .configFragment(page.getConfigFragment()) .editAndSave(ConfigChecker.InputType.TEXT, TARGET_PASSWORD_IDENTIFIER, VALUE) .verifyFormSaved() .verifyAttribute(TARGET_PASSWORD_IDENTIFIER, VALUE); } finally { operations.writeAttribute(JMS_BRIDGE_ADDRESS, TARGET_PASSWORD_IDENTIFIER, origValue); } }
Source:
private long checkLatency(int value) { RemoteService service = RemoteService.getRemoteService(); long startTime = System.currentTimeMillis(); long result = service.doRemoteFunction(value); long timeTaken = System.currentTimeMillis() - startTime; LOGGER.info("Time taken (ms): " + timeTaken); return result; }

Target:
private long checkLatency(int value) { long startTime = System.currentTimeMillis(); long result = RemoteService.getRemoteService().doRemoteFunction(value); long timeTaken = System.currentTimeMillis() - startTime; LOGGER.info("Time taken (ms): " + timeTaken); return result; }
Source:
public PathFinder(final Vector startNode, final Vector endNode) { this.startNode = startNode; this.endNode = endNode; path = new ArrayList<Vector>(); }

Target:
public PathFinder(final Vector startNode, final Vector endNode) { this.startNode = startNode; this.endNode = endNode; this.path = new ArrayList<Vector>(); }
Source:
private Collection<AMRMClient.ContainerRequest> getPendingRequestsAndCheckConsistency( Priority priority, Resource resource, int expectedNum) { final List<AMRMClient.ContainerRequest> matchingRequests = resourceManagerClient.getMatchingRequests(priority, ResourceRequest.ANY, resource) .stream() .flatMap(requests -> requests.stream()) .collect(Collectors.toList()); Preconditions.checkState( matchingRequests.size() == expectedNum, "The RMClient's and YarnResourceManagers internal state about the number of pending container requests for priority %s has diverged. " + "Number client's pending container requests %s != Number RM's pending container requests %s.", priority.getPriority(), matchingRequests.size(), expectedNum); return matchingRequests; }

Target:
private Collection<AMRMClient.ContainerRequest> getPendingRequestsAndCheckConsistency( Priority priority, Resource resource, int expectedNum) { final List<AMRMClient.ContainerRequest> matchingRequests = resourceManagerClient.getMatchingRequests(priority, ResourceRequest.ANY, resource) .stream() .flatMap(Collection::stream) .collect(Collectors.toList()); Preconditions.checkState( matchingRequests.size() == expectedNum, "The RMClient's and YarnResourceManagers internal state about the number of pending container requests for priority %s has diverged. " + "Number client's pending container requests %s != Number RM's pending container requests %s.", priority.getPriority(), matchingRequests.size(), expectedNum); return matchingRequests; }
Source:
public void setUp() { this.checkConfig = createCheckConfig(UnstableAnnotationCheck.class); this.checkConfig.addAttribute("currentVersion", "8.2-SNAPSHOT"); }

Target:
public void setUp() { this.checkConfig = createCheckConfig(UnstableAnnotationCheck.class); this.checkConfig.addAttribute("currentVersion", "8.1-SNAPSHOT"); }
Source:
private void initializeInstances(List<InstanceConfig> instanceConfigs) throws Exception { logger.info("Initializing cluster information from {}", dcName); for (InstanceConfig instanceConfig : instanceConfigs) { int schemaVersion = getSchemaVersion(instanceConfig); switch (schemaVersion) { case 0: String instanceName = instanceConfig.getInstanceName(); long instanceXid = getXid(instanceConfig); if (instanceXid <= currentXid) { logger.info("Adding node and its disks and replicas", instanceName); AmbryDataNode datanode = new AmbryDataNode(getDcName(instanceConfig), clusterMapConfig, instanceConfig.getHostName(), Integer.valueOf(instanceConfig.getPort()), getRackId(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToAmbryDataNode.put(instanceName, datanode); allInstances.add(instanceName); } else { logger.info( "Ignoring instanceConfig for because the xid associated with it ({}) is later than current xid ({})", instanceName, instanceXid, currentXid); } break; default: logger.error("Unknown InstanceConfig schema version: {}, ignoring.", schemaVersion); break; } } logger.info("Initialized cluster information from {}", dcName); }

Target:
private void initializeInstances(List<InstanceConfig> instanceConfigs) throws Exception { logger.info("Initializing cluster information from {}", dcName); for (InstanceConfig instanceConfig : instanceConfigs) { int schemaVersion = getSchemaVersion(instanceConfig); switch (schemaVersion) { case 0: String instanceName = instanceConfig.getInstanceName(); long instanceXid = getXid(instanceConfig); if (instanceXid <= currentXid) { logger.info("Adding node and its disks and replicas", instanceName); AmbryDataNode datanode = new AmbryDataNode(getDcName(instanceConfig), clusterMapConfig, instanceConfig.getHostName(), Integer.valueOf(instanceConfig.getPort()), getRackId(instanceConfig), getSslPortStr(instanceConfig)); initializeDisksAndReplicasOnNode(datanode, instanceConfig); instanceNameToAmbryDataNode.put(instanceName, datanode); allInstances.add(instanceName); } else { logger.info( "Ignoring instanceConfig for because the xid associated with it ({}) is later than current xid ({})", instanceName, instanceXid, currentXid); helixClusterManagerMetrics.ignoredUpdatesCount.inc(); } break; default: logger.error("Unknown InstanceConfig schema version: {}, ignoring.", schemaVersion); break; } } logger.info("Initialized cluster information from {}", dcName); }
Source:
public static long readNumberFromFile(final Path filePath) throws IOException, NumberFormatException { try (BufferedReader reader = Files .newBufferedReader(filePath, StandardCharsets.UTF_8)) { final long num = Long.parseLong(reader.readLine()); return num; } catch (final IOException | NumberFormatException e) { logger.error(String.format("Failed to read the number from the file %s", filePath), e); throw e; } }

Target:
public static long readNumberFromFile(final Path filePath) throws IOException, NumberFormatException { final List<String> allLines = Files.readAllLines(filePath); if (!allLines.isEmpty()) { return Long.parseLong(allLines.get(0)); } else { throw new NumberFormatException("unable to parse empty file " + filePath.toString()); } }
Source:
public void paintControl(@Nullable PaintEvent e) { if (e == null || !isSelected()) { return; } Iterator<Color> colorsIt = Iterators.cycle(COLORS); GC gc = e.gc; for (ISeries series : getChart().getSeriesSet().getSeries()) { Color color = colorsIt.next(); for (int index : getSelection()) { int graphIndex = getGraphIndexFromTableEntryIndex(series, index); if (graphIndex < 0) { continue; } Rectangle rectangle = ((IBarSeries) series).getBounds()[graphIndex]; gc.setBackground(color); gc.fillRectangle(rectangle); } } }

Target:
public void paintControl(@Nullable PaintEvent e) { if (e == null || !isSelected()) { return; } Iterator<Color> colorsIt = Iterators.cycle(COLORS); GC gc = e.gc; for (ISeries series : getChart().getSeriesSet().getSeries()) { Color color = colorsIt.next(); for (int index : getSelection()) { int graphIndex = getGraphIndexFromTableEntryIndex(series, index); if (graphIndex < 0) { continue; } Rectangle[] bounds = ((IBarSeries) series).getBounds(); if (bounds.length != fCategories.length) { continue; } Rectangle rectangle = bounds[graphIndex]; gc.setBackground(color); gc.fillRectangle(rectangle); } } }
Source:
public ReadOnlyByteBuf(ByteBuf buffer) { super(buffer.capacity()); if (buffer instanceof ReadOnlyByteBuf || buffer instanceof DuplicatedByteBuf) { this.buffer = buffer.unwrap(); } else { this.buffer = buffer; } setIndex(buffer.readerIndex(), buffer.writerIndex()); }

Target:
public ReadOnlyByteBuf(ByteBuf buffer) { super(buffer.maxCapacity()); if (buffer instanceof ReadOnlyByteBuf || buffer instanceof DuplicatedByteBuf) { this.buffer = buffer.unwrap(); } else { this.buffer = buffer; } setIndex(buffer.readerIndex(), buffer.writerIndex()); }
Source:
void reset() { chunkOperationTracker = null; chunkCompleted = false; retainChunkExceptionOnSuccess = false; chunkBlobId = null; chunkIndex = -1; chunkException = null; successfullyDeserialized = false; blobContentAvailableToProcess = false; decryptCallbackResultInfo = new AtomicReference<>(); decryptCallbackResultInfo.set(new DecryptCallBackResultInfo()); correlationIdToGetRequestInfo.clear(); state = ChunkState.Free; }

Target:
void reset() { chunkOperationTracker = null; chunkCompleted = false; retainChunkExceptionOnSuccess = false; chunkBlobId = null; chunkIndex = -1; chunkException = null; successfullyDeserialized = false; progressTracker = null; decryptCallbackResultInfo = null; correlationIdToGetRequestInfo.clear(); state = ChunkState.Free; }
Source:
private boolean publishMessageUnbound(DataMessage message) throws KuraException { publishInternal(message); DataServiceImpl.this.dataServiceListeners.onMessagePublished(message.getId(), message.getTopic()); return true; }

Target:
private void publishMessageUnbound(DataMessage message) throws KuraException { publishInternal(message); DataServiceImpl.this.dataServiceListeners.onMessagePublished(message.getId(), message.getTopic()); }
Source:
public static Collection<BaseKey> getAllRegisteredKeys() { return registeredKeys.values(); }

Target:
public static Collection<BaseKey> getAllRegisteredKeys() { return Collections.unmodifiableCollection(registeredKeys.values()); }
Source:
public void openFile(File file) throws CheckstyleException { if (file != null) { try { currentFile = file; title = "Checkstyle GUI : " + file.getName(); reloadActionEnabled = true; final DetailAST parseTree; if (parseMode.equals(ParseMode.PLAIN_JAVA)) { parseTree = parseFile(file); } else { parseTree = parseFileWithComments(file); } parseTreeTableModel.setParseTree(parseTree); parseTreeTableModel.setParseMode(parseMode); final String[] sourceLines = getFileText(file).toLinesArray(); linesToPosition.clear(); linesToPosition.add(0); final StringBuilder sb = new StringBuilder(); for (final String element : sourceLines) { linesToPosition.add(sb.length()); sb.append(element).append(System.lineSeparator()); } text = sb.toString(); } catch (IOException | ANTLRException ex) { final String exceptionMsg = String.format(Locale.ROOT, "%s occurred while opening file %s.", ex.getClass().getSimpleName(), file.getPath()); throw new CheckstyleException(exceptionMsg, ex); } } }

Target:
public void openFile(File file) throws CheckstyleException { if (file != null) { try { currentFile = file; title = "Checkstyle GUI : " + file.getName(); reloadActionEnabled = true; final DetailAST parseTree; switch (parseMode) { case PLAIN_JAVA: parseTree = parseFile(file); break; case JAVA_WITH_COMMENTS: case JAVA_WITH_JAVADOC_AND_COMMENTS: parseTree = parseFileWithComments(file); break; default: throw new IllegalArgumentException("Unknown mode: " + parseMode); } parseTreeTableModel.setParseTree(parseTree); parseTreeTableModel.setParseMode(parseMode); final String[] sourceLines = getFileText(file).toLinesArray(); linesToPosition.clear(); linesToPosition.add(0); final StringBuilder sb = new StringBuilder(); for (final String element : sourceLines) { linesToPosition.add(sb.length()); sb.append(element).append(System.lineSeparator()); } text = sb.toString(); } catch (IOException | ANTLRException ex) { final String exceptionMsg = String.format(Locale.ROOT, "%s occurred while opening file %s.", ex.getClass().getSimpleName(), file.getPath()); throw new CheckstyleException(exceptionMsg, ex); } } }
Source:
@Test public void overloads() throws Exception { PrintWriter receiver = new PrintWriter(ByteStreams.nullOutputStream()); assertEquals(PrintWriter.class.getMethod("print", Object.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {new Object()})); assertEquals(PrintWriter.class.getMethod("print", String.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {"message"})); assertEquals(PrintWriter.class.getMethod("print", int.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {42})); }

Target:
@Test public void overloads() throws Exception { PrintWriter receiver = new PrintWriter(new NullOutputStream()); assertEquals(PrintWriter.class.getMethod("print", Object.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {new Object()})); assertEquals(PrintWriter.class.getMethod("print", String.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {"message"})); assertEquals(PrintWriter.class.getMethod("print", int.class), GroovyCallSiteSelector.method(receiver, "print", new Object[] {42})); }
Source:
private void handleNewDatastream() { leaderDoAssignmentScheduled.set(false); List<Datastream> newDatastreams = _adapter.getAllDatastreams(); if (newDatastreams.size() == 0) { return; } try { _destinationManager.populateDatastreamDestination(newDatastreams); newDatastreams = newDatastreams.stream().filter( ds -> ds.getDestination() != null).collect(Collectors.toList()); if (newDatastreams.size() == 0) { return; } newDatastreams.stream().forEach(ds -> { if (!_adapter.updateDatastream(ds)) { LOG.error(String.format("Failed to update datastream destination for datastream %s, " + "This datastream will not be scheduled for producing events ", ds.getName())); } }); _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); } catch (Exception e) { LOG.error("Failed to update the destination of new datastreams.", e); if (leaderDoAssignmentScheduled.compareAndSet(false, true)) { LOG.warn("Schedule retry for handling new datastream"); _executor.schedule(() -> _eventQueue.put(CoordinatorEvent.createHandleNewDatastreamEvent()), _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } } }

Target:
private void handleNewDatastream() { leaderDoAssignmentScheduled.set(false); List<Datastream> newDatastreams = _adapter.getAllDatastreams(); if (newDatastreams.size() == 0) { return; } try { _destinationManager.populateDatastreamDestination(newDatastreams); for (Datastream stream: newDatastreams) { if (stream.hasDestination() && !_adapter.updateDatastream(stream)) { LOG.error(String.format("Failed to update datastream destination for datastream %s, " + "This datastream will not be scheduled for producing events ", stream.getName())); } } _eventQueue.put(CoordinatorEvent.createLeaderDoAssignmentEvent()); } catch (Exception e) { LOG.error("Failed to update the destination of new datastreams.", e); if (leaderDoAssignmentScheduled.compareAndSet(false, true)) { LOG.warn("Schedule retry for handling new datastream"); _executor.schedule(() -> _eventQueue.put(CoordinatorEvent.createHandleNewDatastreamEvent()), _config.getRetryIntervalMS(), TimeUnit.MILLISECONDS); } } }
Source:
public static Nucleotide inferAltFromPileup(final Map<Nucleotide, List<BaseQuality>> baseQualities, final Nucleotide refBase) { Nucleotide[] bases = BASES; Arrays.sort(bases, (L, R) -> Integer.compare(baseQualities.get(R).size(), baseQualities.get(L).size())); for (Nucleotide base : bases) { if (base != refBase) { return base; } } throw new GATKException.ShouldNeverReachHereException("The Alt base can not be inferred from the " + "pileup. The size of the pileup is: " + baseQualities.size()); }

Target:
static Nucleotide inferAltFromPileup(final Map<Nucleotide, List<BaseQuality>> baseQualities, final Nucleotide refBase) { final Nucleotide[] bases = BASES.clone(); Arrays.sort(bases, (L, R) -> Integer.compare(baseQualities.get(R).size(), baseQualities.get(L).size())); for (Nucleotide base : bases) { if (base != refBase) { return base; } } throw new GATKException.ShouldNeverReachHereException("The Alt base can not be inferred from the " + "pileup. The size of the pileup is: " + baseQualities.size()); }
Source:
public List<Installment> calculateInstallments(int amount, int freeInstallments, double interestRate, int maxInstallments) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, "/transactions/calculate_installments_amount"); Map<String, Object> params = new HashMap<String, Object>(); params.put("amount", amount); params.put("max_installments", maxInstallments); params.put("free_installments", freeInstallments); params.put("interest_rate", interestRate); request.setParameters(params); JsonObject response = request.execute(); JsonObject installmentsArray = response.getAsJsonObject("installments"); List<Installment> installments = new ArrayList<Installment>(); for (int i = 1; i <= maxInstallments; i++) { Installment objInstallment = new Installment(); JsonObject installment = installmentsArray.getAsJsonObject(""+i); objInstallment.setInstallment_amount(Integer.parseInt(installment.get("installment_amount").toString())); objInstallment.setAmount(Integer.parseInt(installment.get("amount").toString())); objInstallment.setInstallment(Integer.parseInt(installment.get("installment").toString())); installments.add(objInstallment); } return installments; }

Target:
public List<Installment> calculateInstallments(int amount, int freeInstallments, double interestRate, int maxInstallments) throws PagarMeException { final PagarMeRequest request = new PagarMeRequest(HttpMethod.GET, "/transactions/calculate_installments_amount"); Map<String, Object> params = new HashMap<String, Object>(); params.put("amount", amount); params.put("max_installments", maxInstallments); params.put("free_installments", freeInstallments); params.put("interest_rate", interestRate); request.setParameters(params); JsonObject response = request.execute(); JsonObject installmentsArray = response.getAsJsonObject("installments"); List<Installment> installments = new ArrayList<Installment>(); for (int i = 1; i <= maxInstallments; i++) { Installment objInstallment = new Installment(); JsonObject installment = installmentsArray.getAsJsonObject(""+i); objInstallment.setInstallmentAmount(Integer.parseInt(installment.get("installment_amount").toString())); objInstallment.setAmount(Integer.parseInt(installment.get("amount").toString())); objInstallment.setInstallment(Integer.parseInt(installment.get("installment").toString())); installments.add(objInstallment); } return installments; }
Source:
private LinkdHopCriteria(String nodeId, String nodeLabel) { super(nodeLabel); setId(nodeId); m_nodeId = nodeId; }

Target:
private LinkdHopCriteria(String nodeId, String nodeLabel) { super(nodeId,nodeLabel); m_nodeId = nodeId; }
Source:
private static void initClusterSeverities() { severities.put(AuditLogType.USER_ADD_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_ADD_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.USER_UPDATE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_UPDATE_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.USER_REMOVE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_REMOVE_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.SYSTEM_UPDATE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.SYSTEM_UPDATE_VDS_GROUP_FAILED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_UPDATE_VM_CLUSTER_DEFAULT_HOST_CLEARED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_TEMPLATE_FROM_TRUSTED_TO_UNTRUSTED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_TEMPLATE_FROM_UNTRUSTED_TO_TRUSTED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_TRUSTED_TO_UNTRUSTED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_UNTRUSTED_TO_TRUSTED, AuditLogSeverity.NORMAL); }

Target:
private static void initClusterSeverities() { severities.put(AuditLogType.USER_ADD_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_ADD_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.USER_UPDATE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_UPDATE_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.USER_REMOVE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_REMOVE_VDS_GROUP_FAILED, AuditLogSeverity.ERROR); severities.put(AuditLogType.SYSTEM_UPDATE_VDS_GROUP, AuditLogSeverity.NORMAL); severities.put(AuditLogType.SYSTEM_UPDATE_VDS_GROUP_FAILED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.USER_UPDATE_VM_CLUSTER_DEFAULT_HOST_CLEARED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_TEMPLATE_FROM_TRUSTED_TO_UNTRUSTED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_TEMPLATE_FROM_UNTRUSTED_TO_TRUSTED, AuditLogSeverity.NORMAL); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_TRUSTED_TO_UNTRUSTED, AuditLogSeverity.WARNING); severities.put(AuditLogType.IMPORTEXPORT_IMPORT_VM_FROM_UNTRUSTED_TO_TRUSTED, AuditLogSeverity.WARNING); }
Source:
public Info(boolean maturity, boolean eom, Frequency frequency, LocalDate periodEnd, SchedulePeriodType type) { super(); this.maturity = maturity; this.eom = eom; this.frequency = frequency; this.periodEnd = periodEnd; this.type = type; }

Target:
public Info(boolean maturity, boolean eom, Frequency frequency, LocalDate periodEnd, SchedulePeriodType type) { this.maturity = maturity; this.eom = eom; this.frequency = frequency; this.periodEnd = periodEnd; this.type = type; }
Source:
public static void updateAutoTuningParameters(Props props) { int count = 0; boolean noException = false; Map<String, String> params = null; if(props.containsKey(TuningCommonConstants.TUNING_API_END_POINT)==false) { log.error("Tuning API End Point not found in properties. Not applying auto tuning. "); return; } int retryCount = DEFAULT_TUNING_API_RETRY_COUNT; if (props.containsKey(TUNING_API_RETRY_COUNT)) { retryCount = props.getInt(TUNING_API_RETRY_COUNT); } while (!noException && count < retryCount) { try { count++; log.info("Calling get current run parameters. Try count " + count); params = getCurrentRunParameters(props); log.info("Parameters are " + params.toString()); noException = true; } catch (IOException e) { log.error("Error in getting current run parameter ", e); } catch (Exception e) { log.error("Error in getting current run parameter ", e); } } if (params != null) { for (Map.Entry<String, String> param : params.entrySet()) { props.put(HadoopConfigurationInjector.INJECT_PREFIX + param.getKey(), param.getValue()); log.info("Applied parameter " + param.getKey() + " with value " + param.getValue()); } props.put(HadoopConfigurationInjector.INJECT_PREFIX + "auto.tuning.enabled", "true"); } }

Target:
public void updateAutoTuningParameters(Props props) { int retryCount = 0; Map<String, String> params = null; if (!props.containsKey(TuningCommonConstants.TUNING_API_END_POINT)) { log.error("Tuning API End Point not found in properties. Not applying auto tuning. "); return; } int maxRetryCount = DEFAULT_TUNING_API_RETRY_COUNT; if (props.containsKey(TUNING_API_RETRY_COUNT)) { maxRetryCount = props.getInt(TUNING_API_RETRY_COUNT); } while (retryCount < maxRetryCount) { try { retryCount++; log.info("Calling get current run parameters. Try count " + retryCount); params = getCurrentRunParameters(props); break; } catch (Exception e) { log.error("Error in getting current run parameter ", e); } } if (params != null) { for (Map.Entry<String, String> param : params.entrySet()) { props.put(HadoopConfigurationInjector.INJECT_PREFIX + param.getKey(), param.getValue()); log.info("Applied parameter " + param.getKey() + " with value " + param.getValue()); } props.put(HadoopConfigurationInjector.INJECT_PREFIX + TuningCommonConstants.AUTO_TUNING_ENABLED, "true"); } }
Source:
protected void handleAttemptLockout(long elapsedRealtimeDeadline) { setPasswordEntryEnabled(false); long elapsedRealtime = SystemClock.elapsedRealtime(); new CountDownTimer(elapsedRealtimeDeadline - elapsedRealtime, 200) { @Override public void onTick(long millisUntilFinished) { int secondsRemaining = (int) Math.ceil(millisUntilFinished / 1000.0); mSecurityMessageDisplay.setMessage( R.string.kg_too_many_failed_attempts_countdown, true, secondsRemaining); } @Override public void onFinish() { mSecurityMessageDisplay.setMessage("", false); resetState(true); } }.start(); }

Target:
protected void handleAttemptLockout(long elapsedRealtimeDeadline) { setPasswordEntryEnabled(false); long elapsedRealtime = SystemClock.elapsedRealtime(); long millisInFuture = ((long) Math.ceil( (elapsedRealtimeDeadline - elapsedRealtime) / 1000.0) + 2) * 1000; new CountDownTimer(millisInFuture, 1000) { @Override public void onTick(long millisUntilFinished) { int secondsRemaining = (int) Math.round(millisUntilFinished / 1000.0) - 2; if (secondsRemaining > 0) { mSecurityMessageDisplay.setMessage( R.string.kg_too_many_failed_attempts_countdown, true, secondsRemaining); } else { mSecurityMessageDisplay.setMessage("", false); resetState(true ); cancel(); } } @Override public void onFinish() { } }.start(); }
Source:
public void setSparkObject(Object sparkObject) throws StandardException { value = sparkObject; }

Target:
public void setSparkObject(Object sparkObject) throws StandardException { if (sparkObject instanceof byte[]) { value = SerializationUtils.deserialize((byte[]) sparkObject); } else { value = sparkObject; } }
Source:
public Control createContents(Composite parent) { if(mappingsViewer.mappings == null) { setErrorMessage("Can not read pom.xml"); return parent; } mappingsViewer.setShell(parent.getShell()); return mappingsViewer.createContents(parent); }

Target:
public Control createContents(Composite parent) { if(!mappingsViewer.isValid()) { setErrorMessage(Messages.LifecycleMappingPropertyPage_invalidPom); return parent; } mappingsViewer.setShell(parent.getShell()); return mappingsViewer.createContents(parent); }
Source:
public void testGenerateDOIFrozenVersion() throws ApiException { ApiClient webClient = WorkflowIT.getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi workflowApi = new WorkflowsApi(webClient); UsersApi usersApi = new UsersApi(webClient); final Long userId = usersApi.getUser().getId(); usersApi.refreshWorkflows(userId); Workflow githubWorkflow = workflowApi .manualRegister("github", "DockstoreTestUser2/test_lastmodified", "/hello.wdl", "test-update-workflow", "wdl", "/test.json"); workflowApi.refresh(githubWorkflow.getId()); Workflow workflowBeforeFreezing = workflowApi.refresh(githubWorkflow.getId()); WorkflowVersion master = workflowBeforeFreezing.getWorkflowVersions().stream().filter(v -> v.getName().equals("master")).findFirst().get(); try { workflowApi.requestDOIForWorkflowVersion(workflowBeforeFreezing.getId(), master.getId(), ""); fail("This line should never execute if version is mutable. DOI should only be generated for frozen versions of workflows."); } catch (ApiException ex) { assertFalse("Version should not be frozen", master.isFrozen()); assertNull("version DOI is null", master.getDoiURL()); } master.setFrozen(true); final List<WorkflowVersion> workflowVersions1 = workflowApi .updateWorkflowVersion(workflowBeforeFreezing.getId(), Lists.newArrayList(master)); master = workflowVersions1.stream().filter(v -> v.getName().equals("master")).findFirst().get(); assertTrue(master.isFrozen()); try { workflowApi.requestDOIForWorkflowVersion(workflowBeforeFreezing.getId(), master.getId(), ""); fail("This line should never execute without valid Zenodo token"); } catch (ApiException ex) { } }

Target:
public void testGenerateDOIFrozenVersion() throws ApiException { ApiClient webClient = WorkflowIT.getWebClient(USER_2_USERNAME, testingPostgres); WorkflowsApi workflowApi = new WorkflowsApi(webClient); Workflow githubWorkflow = workflowApi .manualRegister("github", "DockstoreTestUser2/test_lastmodified", "/hello.wdl", "test-update-workflow", "wdl", "/test.json"); Workflow workflowBeforeFreezing = workflowApi.refresh(githubWorkflow.getId()); WorkflowVersion master = workflowBeforeFreezing.getWorkflowVersions().stream().filter(v -> v.getName().equals("master")).findFirst().get(); try { workflowApi.requestDOIForWorkflowVersion(workflowBeforeFreezing.getId(), master.getId(), ""); fail("This line should never execute if version is mutable. DOI should only be generated for frozen versions of workflows."); } catch (ApiException ex) { assertTrue(ex.getResponseBody().contains(FROZEN_VERSION_REQUIRED)); } master.setFrozen(true); final List<WorkflowVersion> workflowVersions1 = workflowApi .updateWorkflowVersion(workflowBeforeFreezing.getId(), Lists.newArrayList(master)); master = workflowVersions1.stream().filter(v -> v.getName().equals("master")).findFirst().get(); assertTrue(master.isFrozen()); try { workflowApi.requestDOIForWorkflowVersion(workflowBeforeFreezing.getId(), master.getId(), ""); fail("This line should never execute without valid Zenodo token"); } catch (ApiException ex) { assertTrue(ex.getResponseBody().contains(NO_ZENDO_USER_TOKEN)); } }
Source:
private void parseReportsXML() { try { constructServiceRequestBuilder(ReportXmlService).sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { if (!reportBaseUrl.trim().isEmpty() && !scheduledStatusCheckInProgress && !reportsWebappDeployed) { scheduleCheckStatus(); } setXmlInitialized(); } @Override public void onResponseReceived(Request request, Response response) { switch (response.getStatusCode()) { case Response.SC_NOT_FOUND: if (!reportBaseUrl.trim().isEmpty() && !scheduledStatusCheckInProgress && !reportsWebappDeployed) { scheduleCheckStatus(); } setXmlInitialized(); break; case Response.SC_OK: try { if (ReportParser.getInstance().parseReport(response.getText())) { resourceMap = ReportParser.getInstance().getResourceMap(); dashboardMap = ReportParser.getInstance().getDashboardMap(); isCommunityEdition = ReportParser.getInstance().isCommunityEdition(); } } catch (DOMParseException e) { } finally { setXmlInitialized(); } break; } } }); } catch (RequestException e) { setXmlInitialized(); } }

Target:
private void parseReportsXML() { try { constructServiceRequestBuilder(ReportXmlService).sendRequest(null, new RequestCallback() { @Override public void onError(Request request, Throwable exception) { scheduleCheckStatus(); setXmlInitialized(); } @Override public void onResponseReceived(Request request, Response response) { switch (response.getStatusCode()) { case Response.SC_NOT_FOUND: scheduleCheckStatus(); setXmlInitialized(); break; case Response.SC_OK: try { if (ReportParser.getInstance().parseReport(response.getText())) { resourceMap = ReportParser.getInstance().getResourceMap(); dashboardMap = ReportParser.getInstance().getDashboardMap(); isCommunityEdition = ReportParser.getInstance().isCommunityEdition(); } } catch (DOMParseException e) { } finally { setXmlInitialized(); } break; } } }); } catch (RequestException e) { setXmlInitialized(); } }
Source:
public void handle() { final TaskDetails details = running.get(task.getId()); if (details == null) { log.warn("Got status notice for task [%s] that isn't running...", task.getId()); return; } if (!status.isComplete()) { log.warn( "Got status notice for task [%s] that isn't complete (status = [%s])...", task.getId(), status.getStatusCode() ); return; } details.status = status.withDuration(System.currentTimeMillis() - details.startTime); try { workerCuratorCoordinator.updateAnnouncement( TaskAnnouncement.create( details.task, details.status, details.location ) ); log.info( "Job's finished. Completed [%s] with status [%s]", task.getId(), status.getStatusCode() ); } catch (Exception e) { log.makeAlert(e, "Failed to update task announcement") .addData("task", task.getId()) .emit(); } finally { running.remove(task.getId()); } }

Target:
public void handle() { final TaskDetails details = running.get(task.getId()); if (details == null) { log.warn("Got status notice for task [%s] that isn't running...", task.getId()); return; } if (!status.isComplete()) { log.warn( "WTF?! Got status notice for task [%s] that isn't complete (status = [%s])...", task.getId(), status.getStatusCode() ); return; } details.status = status.withDuration(System.currentTimeMillis() - details.startTime); try { workerCuratorCoordinator.updateTaskStatusAnnouncement( TaskAnnouncement.create( details.task, details.status, details.location ) ); log.info( "Job's finished. Completed [%s] with status [%s]", task.getId(), status.getStatusCode() ); } catch (Exception e) { log.makeAlert(e, "Failed to update task announcement") .addData("task", task.getId()) .emit(); } finally { running.remove(task.getId()); } }
Source:
public void update(Object obj) { try { execute(session -> { session.update(obj); return null; }); } catch (OptimisticLockException ex) { throw new ConcurrentModificationException("Row has the wrong version number; it may have " + "been saved in the background."); } catch (PersistenceException ex) { if (ex.getCause() instanceof ConstraintViolationException) { throw new ConcurrentModificationException(ex.getMessage()); } else { throw ex; } } }

Target:
public void update(Object obj) { try { execute(session -> { session.update(obj); return null; }); } catch (OptimisticLockException ex) { throw new ConcurrentModificationException("Row has the wrong version number; it may have " + "been saved in the background."); } catch (PersistenceException ex) { if (ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) { throw new ConstraintViolationException.Builder() .withMessage("Email or phone number conflicts with an existing account.").build(); } else { throw ex; } } }
Source:
public String getIpMatch() { return null; }

Target:
public String getIpMatch() { throw new UnsupportedOperationException(); }
Source:
private static void executeCheckSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack, int lastCodeSepLocation, int opcode, Set<VerifyFlag> verifyFlags) throws ScriptException { final boolean requireCanonical = verifyFlags.contains(VerifyFlag.STRICTENC) || verifyFlags.contains(VerifyFlag.DERSIG) || verifyFlags.contains(VerifyFlag.LOW_S); if (stack.size() < 2) throw new ScriptException("Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2"); byte[] pubKey = stack.pollLast(); byte[] sigBytes = stack.pollLast(); byte[] prog = script.getProgram(); byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length); UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1); try { writeBytes(outStream, sigBytes); } catch (IOException e) { throw new RuntimeException(e); } connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray()); boolean sigValid = false; try { TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, requireCanonical); Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags); sigValid = ECKey.verify(hash.getBytes(), sig, pubKey); } catch (Exception e1) { if (!e1.getMessage().contains("Reached past end of ASN.1 stream")) log.warn("Signature checking failed! {}", e1); } if (opcode == OP_CHECKSIG) stack.add(sigValid ? new byte[] {1} : new byte[] {}); else if (opcode == OP_CHECKSIGVERIFY) if (!sigValid) throw new ScriptException("Script failed OP_CHECKSIGVERIFY"); }

Target:
private static void executeCheckSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack, int lastCodeSepLocation, int opcode, Set<VerifyFlag> verifyFlags) throws ScriptException { final boolean requireCanonical = verifyFlags.contains(VerifyFlag.STRICTENC) || verifyFlags.contains(VerifyFlag.DERSIG) || verifyFlags.contains(VerifyFlag.LOW_S); if (stack.size() < 2) throw new ScriptException("Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2"); byte[] pubKey = stack.pollLast(); byte[] sigBytes = stack.pollLast(); byte[] prog = script.getProgram(); byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length); UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1); try { writeBytes(outStream, sigBytes); } catch (IOException e) { throw new RuntimeException(e); } connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray()); boolean sigValid = false; try { TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, requireCanonical); Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags); sigValid = ECKey.verify(hash.getBytes(), sig, pubKey); } catch (Exception e1) { if (!e1.getMessage().contains("Reached past end of ASN.1 stream")) log.warn("Signature checking failed!", e1); } if (opcode == OP_CHECKSIG) stack.add(sigValid ? new byte[] {1} : new byte[] {}); else if (opcode == OP_CHECKSIGVERIFY) if (!sigValid) throw new ScriptException("Script failed OP_CHECKSIGVERIFY"); }
Source:
public void testSingleUpdate() throws Exception { Subscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }); Thread.sleep(1000); Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertNotNull(ref); ObjectId update = triggerUpdate("refs/heads/master"); Thread.sleep(1000); ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(update, ref.getObjectId()); }

Target:
public void testSingleUpdate() throws Exception { setUpPublisher(1); TestSubscriber client1 = createSubscriber(new String[] { "refs/heads/*:refs/remotes/origin/*", "refs/tags/*:refs/tags/*" }, 2); connectLatch.await(); ObjectId update = triggerUpdate("refs/heads/master"); client1.await(); Repository r = client1.getRepository("testrepository").getRepository(); Ref ref = r.getRef("refs/pubsub/origin/heads/master"); assertEquals(update, ref.getObjectId()); }
Source:
public String validateChangeName( final String name, final LocalDate previousNameEndDate) { return previousNameEndDate.isAfter(getClockService().now()) ? "You can not select a future end date" : null; }

Target:
public String validateChangeName( final String name, final LocalDate previousNameEndDate) { if (name.equals(this.getName())) { return "New name must be different from the current name"; } else { return previousNameEndDate.isAfter(getClockService().now()) ? "You can not select a future end date" : null; } }
Source:
public void testGetHasStoreEntryHasCacheLoaderEntry() throws Exception { final MockStore realStore = new MockStore(Collections.singletonMap("key", "value")); this.store = spy(realStore); assertThat(realStore.getMap().get("key"), equalTo("value")); when(this.cacheLoader.load("key")).thenThrow(ExceptionFactory.newCacheLoaderException(new Exception())); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheLoader); assertThat(ehcache.get("key"), equalTo("value")); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoader, never()).load(eq("key")); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(realStore.getMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoaderOutcome.class)); }

Target:
public void testGetHasStoreEntryHasCacheLoaderEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "value")); this.store = spy(fakeStore); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); when(this.cacheLoader.load("key")).thenReturn("value"); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheLoader); assertThat(ehcache.get("key"), equalTo("value")); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoader, never()).load(eq("key")); verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoaderOutcome.class)); }
Source:
public EmailRecords<? extends BasicEmailRecordDto> getEmails(GridSettings filter, HttpServletRequest request) { int defaultRowsAmount = 10; int defaultPage = 1; EmailRecordSearchCriteria criteria = prepareCriteria(filter); List<EmailRecord> filtered = auditService.findEmailRecords(criteria); List<? extends BasicEmailRecordDto> rows = hideColumns(filtered, filter); long total = auditService.countEmailRecords(criteria); if (filter.getRows() == null) { filter.setRows(defaultRowsAmount); } if (filter.getPage() == null) { filter.setPage(defaultPage); } int totalPages = (int) Math.ceil((double) total / filter.getRows()); String username = getUsername(request); if (username != null) { lastFilter.put(username, filter); } return new EmailRecords<>((int) total, filter.getPage(), totalPages, rows); }

Target:
public EmailRecords<? extends BasicEmailRecordDto> getEmails(GridSettings filter, HttpServletRequest request) { EmailRecordSearchCriteria criteria = prepareCriteria(filter); List<EmailRecord> filtered = auditService.findEmailRecords(criteria); List<? extends BasicEmailRecordDto> rows = hideColumns(filtered, filter); long total = auditService.countEmailRecords(criteria); if (filter.getRows() == null) { int defaultRowsAmount = 10; filter.setRows(defaultRowsAmount); } if (filter.getPage() == null) { int defaultPage = 1; filter.setPage(defaultPage); } int totalPages = (int) Math.ceil((double) total / filter.getRows()); String username = getUsername(request); if (username != null) { lastFilter.put(username, filter); } return new EmailRecords<>((int) total, filter.getPage(), totalPages, rows); }
Source:
public RegisterResponse call() throws Exception { ServiceManager api = environment.getServiceManager(); RegisterResponse res = api.register(parameters); if (!res.isSuccess()) { return res; } switch (backstoreType) { case TYPE_GOOGLE: case TYPE_FACEBOOK: if (backstoreType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_FACEBOOK) { auth = api.loginByFacebook(accessToken); } else if (backstoreType == SocialFactory.SOCIAL_SOURCE_TYPE.TYPE_GOOGLE) { auth = api.loginByGoogle(accessToken); } break; default: String username = parameters.getString("username"); String password = parameters.getString("password"); auth = loginAPI.getAccessToken(username, password); Gson gson = new GsonBuilder().create(); PrefManager pref = new PrefManager(context, PrefManager.Pref.LOGIN); pref.put(PrefManager.Key.AUTH_JSON, gson.toJson(auth)); pref.put(PrefManager.Key.SEGMENT_KEY_BACKEND, ISegment.Values.PASSWORD); if (auth.isSuccess()) { logger.debug("login succeeded after email registration"); } } if (auth != null && auth.isSuccess()) { auth.profile = api.getProfile(); } return res; }

Target:
public RegisterResponse call() throws Exception { ServiceManager api = environment.getServiceManager(); RegisterResponse res = api.register(parameters); if (!res.isSuccess()) { return res; } switch (backstoreType) { case TYPE_GOOGLE: auth = api.loginByGoogle(accessToken); break; case TYPE_FACEBOOK: auth = api.loginByFacebook(accessToken); break; default: String username = parameters.getString("username"); String password = parameters.getString("password"); auth = loginAPI.getAccessToken(username, password); Gson gson = new GsonBuilder().create(); PrefManager pref = new PrefManager(context, PrefManager.Pref.LOGIN); pref.put(PrefManager.Key.AUTH_JSON, gson.toJson(auth)); pref.put(PrefManager.Key.SEGMENT_KEY_BACKEND, ISegment.Values.PASSWORD); if (auth.isSuccess()) { logger.debug("login succeeded after email registration"); } } if (auth != null && auth.isSuccess()) { auth.profile = api.getProfile(); } return res; }
Source:
public void testRawModeOption() { GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobInfo).rawMode(true).build(); assertEquals("RawMode from options not as expected.", true, options.isRawMode()); }

Target:
public void testRawModeOption() { for (Boolean boolVal : TestUtils.BOOLEAN_VALUES) { GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.All).rawMode(boolVal).build(); assertEquals("RawMode from options not as expected.", boolVal, options.isRawMode()); } }