auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void addAttributeField(Field attributeField, EntityProjectionBuilder projectionBuilder) { Class<?> parentType = projectionBuilder.getType(); String attributeName = attributeField.getName(); Class<?> attributeType = entityDictionary.getType(parentType, attributeName); if (attributeType != null) { Attribute matched = projectionBuilder.getAttributeByName(attributeName); if (matched == null) { Attribute attribute = Attribute.builder() .type(attributeType) .name(attributeName) .arguments( attributeField.getArguments().stream() .map(graphQLArgument -> com.yahoo.elide.request.Argument.builder() .name(graphQLArgument.getName()) .value( variableResolver.resolveValue( graphQLArgument.getValue())) .build()) .collect(Collectors.toList())) .build(); projectionBuilder.attribute(attribute); } else { if (matched.getArguments().isEmpty() && matched.getArguments() == Collections.EMPTY_SET) { matched.setArguments(new HashSet<>()); } attributeField.getArguments().forEach( graphQLArgument -> matched.getArguments().add( com.yahoo.elide.request.Argument.builder() .name(graphQLArgument.getName()) .value(variableResolver.resolveValue(graphQLArgument.getValue())) .build())); } } else { throw new InvalidEntityBodyException( String.format( "Unknown attribute field {%s.%s}.", entityDictionary.getJsonAliasFor(projectionBuilder.getType()), attributeName)); } }

Target:
private void addAttributeField(Field attributeField, EntityProjectionBuilder projectionBuilder) { Class<?> parentType = projectionBuilder.getType(); String attributeName = attributeField.getName(); String attributeAlias = attributeField.getAlias() == null ? attributeName : attributeField.getAlias(); Class<?> attributeType = entityDictionary.getType(parentType, attributeName); if (attributeType != null) { Attribute attribute = Attribute.builder() .type(attributeType) .name(attributeName) .alias(attributeAlias) .arguments( attributeField.getArguments().stream() .map(graphQLArgument -> com.yahoo.elide.request.Argument.builder() .name(graphQLArgument.getName()) .value( variableResolver.resolveValue( graphQLArgument.getValue())) .build()) .collect(Collectors.toList())) .build(); projectionBuilder.attribute(attribute); } else { throw new InvalidEntityBodyException(String.format( "Unknown attribute field {%s.%s}.", entityDictionary.getJsonAliasFor(projectionBuilder.getType()), attributeName)); } }
Source:
private String decode(final byte[] payload) { if (payload == null) { return ""; } final int length = Math.min(payload.length, 1024); return new String(payload, 0, length, UTF_8); }

Target:
private static String decode(final byte[] payload) { if (payload == null) { return ""; } final int length = Math.min(payload.length, 1024); return new String(payload, 0, length, UTF_8); }
Source:
public void testMultiLevelMergeCombineTask() throws Exception { final int keyCnt = 100000; final int valCnt = 8; addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInputComparator(this.comparator); setOutput(this.outList); getTaskConfig().setDriverStrategy(DriverStrategy.PARTIAL_GROUP); getTaskConfig().setMemoryDriver(COMBINE_MEM); getTaskConfig().setFilehandlesDriver(2); final CombineDriver<Record> testTask = new CombineDriver<Record>(); testDriver(testTask, MockCombiningReduceStub.class); int expSum = 0; for (int i = 1;i < valCnt; i++) { expSum += i; } final HashMap<IntValue, IntValue> aggMap = new HashMap<IntValue, IntValue>(); for (Record record : this.outList) { IntValue key = new IntValue(); IntValue value = new IntValue(); key = record.getField(0, key); value = record.getField(1, value); IntValue prevVal = aggMap.get(key); if (prevVal != null) { aggMap.put(key, new IntValue(prevVal.getValue() + value.getValue())); } else { aggMap.put(key, value); } } Assert.assertTrue("Resultset size was "+aggMap.size()+". Expected was "+keyCnt, aggMap.size() == keyCnt); for (IntValue integer : aggMap.values()) { Assert.assertTrue("Incorrect result", integer.getValue() == expSum); } this.outList.clear(); }

Target:
public void testMultiLevelMergeCombineTask() throws Exception { final int keyCnt = 100000; final int valCnt = 8; addInput(new UniformRecordGenerator(keyCnt, valCnt, false)); addInputComparator(this.comparator); setOutput(this.outList); getTaskConfig().setDriverStrategy(DriverStrategy.PARTIAL_GROUP); getTaskConfig().setMemoryDriver(COMBINE_MEM); getTaskConfig().setFilehandlesDriver(2); final CombineDriver<Record> testTask = new CombineDriver<Record>(); try { testDriver(testTask, MockCombiningReduceStub.class); } catch (Exception e) { e.printStackTrace(); Assert.fail("Invoke method caused exception."); } int expSum = 0; for (int i = 1;i < valCnt; i++) { expSum += i; } final HashMap<IntValue, IntValue> aggMap = new HashMap<IntValue, IntValue>(); for (Record record : this.outList) { IntValue key = new IntValue(); IntValue value = new IntValue(); key = record.getField(0, key); value = record.getField(1, value); IntValue prevVal = aggMap.get(key); if (prevVal != null) { aggMap.put(key, new IntValue(prevVal.getValue() + value.getValue())); } else { aggMap.put(key, value); } } Assert.assertTrue("Resultset size was "+aggMap.size()+". Expected was "+keyCnt, aggMap.size() == keyCnt); for (IntValue integer : aggMap.values()) { Assert.assertTrue("Incorrect result", integer.getValue() == expSum); } this.outList.clear(); }
Source:
protected Measurement[] getModelMeasurementsImpl() { return null; }

Target:
protected Measurement[] getModelMeasurementsImpl() { return new Measurement[]{new Measurement("ensemble size", this.ensemble != null ? this.ensemble.length : 0)}; }
Source:
private static List<String> loadEndpoints(JsonNode node) { Preconditions.checkNotNull(node, "Must have endpoints node"); Preconditions.checkArgument(node.isArray(), "Endpoints config should be an array"); final List<String> list = new ArrayList<>(node.size()); node.elements().forEachRemaining(endpoint -> { list.add(endpoint.asText()); }); return list; }

Target:
private static List<String> loadEndpoints(JsonNode node) { Preconditions.checkNotNull(node, "Must have endpoints node"); Preconditions.checkArgument(node.isArray(), "Endpoints config should be an array"); return Streams.stream(node.elements()) .map(endpoint -> endpoint.asText()) .collect(ImmutableList.toImmutableList()); }
Source:
public void getSystemInformation_shouldAddAllLoadedModulesInformation() { Module module = new Module("name", "moduleId", "packageName", "author", "description", "version"); ModuleFactory.loadModule(module, false); int numberOfModules = ModuleFactory.getLoadedModules().size(); Map<String, Map<String, String>> systemInfoMap = Context.getAdministrationService().getSystemInformation(); assertEquals(numberOfModules + 1, systemInfoMap.get("SystemInfo.title.moduleInformation").size()); }

Target:
public void getSystemInformation_shouldAddAllLoadedModulesInformation() { int numberOfModulesOld = ModuleFactory.getLoadedModules().size(); Module module = new Module("name", "moduleId", "packageName", "author", "description", "version"); ModuleFactory.loadModule(module, false); int numberOfModulesNew = ModuleFactory.getLoadedModules().size(); Map<String, Map<String, String>> systemInfoMap = adminService.getSystemInformation(); assertEquals(numberOfModulesNew, numberOfModulesOld + 1); assertEquals(numberOfModulesNew + 1, systemInfoMap.get("SystemInfo.title.moduleInformation").size()); }
Source:
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation, Consumer<Poller<T>> cancelOperation) { if (pollInterval == null || pollInterval.toNanos() <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Null, negative or zero value for poll " + "interval is not allowed.")); } if (pollOperation == null) { throw logger.logExceptionAsWarning(new IllegalArgumentException("Null value for poll operation is not " + "allowed.")); } this.pollInterval = pollInterval; this.pollOperation = pollOperation; this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null); this.fluxHandle = asyncPollRequestWithDelay() .flux() .repeat() .takeUntil(pollResponse -> hasCompleted()) .share(); this.fluxDisposable = fluxHandle.subscribe(); this.autoPollingEnabled = true; this.cancelOperation = cancelOperation; }

Target:
public Poller(Duration pollInterval, Function<PollResponse<T>, Mono<PollResponse<T>>> pollOperation, Consumer<Poller<T>> cancelOperation) { if (pollInterval == null || pollInterval.toNanos() <= 0) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Null, negative or zero value for poll interval is not allowed.")); } if (pollOperation == null) { throw logger.logExceptionAsWarning(new IllegalArgumentException( "Null value for poll operation is not allowed.")); } this.pollInterval = pollInterval; this.pollOperation = pollOperation; this.pollResponse = new PollResponse<>(OperationStatus.NOT_STARTED, null); this.fluxHandle = asyncPollRequestWithDelay() .flux() .repeat() .takeUntil(pollResponse -> hasCompleted()) .share(); this.fluxDisposable = fluxHandle.subscribe(); this.autoPollingEnabled = true; this.cancelOperation = cancelOperation; }
Source:
public void testList() throws GitLabApiException { Snippet snippet1 = createSnippet(new Snippet("Snippet 1", "Snippet.java", "Java content")); Snippet snippet2 = createSnippet(new Snippet("Snippet 2", "Snippet.java", "Another java content")); SnippetsApi api = gitLabApi.getSnippetApi(); List<Snippet> snippets = api.getSnippets(); assertTrue(snippets.size() >= 2); assertTrue(snippets.stream().anyMatch(s -> s.getContent().equals("Java content"))); assertTrue(snippets.stream().anyMatch(s -> s.getContent().equals("Another java content"))); deleteSnippet(snippet1); deleteSnippet(snippet2); }

Target:
public void testList() throws GitLabApiException { Snippet snippet1 = createSnippet(new Snippet(TEST_SNIPPET_TITLE_1, TEST_SNIPPET_FILE_NAME_1, TEST_SNIPPET_CONTENT_1)); Snippet snippet2 = createSnippet(new Snippet(TEST_SNIPPET_TITLE_1, TEST_SNIPPET_FILE_NAME_1, TEST_SNIPPET_CONTENT_2)); SnippetsApi api = gitLabApi.getSnippetApi(); List<Snippet> snippets = api.getSnippets(true); assertTrue(snippets.size() >= 2); assertTrue(snippets.stream().anyMatch(s -> s.getContent().equals(TEST_SNIPPET_CONTENT_1))); assertTrue(snippets.stream().anyMatch(s -> s.getContent().equals(TEST_SNIPPET_CONTENT_2))); deleteSnippet(snippet1); deleteSnippet(snippet2); }
Source:
private API getApi() { API api = new API(); for (DetailedLink link : getLinks()) { api.getLinks().add(LinkHelper.createLink(link.getHref(), link.getRel())); if (link.isSetLinkCapabilities() && link.getLinkCapabilities().isSetSearchable() && link.getLinkCapabilities().isSearchable()) { api.getLinks().add(LinkHelper.createLink(link.getHref(), link.getRel(), link.getUrlParmeters())); } } return api; }

Target:
private API getApi() { API api = new API(); for (DetailedLink detailedLink : getLinks()) { api.getLinks().add(LinkHelper.createLink(detailedLink.getHref(), detailedLink.getRel())); if (detailedLink.isSetLinkCapabilities() && detailedLink.getLinkCapabilities().isSetSearchable() && detailedLink.getLinkCapabilities().isSearchable()) { api.getLinks().add(LinkHelper.createLink(detailedLink.getHref(), detailedLink.getRel(), detailedLink.getUrlParmeters())); } } return api; }
Source:
public AbstractTmfStateProvider(ITmfTrace trace, Class<? extends ITmfEvent> eventType, String id) { this.fTrace = trace; this.fEventType = eventType; fEventsQueue = new ArrayBlockingQueue<>(DEFAULT_EVENTS_QUEUE_SIZE); fStateSystemAssigned = false; fEventHandlerThread = new Thread(new EventProcessor(), id + " Event Handler"); }

Target:
public AbstractTmfStateProvider(ITmfTrace trace, Class<? extends ITmfEvent> eventType, String id) { fTrace = trace; fEventType = eventType; fEventsQueue = new ArrayBlockingQueue<>(DEFAULT_EVENTS_QUEUE_SIZE); fStateSystemAssigned = false; fEventHandlerThread = new Thread(new EventProcessor(), id + " Event Handler"); }
Source:
private String createStandbyProcess(String type, String title, String tenantId, String tenantName) { Process process = fetchStandbyProcess(type, tenantId).orElse(null); if (process != null) { return process.getIdAsString(); } AtomicReference<String> processId = new AtomicReference<>(""); locks.tryLocked(LOCK_CREATE_STANDBY_PROCESS + "-" + type + "-" + tenantId, Duration.ofSeconds(30), () -> { Wait.millis(1200); Process p = fetchStandbyProcess(type, tenantId).orElse(null); if (p != null) { processId.set(p.getIdAsString()); return; } p = new Process(); p.setTitle(title); p.setProcessType(type); p.setTenantId(tenantId); p.setTenantName(tenantName); p.setState(ProcessState.STANDBY); p.setStarted(LocalDateTime.now()); elastic.update(p); process1stLevelCache.put(p.getId(), p); process2ndLevelCache.put(p.getId(), p); standbyProcessCache.put(type + "-" + tenantId, p); processId.set(p.getIdAsString()); }); return processId.get(); }

Target:
private String createStandbyProcess(String type, String title, String tenantId, String tenantName) { ValueHolder<String> processId = new ValueHolder<>(""); locks.tryLocked(LOCK_CREATE_STANDBY_PROCESS + "-" + type + "-" + tenantId, Duration.ofSeconds(30), () -> { Process p = fetchStandbyProcess(type, tenantId); if (p != null) { processId.set(p.getIdAsString()); return; } Wait.millis(1200); p = fetchStandbyProcess(type, tenantId); if (p != null) { processId.set(p.getIdAsString()); return; } p = new Process(); p.setTitle(title); p.setProcessType(type); p.setTenantId(tenantId); p.setTenantName(tenantName); p.setState(ProcessState.STANDBY); p.setStarted(LocalDateTime.now()); elastic.update(p); process1stLevelCache.put(p.getId(), p); process2ndLevelCache.put(p.getId(), p); standbyProcessCache.put(type + "-" + tenantId, p); processId.set(p.getIdAsString()); }); return processId.get(); }
Source:
public TransactionManager newTransactionManager() { if (globalTransactionManager == null) { throw new RuntimeException("No transaction manager set nor environemtn provided to loo it up"); } return new KieSpringTransactionManager(globalTransactionManager); }

Target:
public TransactionManager newTransactionManager() { if (globalTransactionManager == null) { throw new RuntimeException("No transaction manager set nor environment provided to look it up"); } return new KieSpringTransactionManager(globalTransactionManager); }
Source:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager) { Type keyType = boundVariables.getTypeVariable("K"); Type valueType = boundVariables.getTypeVariable("V"); Type mapType = typeManager.getParameterizedType(MAP, ImmutableList.of(TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(valueType.getTypeSignature()))); MethodHandle keyHashCode = functionManager.getScalarFunctionImplementation(functionManager.resolveOperator(OperatorType.HASH_CODE, fromTypes(keyType))).getMethodHandle(); MethodHandle keyEqual = functionManager.getScalarFunctionImplementation(functionManager.resolveOperator(OperatorType.EQUAL, fromTypes(keyType, keyType))).getMethodHandle(); MethodHandle keyIndeterminate = functionManager.getScalarFunctionImplementation( functionManager.resolveOperator(INDETERMINATE, TypeSignatureProvider.fromTypeSignatures((keyType.getTypeSignature())))).getMethodHandle(); MethodHandle instanceFactory = constructorMethodHandle(State.class, MapType.class).bindTo(mapType); return new ScalarFunctionImplementation( false, ImmutableList.of( valueTypeArgumentProperty(RETURN_NULL_ON_NULL), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)), METHOD_HANDLE.bindTo(mapType).bindTo(keyEqual).bindTo(keyHashCode).bindTo(keyIndeterminate), Optional.of(instanceFactory), isDeterministic()); }

Target:
public ScalarFunctionImplementation specialize(BoundVariables boundVariables, int arity, TypeManager typeManager, FunctionManager functionManager) { Type keyType = boundVariables.getTypeVariable("K"); Type valueType = boundVariables.getTypeVariable("V"); Type mapType = typeManager.getParameterizedType(MAP, ImmutableList.of(TypeSignatureParameter.of(keyType.getTypeSignature()), TypeSignatureParameter.of(valueType.getTypeSignature()))); MethodHandle keyHashCode = functionManager.getScalarFunctionImplementation(functionManager.resolveOperator(OperatorType.HASH_CODE, fromTypes(keyType))).getMethodHandle(); MethodHandle keyEqual = functionManager.getScalarFunctionImplementation(functionManager.resolveOperator(OperatorType.EQUAL, fromTypes(keyType, keyType))).getMethodHandle(); MethodHandle keyIndeterminate = functionManager.getScalarFunctionImplementation( functionManager.resolveOperator(INDETERMINATE, fromTypeSignatures((keyType.getTypeSignature())))).getMethodHandle(); MethodHandle instanceFactory = constructorMethodHandle(State.class, MapType.class).bindTo(mapType); return new ScalarFunctionImplementation( false, ImmutableList.of( valueTypeArgumentProperty(RETURN_NULL_ON_NULL), valueTypeArgumentProperty(RETURN_NULL_ON_NULL)), METHOD_HANDLE.bindTo(mapType).bindTo(keyEqual).bindTo(keyHashCode).bindTo(keyIndeterminate), Optional.of(instanceFactory), isDeterministic()); }
Source:
public ResponseEntity<?> create(@PathVariable("name") final String name, @Valid @RequestBody final EventTypeSchemaBase schema, final Errors errors) { if (errors.hasErrors()) { throw new ValidationException(errors); } final EventType eventType = eventTypeService.get(name); schemaService.addSchema(eventType, schema); return status(HttpStatus.OK).build(); }

Target:
public ResponseEntity<?> create(@PathVariable("name") final String name, @Valid @RequestBody final EventTypeSchemaBase schema, final Errors errors) { if (errors.hasErrors()) { throw new ValidationException(errors); } schemaService.addSchema(name, schema); return status(HttpStatus.OK).build(); }
Source:
RepositoryCache() { new Closer(queue).start(); ListenerList global = Repository.getGlobalListenerList(); global.addConfigChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { ConfigChangedEvent newEvent = new ConfigChangedEvent(); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addIndexChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { IndexChangedEvent newEvent = new IndexChangedEvent( event.isInternal()); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addRefsChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { RefsChangedEvent newEvent = new RefsChangedEvent(); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addWorkingTreeModifiedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { WorkingTreeModifiedEvent newEvent = new WorkingTreeModifiedEvent( event.getModified(), event.getDeleted()); newEvent.setRepository( getRepository(event.getRepository().getDirectory())); globalListeners.dispatch(newEvent); } }); }

Target:
RepositoryCache() { new Closer(queue).start(); ListenerList global = Repository.getGlobalListenerList(); global.addConfigChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { ConfigChangedEvent newEvent = new ConfigChangedEvent(); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addIndexChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { IndexChangedEvent newEvent = new IndexChangedEvent( event.isInternal()); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addRefsChangedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { RefsChangedEvent newEvent = new RefsChangedEvent(); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); global.addWorkingTreeModifiedListener(event -> { Repository repo = getRepository( event.getRepository().getDirectory()); if (repo == null || repo == event.getRepository()) { globalListeners.dispatch(event); } else { WorkingTreeModifiedEvent newEvent = new WorkingTreeModifiedEvent( event.getModified(), event.getDeleted()); newEvent.setRepository(repo); globalListeners.dispatch(newEvent); } }); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.upload_files_menu, menu); getMenuInflater().inflate(R.menu.sort_menu, menu.findItem(R.id.action_sort).getSubMenu()); mMainMenu = menu; mItemSelectAll = (MenuItem) menu.findItem(R.id.action_select_all); mItemSelectInverse = (MenuItem) menu.findItem(R.id.action_select_inverse); recoverSortMenuState(menu); setSelectAllMenuItemState(); setSelectInverseMenuItemState(); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.upload_files_menu, menu); getMenuInflater().inflate(R.menu.sort_menu, menu.findItem(R.id.action_sort).getSubMenu()); mMainMenu = menu; mItemSelectAll = menu.findItem(R.id.action_select_all); mItemSelectInverse = menu.findItem(R.id.action_select_inverse); recoverSortMenuState(menu); setSelectAllMenuItemState(); setSelectInverseMenuItemState(); return true; }
Source:
public boolean login(HttpServletRequest request, HttpServletResponse response, Scope... scopes) throws IOException { if (isLoggedIn()) { return true; } LOG.debug("Login " + this); if (OAuthProtocol.isOAuthFinal(request)) { log.debug("Login-FINAL " + this); AccessToken loginAccessToken = oauth.loginPhase2(request, response); if(loginAccessToken != null && !loginAccessToken.isError()) { login(loginAccessToken); } if (isLoggedIn()) { LOG.debug("Login-SUCCESS " + this); response.sendRedirect(OAuthProtocol.getTargetUrl(request)); return true; } else { response.sendError(HttpStatus.SC_UNAUTHORIZED); return false; } } else { this.loginScopes = getScopes(getScopesKey(request, response), scopes); LOG.debug("Login-PHASE1 " + this); oauth.loginPhase1(request, response, loginScopes); return false; } }

Target:
public boolean login(HttpServletRequest request, HttpServletResponse response, Scope... scopes) throws IOException { if (isLoggedIn()) { return true; } LOG.debug("Login " + this); if (OAuthProtocol.isOAuthFinal(request)) { LOG.debug("Login-FINAL " + this); AccessToken loginAccessToken = oauth.loginPhase2(request, response); if(loginAccessToken != null && !loginAccessToken.isError()) { login(loginAccessToken); } if (isLoggedIn()) { LOG.debug("Login-SUCCESS " + this); response.sendRedirect(OAuthProtocol.getTargetUrl(request)); return true; } else { response.sendError(HttpStatus.SC_UNAUTHORIZED); return false; } } else { this.loginScopes = getScopes(getScopesKey(request, response), scopes); LOG.debug("Login-PHASE1 " + this); oauth.loginPhase1(request, response, loginScopes); return false; } }
Source:
public String text(GrammarAST t) { if ( t==null ) return ""; StringBuilder buf = new StringBuilder(); int a = t.getTokenStartIndex(); int b = t.getTokenStopIndex(); IntervalSet ignore = new IntervalSet(); List<GrammarAST> optionsSubTrees = t.getNodesWithType(ELEMENT_OPTIONS); for (GrammarAST sub : optionsSubTrees) { ignore.add(sub.getTokenStartIndex(), sub.getTokenStopIndex()); } IntervalSet noOptions = new IntervalSet(); List<GrammarAST> labeledSubTrees = t.getNodesWithType(new IntervalSet(ASSIGN,PLUS_ASSIGN)); for (GrammarAST sub : labeledSubTrees) { noOptions.add(sub.getChild(0).getTokenStartIndex()); } String options; for (int i=a; i<=b; i++) { options = ""; if ( ignore.contains(i) ) continue; Token tok = tokenStream.get(i); StringBuilder existingOptions = new StringBuilder(); GrammarAST node = t.getNodeWithTokenIndex(tok.getTokenIndex()); if ( node instanceof GrammarASTWithOptions ) { GrammarASTWithOptions o = (GrammarASTWithOptions)node; Map<String, GrammarAST> opts = o.getOptions(); if ( opts.size()>0 ) { existingOptions.append(","); for (String key : opts.keySet()) { existingOptions.append(key); existingOptions.append('='); existingOptions.append(opts.get(key).getText()); } } } if ( node!=null && !noOptions.contains(i) && (tok.getType()==TOKEN_REF || tok.getType()==STRING_LITERAL || tok.getType()==RULE_REF) ) { options = String.format("<tokenIndex=%d%s>", tok.getTokenIndex(), existingOptions.toString()); } buf.append(tok.getText()); buf.append(options); } return buf.toString(); }

Target:
public String text(GrammarAST t) { if ( t==null ) return ""; int tokenStartIndex = t.getTokenStartIndex(); int tokenStopIndex = t.getTokenStopIndex(); IntervalSet ignore = new IntervalSet(); List<GrammarAST> optionsSubTrees = t.getNodesWithType(ELEMENT_OPTIONS); for (GrammarAST sub : optionsSubTrees) { ignore.add(sub.getTokenStartIndex(), sub.getTokenStopIndex()); } IntervalSet noOptions = new IntervalSet(); List<GrammarAST> labeledSubTrees = t.getNodesWithType(new IntervalSet(ASSIGN,PLUS_ASSIGN)); for (GrammarAST sub : labeledSubTrees) { noOptions.add(sub.getChild(0).getTokenStartIndex()); } StringBuilder buf = new StringBuilder(); for (int i=tokenStartIndex; i<=tokenStopIndex; i++) { if ( ignore.contains(i) ) { continue; } Token tok = tokenStream.get(i); StringBuilder elementOptions = new StringBuilder(); if (!noOptions.contains(i)) { GrammarAST node = t.getNodeWithTokenIndex(tok.getTokenIndex()); if ( node!=null && (tok.getType()==TOKEN_REF || tok.getType()==STRING_LITERAL || tok.getType()==RULE_REF) ) { elementOptions.append("tokenIndex=").append(tok.getTokenIndex()); } if ( node instanceof GrammarASTWithOptions ) { GrammarASTWithOptions o = (GrammarASTWithOptions)node; for (Map.Entry<String, GrammarAST> entry : o.getOptions().entrySet()) { if (elementOptions.length() > 0) { elementOptions.append(','); } elementOptions.append(entry.getKey()); elementOptions.append('='); elementOptions.append(entry.getValue().getText()); } } } buf.append(tok.getText()); if (elementOptions.length() > 0) { buf.append('<').append(elementOptions).append('>'); } } return buf.toString(); }
Source:
protected void updateLightmap(float[] normal, float[] lightmap, float x, float y, float z) { float e1 = 1 - 1e-2f; float e2 = 0.95f; boolean full = blockInfo.isFullCube(); EnumFacing side = null; if((full || y < -e1) && normal[1] < -e2) side = EnumFacing.DOWN; else if((full || y > e1) && normal[1] > e2) side = EnumFacing.UP; else if((full || z < -e1) && normal[2] < -e2) side = EnumFacing.NORTH; else if((full || z > e1) && normal[2] > e2) side = EnumFacing.SOUTH; else if((full || x < -e1) && normal[0] < -e2) side = EnumFacing.WEST; else if((full || x > e1) && normal[0] > e2) side = EnumFacing.EAST; int i = side == null ? 0 : side.ordinal() + 1; int brightness = blockInfo.getPackedLight()[i]; lightmap[0] = ((float)((brightness >> 0x04) & 0xF) * 0x20) / 0xFFFF; lightmap[1] = ((float)((brightness >> 0x14) & 0xF) * 0x20) / 0xFFFF; }

Target:
protected void updateLightmap(float[] normal, float[] lightmap, float x, float y, float z) { final float e1 = 1f - 1e-2f; final float e2 = 0.95f; boolean full = blockInfo.isFullCube(); EnumFacing side = null; if((full || y < -e1) && normal[1] < -e2) side = EnumFacing.DOWN; else if((full || y > e1) && normal[1] > e2) side = EnumFacing.UP; else if((full || z < -e1) && normal[2] < -e2) side = EnumFacing.NORTH; else if((full || z > e1) && normal[2] > e2) side = EnumFacing.SOUTH; else if((full || x < -e1) && normal[0] < -e2) side = EnumFacing.WEST; else if((full || x > e1) && normal[0] > e2) side = EnumFacing.EAST; int i = side == null ? 0 : side.ordinal() + 1; int brightness = blockInfo.getPackedLight()[i]; lightmap[0] = ((float)((brightness >> 0x04) & 0xF) * 0x20) / 0xFFFF; lightmap[1] = ((float)((brightness >> 0x14) & 0xF) * 0x20) / 0xFFFF; }
Source:
public void updated(Provider<E> provider, E oldElement, E element) { final K uidOld = oldElement.getUID(); final K uid = element.getUID(); if (!uidOld.equals(uid)) { logger.warn("Received update event for elements that UID differ (old: {}, new: {}). Ignore event.", uidOld, uid); return; } final E existingElement; elementWriteLock.lock(); try { existingElement = identifierToElement.get(uid); if (existingElement == null) { logger.debug("{} with key '{}' could not be updated for provider because it does not exist!", element.getClass().getSimpleName(), uid, provider.getClass().getSimpleName()); return; } try { beforeUpdateElement(existingElement); onUpdateElement(oldElement, element); } catch (final RuntimeException ex) { logger.warn("Could not update element: {}", ex.getMessage(), ex); return; } identifierToElement.put(uid, element); elementToProvider.remove(existingElement); elementToProvider.put(element, provider); final Collection<E> providerElements = providerToElements.get(provider); providerElements.remove(existingElement); providerElements.add(element); elements.remove(existingElement); elements.add(element); } finally { elementWriteLock.unlock(); } notifyListenersAboutUpdatedElement(oldElement, element); }

Target:
public void updated(Provider<E> provider, E oldElement, E element) { final K uidOld = oldElement.getUID(); final K uid = element.getUID(); if (!uidOld.equals(uid)) { logger.warn("Received update event for elements that UID differ (old: \"{}\", new: \"{}\"). Ignore event.", uidOld, uid); return; } final E existingElement; elementWriteLock.lock(); try { existingElement = identifierToElement.get(uid); if (existingElement == null) { logger.debug("Cannot update \"{}\" with key \"{}\" for provider \"{}\" because it does not exist!", element.getClass().getSimpleName(), uid, provider.getClass().getSimpleName()); return; } try { beforeUpdateElement(existingElement); onUpdateElement(oldElement, element); } catch (final RuntimeException ex) { logger.warn("Cannot update \"{}\" with key \"{}\": {}", element.getClass().getSimpleName(), uid, ex.getMessage(), ex); return; } identifierToElement.put(uid, element); elementToProvider.remove(existingElement); elementToProvider.put(element, provider); final Collection<E> providerElements = providerToElements.get(provider); providerElements.remove(existingElement); providerElements.add(element); elements.remove(existingElement); elements.add(element); } finally { elementWriteLock.unlock(); } notifyListenersAboutUpdatedElement(oldElement, element); }
Source:
public String toString() { String ifaceName = (mIfaceName == null ? "" : "InterfaceName: " + mIfaceName + " "); String linkAddresses = "LinkAddresses: ["; for (LinkAddress addr : mLinkAddresses) linkAddresses += addr.toString() + ","; linkAddresses += "] "; String dns = "DnsAddresses: ["; for (InetAddress addr : mDnses) dns += addr.getHostAddress() + ","; dns += "] "; String domainName = "Domains: " + mDomains; String mtu = "MTU: " + mMtu; String routes = " Routes: ["; for (RouteInfo route : mRoutes) routes += route.toString() + ","; routes += "] "; String proxy = (mHttpProxy == null ? "" : "HttpProxy: " + mHttpProxy.toString() + " "); String stacked = ""; if (mStackedLinks.values().size() > 0) { stacked += " Stacked: ["; for (LinkProperties link: mStackedLinks.values()) { stacked += " [" + link.toString() + " ],"; } stacked += "] "; } return "{" + ifaceName + linkAddresses + routes + dns + domainName + mMtu + proxy + stacked + "}"; }

Target:
public String toString() { String ifaceName = (mIfaceName == null ? "" : "InterfaceName: " + mIfaceName + " "); String linkAddresses = "LinkAddresses: ["; for (LinkAddress addr : mLinkAddresses) linkAddresses += addr.toString() + ","; linkAddresses += "] "; String dns = "DnsAddresses: ["; for (InetAddress addr : mDnses) dns += addr.getHostAddress() + ","; dns += "] "; String domainName = "Domains: " + mDomains; String mtu = "MTU: " + mMtu; String routes = " Routes: ["; for (RouteInfo route : mRoutes) routes += route.toString() + ","; routes += "] "; String proxy = (mHttpProxy == null ? "" : "HttpProxy: " + mHttpProxy.toString() + " "); String stacked = ""; if (mStackedLinks.values().size() > 0) { stacked += " Stacked: ["; for (LinkProperties link: mStackedLinks.values()) { stacked += " [" + link.toString() + " ],"; } stacked += "] "; } return "{" + ifaceName + linkAddresses + routes + dns + domainName + mtu + proxy + stacked + "}"; }
Source:
public void onInsertRowBelow() { assertNotReadOnly(); final Set<Integer> selectedRowIndexes = getSelectedRowIndexes(); if ( selectedRowIndexes.size() != 1 ) { return; } final int rowIndex = selectedRowIndexes.iterator().next(); insertRow( rowIndex + 1 ); }

Target:
public void onInsertRowBelow() { doInsertRow( ( index ) -> insertRow( index + 1 ) ); }
Source:
private Object invoke(Method recovery, Throwable throwable) throws IllegalAccessException, InvocationTargetException { if (!recovery.isAccessible()) { ReflectionUtils.makeAccessible(recovery); } if (args.length != 0) { Object[] newArgs = Arrays.copyOf(args, args.length + 1); newArgs[args.length] = throwable; return recovery.invoke(target, newArgs); } else { return recovery.invoke(target, throwable); } }

Target:
private Object invoke(Method recovery, Throwable throwable) throws IllegalAccessException, InvocationTargetException { boolean accessible = recovery.isAccessible(); try { if (!accessible) { ReflectionUtils.makeAccessible(recovery); } if (args.length != 0) { Object[] newArgs = Arrays.copyOf(args, args.length + 1); newArgs[args.length] = throwable; return recovery.invoke(target, newArgs); } else { return recovery.invoke(target, throwable); } } finally { if (!accessible) { recovery.setAccessible(false); } } }
Source:
public void addNotify() { super.addNotify(); IngestManager.getInstance().addIngestModuleEventListener(INGEST_MODULE_EVENTS_OF_INTEREST, ingestListener); IngestManager.getInstance().addIngestJobEventListener(INGEST_JOB_EVENTS_OF_INTEREST, ingestJobListener); Case.addEventTypeSubscriber(EnumSet.of(CURRENT_CASE), evt -> { devicesMap.clear(); devicesListPane.removeAll(); accountTypeMap.clear(); accountTypeListPane.removeAll(); CheckBoxIconPanel panel = createAccoutTypeCheckBoxPanel(Account.Type.DEVICE, true); accountTypeMap.put(Account.Type.DEVICE, panel.getCheckBox()); accountTypeListPane.add(panel); }); }

Target:
public void addNotify() { super.addNotify(); IngestManager.getInstance().addIngestModuleEventListener(INGEST_MODULE_EVENTS_OF_INTEREST, ingestListener); IngestManager.getInstance().addIngestJobEventListener(INGEST_JOB_EVENTS_OF_INTEREST, ingestJobListener); Case.addEventTypeSubscriber(EnumSet.of(CURRENT_CASE), evt -> { devicesMap.clear(); devicesListPane.removeAll(); accountTypeMap.clear(); accountTypeListPane.removeAll(); initalizeDeviceAccountType(); }); }
Source:
public void updateAssetsPath(String pluginId, String assetPath) { AnalyticsPluginInfo pluginInfo = getPluginInfo(pluginId); if (pluginInfo != null) { pluginInfo.setStaticAssetsPath(assetPath); } }

Target:
public void updateAssetsPath(String pluginId, String assetPath) { AnalyticsPluginInfo pluginInfo = getPluginInfo(pluginId); pluginInfo.setStaticAssetsPath(assetPath); }
Source:
private static JsonParserIterator<DataSegment> getMetadataSegments( DruidLeaderClient coordinatorClient, ObjectMapper jsonMapper, BytesAccumulatingResponseHandler responseHandler ) { Request request; try { request = coordinatorClient.makeRequest( HttpMethod.GET, StringUtils.format("/druid/coordinator/v1/metadata/segments") ); } catch (IOException e) { throw new RuntimeException(e); } ListenableFuture<InputStream> future = coordinatorClient.goStream( request, responseHandler ); try { future.get(); } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } if (responseHandler.getStatus() != HttpServletResponse.SC_OK) { throw new ISE( "Error while fetching metadata segments status[%s] description[%s]", responseHandler.status, responseHandler.description ); } final JavaType typeRef = jsonMapper.getTypeFactory().constructType(new TypeReference<DataSegment>() { }); JsonParserIterator<DataSegment> iterator = new JsonParserIterator<>( typeRef, future, request.getUrl().toString(), null, request.getUrl().getHost(), jsonMapper ); return iterator; }

Target:
private static JsonParserIterator<DataSegment> getMetadataSegments( DruidLeaderClient coordinatorClient, ObjectMapper jsonMapper, BytesAccumulatingResponseHandler responseHandler ) { Request request; try { request = coordinatorClient.makeRequest( HttpMethod.GET, StringUtils.format("/druid/coordinator/v1/metadata/segments") ); } catch (IOException e) { throw new RuntimeException(e); } ListenableFuture<InputStream> future = coordinatorClient.goAsync( request, responseHandler ); final JavaType typeRef = jsonMapper.getTypeFactory().constructType(new TypeReference<DataSegment>() { }); return new JsonParserIterator<>( typeRef, future, request.getUrl().toString(), null, request.getUrl().getHost(), jsonMapper ); }
Source:
protected void endVmCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { final boolean taskGroupSucceeded = getParameters().getTaskGroupSuccess(); Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), getParameters().getSnapshotType(), SnapshotStatus.LOCKED); if (taskGroupSucceeded) { getSnapshotDao().updateStatus(createdSnapshotId, SnapshotStatus.OK); if (getParameters().getParentCommand() != VdcActionType.RunVm && getVm() != null && getVm().isStatusUp() && getVm().getRunOnVds() != null) { performLiveSnapshot(createdSnapshotId); } } else { revertToActiveSnapshot(createdSnapshotId); } getVmStaticDAO().incrementDbGeneration(getVm().getId()); endActionOnDisks(); setSucceeded(taskGroupSucceeded); getReturnValue().setEndActionTryAgain(false); return null; } }); if (isVmDownUnexpectedly() && getVm().isAutoStartup() && wasVmUpInitially()) { Backend.getInstance().runInternalAction(VdcActionType.RunVm, new RunVmParams(getVmId()), ExecutionHandler.createInternalJobContext()); } }

Target:
protected void endVmCommand() { TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { final boolean taskGroupSucceeded = getParameters().getTaskGroupSuccess(); Guid createdSnapshotId = getSnapshotDao().getId(getVmId(), getParameters().getSnapshotType(), SnapshotStatus.LOCKED); if (taskGroupSucceeded) { getSnapshotDao().updateStatus(createdSnapshotId, SnapshotStatus.OK); if (getParameters().getParentCommand() != VdcActionType.RunVm && getVm() != null && getVm().isStatusUp() && getVm().getRunOnVds() != null) { performLiveSnapshot(createdSnapshotId); } } else { revertToActiveSnapshot(createdSnapshotId); } getVmStaticDAO().incrementDbGeneration(getVm().getId()); endActionOnDisks(); setSucceeded(taskGroupSucceeded); getReturnValue().setEndActionTryAgain(false); return null; } }); if (getVm().isAutoStartup() && isVmDownUnintentionally() && getParameters().getInitialVmStatus() != VMStatus.Down) { Backend.getInstance().runInternalAction(VdcActionType.RunVm, new RunVmParams(getVmId()), ExecutionHandler.createInternalJobContext()); } }
Source:
public void test_verifySignedCertificateTimestamps_failInvalidTimestamp() throws Exception { OpenSSLX509Certificate[] chain = new OpenSSLX509Certificate[] { CERT, CA }; byte[] tlsExtension = readTestFile("ct-signed-timestamp-list-invalid"); CTResults results = CT_VERIFIER.verifySignedCertificateTimestamps(chain, tlsExtension, null); assertEquals(0, results.getValidSCTs().size()); assertEquals(1, results.getInvalidSCTs().size()); }

Target:
public void test_verifySignedCertificateTimestamps_failInvalidTimestamp() throws Exception { OpenSSLX509Certificate[] chain = new OpenSSLX509Certificate[] { CERT, CA }; byte[] tlsExtension = readTestFile("ct-signed-timestamp-list-invalid"); CTResults results = CT_VERIFIER.verifySignedCertificateTimestamps(chain, tlsExtension, null); assertEquals(0, results.getValidSCTs().size()); assertEquals(1, results.getInvalidSCTs().size()); assertEquals(SCTVerificationResult.Status.INVALID_SIGNATURE, results.getInvalidSCTs().get(0).status); }
Source:
public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } final ListResponseModel lObj = (ListResponseModel) obj; if (delegate.equals(lObj.delegate)) { return delegate.equals(lObj.delegate); } return false; }

Target:
public boolean equals(Object obj) { return this.delegate.equals(obj); }
Source:
public Set<String> call() throws NoWorkTreeException, GitAPIException { Set<String> files = new TreeSet<>(); try { StatusCommand command = new StatusCommand(repo); Status status = command.call(); Set<String> untrackedFiles = new TreeSet<>( status.getUntracked()); Set<String> untrackedDirs = new TreeSet<>( status.getUntrackedFolders()); FS fs = getRepository().getFS(); for (String p : status.getIgnoredNotInIndex()) { File f = new File(repo.getWorkTree(), p); if (fs.isFile(f) || fs.isSymLink(f)) untrackedFiles.add(p); else if (fs.isDirectory(f)) { untrackedDirs.add(p); } } Set<String> filtered = filterFolders(untrackedFiles, untrackedDirs); Set<String> notIgnoredFiles = filterIgnorePaths(filtered, status.getIgnoredNotInIndex(), true); Set<String> notIgnoredDirs = filterIgnorePaths( untrackedDirs, status.getIgnoredNotInIndex(), false); for (String file : notIgnoredFiles) if (paths.isEmpty() || paths.contains(file)) { files = cleanPath(file, files); } for (String dir : notIgnoredDirs) if (paths.isEmpty() || paths.contains(dir)) { files = cleanPath(dir, files); } } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } finally { if (!files.isEmpty()) { repo.fireEvent(new WorkingTreeModifiedEvent(null, files)); } } return files; }

Target:
public Set<String> call() throws NoWorkTreeException, GitAPIException { Set<String> files = new TreeSet<>(); try { StatusCommand command = new StatusCommand(repo); Status status = command.call(); Set<String> untrackedFiles = new TreeSet<>(status.getUntracked()); Set<String> untrackedDirs = new TreeSet<>( status.getUntrackedFolders()); FS fs = getRepository().getFS(); for (String p : status.getIgnoredNotInIndex()) { File f = new File(repo.getWorkTree(), p); if (fs.isFile(f) || fs.isSymLink(f)) { untrackedFiles.add(p); } else if (fs.isDirectory(f)) { untrackedDirs.add(p); } } Set<String> filtered = filterFolders(untrackedFiles, untrackedDirs); Set<String> notIgnoredFiles = filterIgnorePaths(filtered, status.getIgnoredNotInIndex(), true); Set<String> notIgnoredDirs = filterIgnorePaths(untrackedDirs, status.getIgnoredNotInIndex(), false); for (String file : notIgnoredFiles) if (paths.isEmpty() || paths.contains(file)) { files = cleanPath(file, files); } for (String dir : notIgnoredDirs) if (paths.isEmpty() || paths.contains(dir)) { files = cleanPath(dir, files); } } catch (IOException e) { throw new JGitInternalException(e.getMessage(), e); } finally { if (!files.isEmpty()) { repo.fireEvent(new WorkingTreeModifiedEvent(null, files)); } } return files; }
Source:
public void throwsAnExceptionWhenEnvironmentNotFound() { String uuid = "A Consumer"; EnvironmentDTO changedEnvironment = new EnvironmentDTO(); changedEnvironment.setId("42"); changedEnvironment.setName("environment"); ConsumerDTO updated = new ConsumerDTO(); updated.setUuid(uuid); updated.setEnvironment(changedEnvironment); Consumer existing = getFakeConsumer(); existing.setUuid(updated.getUuid()); when(consumerCurator.verifyAndLookupConsumer( existing.getUuid())).thenReturn(existing); when(environmentCurator.find(changedEnvironment.getId())).thenReturn(null); resource.updateConsumer(existing.getUuid(), updated, principal); }

Target:
public void throwsAnExceptionWhenEnvironmentNotFound() { String uuid = "A Consumer"; EnvironmentDTO changedEnvironment = new EnvironmentDTO() .setId("42") .setName("environment"); ConsumerDTO updated = new ConsumerDTO(); updated.setUuid(uuid); updated.setEnvironment(changedEnvironment); Consumer existing = getFakeConsumer(); existing.setUuid(updated.getUuid()); when(consumerCurator.verifyAndLookupConsumer(existing.getUuid())).thenReturn(existing); when(environmentCurator.find(changedEnvironment.getId())).thenReturn(null); resource.updateConsumer(existing.getUuid(), updated, principal); }
Source:
private ConstraintValidator<A, ?> getInitializedConstraintValidator(ValidationContext<?> validationContext) { ConstraintValidator<A, ?> validator = validationContext.getConstraintValidatorManager().getInitializedValidator( validatedValueType, descriptor, validationContext.getConstraintValidatorFactory(), HibernateConstraintValidatorInitializationContextImpl.from( validationContext ) ); if ( validator != null ) { return validator; } else { return (ConstraintValidator<A, ?>) DUMMY_CONSTRAINT_VALIDATOR; } }

Target:
private ConstraintValidator<A, ?> getInitializedConstraintValidator(ValidationContext<?> validationContext) { ConstraintValidator<A, ?> validator = validationContext.getConstraintValidatorManager().getInitializedValidator( validatedValueType, descriptor, validationContext.getConstraintValidatorFactory(), validationContext.getConstraintValidatorInitializationContext() ); if ( validator != null ) { return validator; } else { return (ConstraintValidator<A, ?>) DUMMY_CONSTRAINT_VALIDATOR; } }
Source:
Set<String> getFileNames() { readLock.lock(); try { return filenames; } finally { readLock.unlock(); } }

Target:
Set<String> getFileNames() { readLock.lock(); try { return new HashSet<>(filenames); } finally { readLock.unlock(); } }
Source:
public static JSONArray jsonForCodes(List<? extends Barcode> codes, BarcodePicker picker) { JSONArray array = new JSONArray(); for (Barcode code : codes) { JSONObject object = new JSONObject(); try { object.put("symbology", code.getSymbologyName()); object.put("gs1DataCarrier", code.isGs1DataCarrier()); object.put("recognized", code.isRecognized()); object.put("data", code.getData()); object.put("location", jsonForQuadrilateral(code.getLocation())); object.put("compositeFlag", code.getCompositeFlag()); if (code instanceof TrackedBarcode) { object.put("uniqueId", ((TrackedBarcode) code).getId()); object.put("predictedLocation", jsonForQuadrilateral(((TrackedBarcode) code).getPredictedLocation())); object.put("convertedLocation", jsonForQuadrilateral(convertQuadrilateral(picker, code.getLocation()))); object.put("convertedPredictedLocation", jsonForQuadrilateral(convertQuadrilateral(picker, ((TrackedBarcode) code).getPredictedLocation()))); } else { object.put("uniqueId", code.getHandle()); } if (code.isRecognized()) { JSONArray bytes = new JSONArray(); byte[] rawData = code.getRawData(); for (byte theByte : rawData) { bytes.put((int) theByte); } object.put("rawData", bytes); } array.put(object); } catch (JSONException e) { e.printStackTrace(); } } return array; }

Target:
public static JSONArray jsonForCodes(List<? extends Barcode> codes, BarcodePicker picker) { JSONArray array = new JSONArray(); for (Barcode code : codes) { JSONObject object = new JSONObject(); try { object.put("symbology", code.getSymbologyName()); object.put("gs1DataCarrier", code.isGs1DataCarrier()); object.put("recognized", code.isRecognized()); object.put("data", code.getData()); object.put("location", jsonForQuadrilateral(code.getLocation())); object.put("convertedLocation", jsonForQuadrilateral(convertQuadrilateral(picker, code.getLocation()))); object.put("compositeFlag", code.getCompositeFlag()); if (code instanceof TrackedBarcode) { object.put("uniqueId", ((TrackedBarcode) code).getId()); object.put("predictedLocation", jsonForQuadrilateral(((TrackedBarcode) code).getPredictedLocation())); object.put("convertedPredictedLocation", jsonForQuadrilateral(convertQuadrilateral(picker, ((TrackedBarcode) code).getPredictedLocation()))); } else { object.put("uniqueId", code.getHandle()); } if (code.isRecognized()) { JSONArray bytes = new JSONArray(); byte[] rawData = code.getRawData(); for (byte theByte : rawData) { bytes.put((int) theByte); } object.put("rawData", bytes); } array.put(object); } catch (JSONException e) { e.printStackTrace(); } } return array; }