auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private org.apache.synapse.MessageContext createMessageContext() { org.apache.synapse.MessageContext messageContext = synapseEnvironment.createMessageContext(); MessageContext axis2MsgCtx = ((org.apache.synapse.core.axis2.Axis2MessageContext) messageContext).getAxis2MessageContext(); axis2MsgCtx.setServerSide(true); axis2MsgCtx.setMessageID(UUIDGenerator.getUUID()); messageContext.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, true); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); axis2MsgCtx.setProperty(MultitenantConstants.TENANT_DOMAIN, carbonContext.getTenantDomain()); return messageContext; }

Target:
private MessageContext createMessageContext() { org.apache.synapse.MessageContext messageContext = synapseEnvironment.createMessageContext(); MessageContext axis2MsgCtx = ((Axis2MessageContext) messageContext).getAxis2MessageContext(); axis2MsgCtx.setServerSide(true); axis2MsgCtx.setMessageID(UUIDGenerator.getUUID()); messageContext.setProperty(MessageContext.CLIENT_API_NON_BLOCKING, true); PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext(); axis2MsgCtx.setProperty(MultitenantConstants.TENANT_DOMAIN, carbonContext.getTenantDomain()); return (MessageContext) messageContext; }
Source:
public void run() { if (shutdown) { return; } try { initialize(); log.info("Initialization complete. Scheduling periodicShardSync.."); periodicShardSyncManager.start(); log.info("Scheduled periodicShardSync tasks. Starting worker loop."); } catch (RuntimeException e) { log.error("Unable to initialize after attempts. Shutting down.", maxInitializationAttempts, e); workerStateChangeListener.onAllInitializationAttemptsFailed(e); shutdown(); } while (!shouldShutdown()) { runProcessLoop(); } finalShutdown(); log.info("Worker loop is complete. Exiting from worker."); }

Target:
public void run() { if (shutdown) { return; } try { initialize(); log.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e) { log.error("Unable to initialize after attempts. Shutting down.", maxInitializationAttempts, e); workerStateChangeListener.onAllInitializationAttemptsFailed(e); shutdown(); } while (!shouldShutdown()) { runProcessLoop(); } finalShutdown(); log.info("Worker loop is complete. Exiting from worker."); }
Source:
protected void addExtensionRecord(Term rowType, Map<Term, String> row, boolean detatched) throws IOException { if (!terms.containsKey(rowType)) { addRowType(rowType, detatched); } List<Term> knownTerms = terms.get(rowType); final boolean isFirst = knownTerms.isEmpty(); for (Term term : row.keySet()) { if (!knownTerms.contains(term)) { if (useHeaders && !isFirst){ throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); } knownTerms.add(term); } } writeRow(row, rowType, detatched); }

Target:
protected void addExtensionRecord(Term rowType, Map<Term, String> row, boolean detatched) throws IOException { if (!terms.containsKey(rowType)) { addRowType(rowType, detatched); } List<Term> knownTerms = terms.get(rowType); final boolean isFirst = knownTerms.isEmpty(); for (Term term : row.keySet()) { if (!knownTerms.contains(term)) { if (!isFirst){ throw new IllegalStateException("You cannot add new terms after the first row when headers are enabled"); } knownTerms.add(term); } } writeRow(row, rowType, detatched); }
Source:
public void setZoomPercentage_cropWidthChangedLinearly() throws InterruptedException { Rect prevCropRegion = getSensorRect(); float prevWidthDelta = 0; for (float percentage = 0.1f; percentage < 1.0f; percentage += 0.1f) { mZoomControl.setZoomPercentage(percentage); HandlerUtil.waitForLooperToIdle(mHandler); Rect cropRegion = getSessionCropRegion(mControlUpdateListener); if (prevWidthDelta == 0) { prevWidthDelta = prevCropRegion.width() - cropRegion.width(); } else { float widthDelta = prevCropRegion.width() - cropRegion.width(); Assert.assertEquals(prevWidthDelta, widthDelta, 10); } prevCropRegion = cropRegion; } }

Target:
public void setZoomPercentage_cropWidthChangedLinearly() throws InterruptedException { Rect prevCropRegion = getSensorRect(); float prevWidthDelta = 0; for (float percentage = 0.1f; percentage < 1.0f; percentage += 0.1f) { mZoomControl.setZoomPercentage(percentage); HandlerUtil.waitForLooperToIdle(mHandler); Rect cropRegion = getSessionCropRegion(mControlUpdateListener); if (prevWidthDelta == 0) { prevWidthDelta = prevCropRegion.width() - cropRegion.width(); } else { float widthDelta = prevCropRegion.width() - cropRegion.width(); Assert.assertEquals(prevWidthDelta, widthDelta, TOLERANCE); } prevCropRegion = cropRegion; } }
Source:
public Object evaluate(DeferredObject[] arguments) throws HiveException { ret.clear(); UserAgent browser = null; Device device = null; OS os = null; try { if (arguments.length > 0 && argumentOIs.length > 0 && argumentOIs[0] != null && arguments[0] != null) { Client c; String pattern = ((StringObjectInspector) argumentOIs[0]) .getPrimitiveJavaObject(arguments[0].get()); c = p.parse(pattern); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } } catch (Exception e) { e.printStackTrace(); } if (browser != null) { ret.put("browser_family", replaceNA(browser.family)); ret.put("browser_major", replaceNA(browser.major)); } else { ret.put("browser_family", NA); ret.put("browser_major", NA); } if (device != null) { ret.put("device_family", replaceNA(device.family)); } else { ret.put("device_family", NA); } if (os != null) { ret.put("os_family", replaceNA(os.family)); ret.put("os_major", replaceNA(os.major)); ret.put("os_minor", replaceNA(os.minor)); } else { ret.put("os_family", NA); ret.put("os_major", NA); ret.put("os_minor", NA); } return ret; }

Target:
public Object evaluate(DeferredObject[] arguments) throws HiveException { result.clear(); UserAgent browser = null; Device device = null; OS os = null; try { if (arguments.length > 0 && argumentOIs.length > 0 && argumentOIs[0] != null && arguments[0] != null) { Client c; String pattern = ((StringObjectInspector) argumentOIs[0]) .getPrimitiveJavaObject(arguments[0].get()); c = p.parse(pattern); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } } catch (Exception e) { e.printStackTrace(); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } return result; }
Source:
protected Boolean _hasPermission(@Nonnull Authentication a, Permission permission) { PrincipalSid principalSid; try { principalSid = principalSidCache.get(a, () -> {return new PrincipalSid(a);}); } catch (ExecutionException e) { LOGGER.log(WARNING, "Failed to populate Principal Sid Cache", e); principalSid = new PrincipalSid(a); } Boolean b = hasPermission(principalSid, permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission(PrincipalSID:"+a.getPrincipal()+","+permission+")=>"+b); if(b!=null) return b; for(GrantedAuthority ga : a.getAuthorities()) { b = hasPermission(new GrantedAuthoritySid(ga),permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission(GroupSID:"+ga.getAuthority()+","+permission+")=>"+b); if(b!=null) return b; } for (Sid sid : AUTOMATIC_SIDS) { b = hasPermission(sid,permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission("+sid+","+permission+")=>"+b); if(b!=null) return b; } return null; }

Target:
protected Boolean _hasPermission(@Nonnull Authentication a, Permission permission) { PrincipalSid principalSid = principalSidCache.get(a); if (principalSid == null) { principalSid = new PrincipalSid(a); principalSidCache.put(a, principalSid); } Boolean b = hasPermission(principalSid, permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission(PrincipalSID:"+a.getPrincipal()+","+permission+")=>"+b); if(b!=null) return b; for(GrantedAuthority ga : a.getAuthorities()) { b = hasPermission(new GrantedAuthoritySid(ga),permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission(GroupSID:"+ga.getAuthority()+","+permission+")=>"+b); if(b!=null) return b; } for (Sid sid : AUTOMATIC_SIDS) { b = hasPermission(sid,permission); if(LOGGER.isLoggable(FINER)) LOGGER.finer("hasPermission("+sid+","+permission+")=>"+b); if(b!=null) return b; } return null; }
Source:
public void createRequest(@NonNull final de.metas.adempiere.model.I_C_Order order) { if (order.getC_DocTypeTarget_ID() == X_C_DocType.DOCTYPE_TEST_APPLIANCE) { R_Request_CreateFromOrder_Async.createWorkpackage(order.getC_Order_ID()); } }

Target:
public void createRequest(@NonNull final de.metas.adempiere.model.I_C_Order order) { final Optional<RequestTypeId> requestType = orderBL.getRequestTypeForCreatingNewRequestsAfterComplete(order); if (requestType.isPresent()) { R_Request_CreateFromOrder_Async.createWorkpackage(order); } }
Source:
public Optional<KeyBinding> mapToKeyBinding(KeyEvent keyEvent) { for (KeyBinding binding : KeyBinding.values()) { if (!binding.getDefaultKeyBinding().isEmpty()){ if (checkKeyCombinationEquality(binding, keyEvent)) { return Optional.of(binding); } } } return Optional.empty(); }

Target:
public Optional<KeyBinding> mapToKeyBinding(KeyEvent keyEvent) { for (KeyBinding binding : KeyBinding.values()) { if (checkKeyCombinationEquality(binding, keyEvent)) { return Optional.of(binding); } } return Optional.empty(); }
Source:
public void before() { indexOperations = operations.indexOps(SampleEntity.class); deleteIndices(); indexOperations.create(); indexOperations.putMapping(SampleEntity.class); IndexOperations indexOpsSampleEntityUUIDKeyed = operations.indexOps(SampleEntityUUIDKeyed.class); indexOpsSampleEntityUUIDKeyed.create(); indexOpsSampleEntityUUIDKeyed.putMapping(SampleEntityUUIDKeyed.class); IndexOperations indexOpsSearchHitsEntity = operations.indexOps(SearchHitsEntity.class); indexOpsSearchHitsEntity.create(); indexOpsSearchHitsEntity.putMapping(SearchHitsEntity.class); if (this instanceof ElasticsearchRestTemplateTests) { IndexOperations indexOpsJoinEntity = operations.indexOps(ElasticsearchRestTemplateTests.SampleJoinEntity.class); indexOpsJoinEntity.create(); indexOpsJoinEntity.putMapping(ElasticsearchRestTemplateTests.SampleJoinEntity.class); } }

Target:
public void before() { indexOperations = operations.indexOps(SampleEntity.class); deleteIndices(); indexOperations.create(); indexOperations.putMapping(SampleEntity.class); IndexOperations indexOpsSampleEntityUUIDKeyed = operations.indexOps(SampleEntityUUIDKeyed.class); indexOpsSampleEntityUUIDKeyed.create(); indexOpsSampleEntityUUIDKeyed.putMapping(SampleEntityUUIDKeyed.class); IndexOperations indexOpsSearchHitsEntity = operations.indexOps(SearchHitsEntity.class); indexOpsSearchHitsEntity.create(); indexOpsSearchHitsEntity.putMapping(SearchHitsEntity.class); IndexOperations indexOpsJoinEntity = operations.indexOps(ElasticsearchRestTemplateTests.SampleJoinEntity.class); indexOpsJoinEntity.create(); indexOpsJoinEntity.putMapping(ElasticsearchRestTemplateTests.SampleJoinEntity.class); }
Source:
private void calculateUsage() { try { List<String> usernames = core.getUsernames("").get() .stream() .filter(usage::containsKey) .collect(Collectors.toList()); for (String username : usernames) { Optional<PublicKeyHash> publicKeyHash = core.getPublicKeyHash(username).get(); publicKeyHash.ifPresent(keyHash -> processCorenodeEvent(username, keyHash)); } } catch (Exception e) { e.printStackTrace(); } }

Target:
public void calculateUsage() { try { List<String> usernames = core.getUsernames("") .get() .stream() .filter(e -> !state.usage.containsKey(e)) .collect(Collectors.toList()); long t1 = System.currentTimeMillis(); for (String username : usernames) { System.out.printf("Processing %s\n", username); Optional<PublicKeyHash> publicKeyHash = core.getPublicKeyHash(username).get(); publicKeyHash.ifPresent(keyHash -> processCorenodeEvent(username, keyHash)); } long t2 = System.currentTimeMillis(); System.out.println(LocalDateTime.now() + " Finished loading space usage for all usernames in " + (t2 - t1)/1000 + " s"); } catch (Exception e) { LOG.log(Level.WARNING, e.getMessage(), e); } }
Source:
public ConnectDocumentToLanguageServerSetupParticipant() { ITextFileBufferManager.DEFAULT.addFileBufferListener(new FileBufferListenerAdapter() { @Override public void bufferDisposed(IFileBuffer buffer) { Job job = locationMap.get(buffer.getLocation()); if (job != null) { job.cancel(); } locationMap.remove(buffer.getLocation()); } }); }

Target:
public ConnectDocumentToLanguageServerSetupParticipant() { ITextFileBufferManager.DEFAULT.addFileBufferListener(new FileBufferListenerAdapter() { @Override public void bufferDisposed(IFileBuffer buffer) { Job job = locationMap.remove(buffer.getLocation()); if (job != null) { job.cancel(); } } }); }
Source:
public void testSuccess() { Mockito.when(schemaService.getSchemas("et_test_name", 0, 1)).thenReturn(Result.ok(null)); final ResponseEntity<?> result = new SchemaController(schemaService, eventTypeService) .getSchemas("et_test_name", 0, 1, nativeWebRequest); Assert.assertEquals(HttpStatus.OK, result.getStatusCode()); }

Target:
public void testSuccess() { Mockito.when(schemaService.getSchemas("et_test", 0, 1)).thenReturn(Result.ok(null)); Mockito.when(eventTypeService.get("et_test")).thenReturn(Result.ok(EventTypeTestBuilder.builder().build())); final ResponseEntity<?> result = new SchemaController(schemaService, eventTypeService) .getSchemas("et_test", 0, 1, nativeWebRequest); Assert.assertEquals(HttpStatus.OK, result.getStatusCode()); }
Source:
private static DelegateRelationship buildApiParentRelationship(File apiLibDirectory, ClassLoader apiClassLoader) { DelegateRelationshipBuilder apiParentRelationshipBuilder = DelegateRelationshipBuilder.builder() .withDelegateClassLoader(apiClassLoader) .withIsolationLevel(IsolationLevel.FULL); apiParentRelationshipBuilder.addDelegatePreferredClassPredicate(new BootstrapClassPredicate()); getApiClasses(apiLibDirectory).forEach( apiClassName -> apiParentRelationshipBuilder.addDelegatePreferredClassPredicate(new GlobMatcher(apiClassName))); return apiParentRelationshipBuilder.build(); }

Target:
private static DelegateRelationship buildApiParentRelationship(File apiLibDirectory, ClassLoader apiClassLoader) { DelegateRelationshipBuilder apiParentRelationshipBuilder = DelegateRelationshipBuilder.builder() .withDelegateClassLoader(apiClassLoader) .withIsolationLevel(IsolationLevel.FULL); apiParentRelationshipBuilder.addDelegatePreferredClassPredicate(new BootstrapClassPredicate()); getFrameworkApiClassGlobs(apiLibDirectory).forEach( apiClassName -> apiParentRelationshipBuilder.addDelegatePreferredClassPredicate(new GlobMatcher(apiClassName))); return apiParentRelationshipBuilder.build(); }
Source:
public boolean addStateTransition(final ActivationState from, final EventType event, final ActivationState to) { Objects.requireNonNull(from, "From state cannot be null!"); Objects.requireNonNull(event, "Event cannot be null!"); Objects.requireNonNull(to, "To state cannot be null!"); Transition transition = new Transition(from, event, to); return addStateTransition(transition); }

Target:
public boolean addStateTransition(final ActivationState from, final EventType event, final ActivationState to) { return addStateTransition(new Transition(from, event, to)); }
Source:
private AsyncScheduler() { super(ScheduledTask.TaskSynchroncity.ASYNCHRONOUS); Thread thread = new Thread(new Runnable() { @Override public void run() { mainLoop(); } }); thread.setName("Sponge Async Scheduler Thread"); thread.setDaemon(true); thread.start(); }

Target:
AsyncScheduler() { super(ScheduledTask.TaskSynchronicity.ASYNCHRONOUS); Thread thread = new Thread(new Runnable() { @Override public void run() { mainLoop(); } }); thread.setName("Sponge Async Scheduler Thread"); thread.setDaemon(true); thread.start(); }
Source:
public AddElementComponent(final EditionWindow parent, Controller controller, Skin skin) { super(parent, controller, skin); this.eraser = new EraserComponent(parent, controller, skin); this.paint = new PaintComponent(parent, controller, skin); createTopToolbar(parent, controller); Button draw = new TextButton( this.i18n.m("edition.tool.add-paint-element"), skin); this.add(draw).fillX().expandX(); this.row(); this.add( new TextButton(this.i18n.m("edition.tool.add-recent-element"), skin)).fillX().expandX(); this.row(); this.add( new TextButton(this.i18n.m("edition.tool.add-photo-element"), skin)).fillX().expandX(); this.row(); final Button addFromGalleryButton = new TextButton( this.i18n.m("edition.tool.add-gallery-element"), skin); addFromGalleryButton.addListener(new ActionOnDownListener(controller, AddSceneElementFromResource.class)); this.add(addFromGalleryButton).fillX().expandX(); draw.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { if (!AddElementComponent.this.topToolbar.isVisible()) { AddElementComponent.this.hide(); AddElementComponent.this.topToolbar.setVisible(true); AddElementComponent.this.painting.setVisible(true); parent.getTop().setVisible(false); } else { parent.getTop().setVisible(true); AddElementComponent.this.painting.setVisible(false); AddElementComponent.this.painting.flush(); } } }); }

Target:
public AddElementComponent(final EditionWindow parent, Controller controller, Skin skin) { super(parent, controller, skin); this.eraser = new EraserComponent(parent, controller, skin); this.paint = new PaintComponent(parent, controller, skin); createTopToolbar(parent, controller); Button draw = new TextButton( this.i18n.m("edition.tool.add-paint-element"), skin); this.add(draw).fillX().expandX(); this.row(); this.add( new TextButton(this.i18n.m("edition.tool.add-recent-element"), skin)).fillX().expandX(); this.row(); this.add( new TextButton(this.i18n.m("edition.tool.add-photo-element"), skin)).fillX().expandX(); this.row(); final Button addFromGalleryButton = new TextButton( this.i18n.m("edition.tool.add-gallery-element"), skin); addFromGalleryButton.addListener(new ActionOnDownListener(controller, AddSceneElementFromResource.class)); this.add(addFromGalleryButton).fillX().expandX(); draw.addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { if (!topToolbar.isVisible()) { hide(); topToolbar.setVisible(true); brushStrokes.setVisible(true); parent.getTop().setVisible(false); } else { parent.getTop().setVisible(true); brushStrokes.setVisible(false); brushStrokes.release(); brushStrokes.clearMesh(); } } }); }
Source:
private void initMetricCollector() { try { Path dbDumpPath = currentDatabaseIterator.dbLevelPath(); FileSystem fs = dbDumpPath.getFileSystem(hiveConf); long numTables = getNumTables(dbDumpPath, fs); long numFunctions = getNumFunctions(dbDumpPath, fs); Map<String, Long> metricMap = new HashMap<>(); metricMap.put(ReplUtils.MetricName.TABLES.name(), (long) numTables); metricMap.put(ReplUtils.MetricName.FUNCTIONS.name(), (long) numFunctions); metricCollector.reportStageStart("REPL_LOAD", metricMap); } catch (IOException e) { } catch (SemanticException e) { throw new RuntimeException("Failed to collect Metrics ", e); } }

Target:
private void initMetricCollector() { try { Path dbDumpPath = currentDatabaseIterator.dbLevelPath(); FileSystem fs = dbDumpPath.getFileSystem(hiveConf); long numTables = getNumTables(dbDumpPath, fs); long numFunctions = getNumFunctions(dbDumpPath, fs); Map<String, Long> metricMap = new HashMap<>(); metricMap.put(ReplUtils.MetricName.TABLES.name(), numTables); metricMap.put(ReplUtils.MetricName.FUNCTIONS.name(), numFunctions); metricCollector.reportStageStart("REPL_LOAD", metricMap); } catch (Exception e) { throw new RuntimeException("Failed to collect Metrics ", e); } }
Source:
private List<KfsToPMWSupplierDiversityDTO> buildPmwToKfsSupplierDiversityList(String sqlToRun) { List<KfsToPMWSupplierDiversityDTO> supplierList = new ArrayList<KfsToPMWSupplierDiversityDTO>(); List<PaymentWorksSupplierDiversityMapDatabaseRow> pmwToKfsDiversityDatabaseRows = findActiveSupplierDiversitiesForMap(sqlToRun); if (ObjectUtils.isNotNull(pmwToKfsDiversityDatabaseRows) && !pmwToKfsDiversityDatabaseRows.isEmpty()) { for (PaymentWorksSupplierDiversityMapDatabaseRow row : pmwToKfsDiversityDatabaseRows) { supplierList.add(new KfsToPMWSupplierDiversityDTO(row.getKfsSupplierDiversityCode(), row.getKfsSupplierDiversityDescription(), row.getPmwSupplierDiversityDescription())); } for (KfsToPMWSupplierDiversityDTO dto : supplierList) { LOG.info("buildPmwToKfsSupplierDiversityList, KfsToPMWSupplierDiversityDTO: " + dto.toString()); } } return supplierList; }

Target:
private List<KfsToPMWSupplierDiversityDTO> buildPmwToKfsSupplierDiversityList(String sqlToRun) { List<KfsToPMWSupplierDiversityDTO> supplierList = new ArrayList<KfsToPMWSupplierDiversityDTO>(); List<PaymentWorksSupplierDiversityMapDatabaseRow> pmwToKfsDiversityDatabaseRows = findActiveSupplierDiversitiesList(sqlToRun); if (ObjectUtils.isNotNull(pmwToKfsDiversityDatabaseRows) && !pmwToKfsDiversityDatabaseRows.isEmpty()) { for (PaymentWorksSupplierDiversityMapDatabaseRow row : pmwToKfsDiversityDatabaseRows) { supplierList.add(new KfsToPMWSupplierDiversityDTO(row.getKfsSupplierDiversityCode(), row.getKfsSupplierDiversityDescription(), row.getPmwSupplierDiversityDescription())); } if (LOG.isDebugEnabled()) { for (KfsToPMWSupplierDiversityDTO dto : supplierList) { LOG.debug("buildPmwToKfsSupplierDiversityList, KfsToPMWSupplierDiversityDTO: " + dto.toString()); } } } return supplierList; }
Source:
public Response updateAsset(@PathParam(CuCamsConstants.CapAssetApi.CAPITAL_ASSET_NUMBER) String capitalAssetNumber, @Context HttpHeaders headers) { try { if (!validateUpdateAssetQueryParameters()) { LOG.warn("Bad Request for Asset Inventory #" + capitalAssetNumber + " " + servletRequest.getQueryString()); return respondBadRequest(); } LOG.info("Requesting Capital Asset Inventory #" + capitalAssetNumber + " " + servletRequest.getQueryString()); String conditionCode = servletRequest.getParameter(CuCamsConstants.CapAssetApi.CONDITION_CODE); String buildingCode = servletRequest.getParameter(CuCamsConstants.CapAssetApi.BUILDING_CODE); String roomNumber = servletRequest.getParameter(CuCamsConstants.CapAssetApi.ROOM_NUMBER); Asset asset = getCuAssetService().updateAssetInventory(capitalAssetNumber, conditionCode, buildingCode, roomNumber); LOG.info("Updated Capital Asset Inventory #" + capitalAssetNumber + " " + asset.getLastInventoryDate().toString()); Properties properties = getAssetProperties(asset); return Response.ok(gson.toJson(properties)).build(); } catch (Exception ex) { LOG.error("updateAsset", ex); return ex instanceof BadRequestException ? respondBadRequest() : respondInternalServerError(ex); } }

Target:
public Response updateAsset(@PathParam(CuCamsConstants.CapAssetApi.CAPITAL_ASSET_NUMBER) String capitalAssetNumber, @Context HttpHeaders headers) { try { if (!validateUpdateAssetQueryParameters()) { LOG.error("updateAsset: Bad Request for Asset Inventory #" + capitalAssetNumber + " " + servletRequest.getQueryString()); return respondBadRequest(); } LOG.info("updateAsset: Requesting Capital Asset Inventory #" + capitalAssetNumber + " " + servletRequest.getQueryString()); String conditionCode = servletRequest.getParameter(CuCamsConstants.CapAssetApi.CONDITION_CODE); String buildingCode = servletRequest.getParameter(CuCamsConstants.CapAssetApi.BUILDING_CODE); String roomNumber = servletRequest.getParameter(CuCamsConstants.CapAssetApi.ROOM_NUMBER); Asset asset = getCuAssetService().updateAssetInventory(capitalAssetNumber, conditionCode, buildingCode, roomNumber); if (ObjectUtils.isNull(asset)) { LOG.error("updateAsset: Asset Inventory #" + capitalAssetNumber + " Not Found"); return respondNotFound(); } LOG.info("updateAsset: Updated Capital Asset Inventory #" + capitalAssetNumber + " " + asset.getLastInventoryDate().toString()); Properties properties = getAssetProperties(asset); return Response.ok(gson.toJson(properties)).build(); } catch (Exception ex) { LOG.error("updateAsset", ex); return ex instanceof BadRequestException ? respondBadRequest() : respondInternalServerError(ex); } }
Source:
private String resolveStackPointerName() throws Throwable { get_X86_REGS(); String sp_name = "rsp"; if (fRegisterNames.contains(sp_name)) { return sp_name; } sp_name = "esp"; if (fRegisterNames.contains(sp_name)) { return sp_name; } sp_name = "sp"; if (fRegisterNames.contains(sp_name)) { return sp_name; } return null; }

Target:
private String resolveStackPointerName() throws Throwable { List<String> regNames = get_X86_REGS(); String sp_name = "rsp"; if (regNames.contains(sp_name)) { return sp_name; } sp_name = "esp"; if (regNames.contains(sp_name)) { return sp_name; } sp_name = "sp"; if (regNames.contains(sp_name)) { return sp_name; } return null; }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode<?>> nodes = getSelectedNodes(); Set<WorkingDirNode> nodesToCollapse = nodes.stream() .map(n -> getWorkingDirParent(n)).filter(n -> n != null) .collect(Collectors.toSet()); if (!nodesToCollapse.isEmpty()) { CommonViewer viewer = getView(event).getCommonViewer(); for (WorkingDirNode node : nodesToCollapse) { viewer.collapseToLevel(node, AbstractTreeViewer.ALL_LEVELS); } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode<?>> nodes = getSelectedNodes(); Set<WorkingDirNode> nodesToCollapse = nodes.stream() .map(this::getWorkingDirParent).filter(Objects::nonNull) .collect(Collectors.toSet()); if (!nodesToCollapse.isEmpty()) { CommonViewer viewer = getView(event).getCommonViewer(); for (WorkingDirNode node : nodesToCollapse) { viewer.collapseToLevel(node, AbstractTreeViewer.ALL_LEVELS); } } return null; }
Source:
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteDatasetCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("logging-config", new LoggingConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }

Target:
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteDatasetCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("log4j-config", new Log4jConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }
Source:
protected void deserializeBody(InputStream inputStream) throws IOException, MessageFormatException { getBlobOperation.setBlobOutput(MessageFormatRecord.deserializeBlob(inputStream).getBlobOutput()); }

Target:
protected void deserializeBody(InputStream inputStream) throws IOException, MessageFormatException { BlobData blobData = MessageFormatRecord.deserializeBlob(inputStream); getBlobOperation.setBlobOutput(new BlobOutput(blobData.getSize(), blobData.getStream())); }
Source:
public ListenableFuture<SubmissionResult> submit(Path path, ProgressObserver observer) throws TmcCoreException { UrlCommunicator communicator = new UrlCommunicator(settings); TmcApi tmcApi = new TmcApi(communicator, settings); ExerciseSubmitter exerciseSubmitter = new ExerciseSubmitter( new ProjectRootFinder(tmcApi), new StudentFileAwareZipper(new EverythingIsStudentFileStudentFilePolicy()), communicator, tmcApi, settings); Submit submit = new Submit( settings, exerciseSubmitter, new SubmissionPoller(tmcApi), path.toString(), observer); return threadPool.submit(submit); }

Target:
public ListenableFuture<SubmissionResult> submit(Path path, ProgressObserver observer) throws TmcCoreException { UrlCommunicator communicator = new UrlCommunicator(settings); TmcApi tmcApi = new TmcApi(communicator, settings); ExerciseSubmitter exerciseSubmitter = new ExerciseSubmitter( new ProjectRootFinder(tmcApi), new TaskExecutorImpl(), communicator, tmcApi, settings); Submit submit = new Submit( settings, exerciseSubmitter, new SubmissionPoller(tmcApi), path.toString(), observer); return threadPool.submit(submit); }
Source:
@Override public void updateCounter(long val) { try { pCntr.update(val); } catch (IgniteCheckedException e) { U.error(log, "Partition counter inconsistency is detected and new counter value will be ignored. " + "Most probably a node with most actual data is out of topology or data streamer is used in isolated " + "mode (allowOverride=true) concurrently with normal cache operations [rebCntr=" + val + ", locCntr=" + pCntr + ']'); if (failNodeOnPartitionInconsistency) ctx.kernalContext().failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); } }

Target:
@Override public void updateCounter(long val) { try { pCntr.update(val); } catch (IgniteCheckedException e) { U.error(log, "Failed to update partition counter. " + "Most probably a node with most actual data is out of topology or data streamer is used " + "in preload mode (allowOverride=false) concurrently with cache transactions [grpName=" + grp.name() + ", partId=" + partId + ']', e); if (failNodeOnPartitionInconsistency) ctx.kernalContext().failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e)); } }
Source:
protected void refreshViewer(final Object object) { asyncViewerRefresh(new Runnable() { public void run() { synchronized (viewer) { final TreePath[] treePaths = viewer.getExpandedTreePaths(); if (object != null) { viewer.refresh(object); } else { viewer.refresh(); } viewer.setExpandedTreePaths(treePaths); } } }); }

Target:
protected void refreshViewer(final Object object) { asyncViewerRefresh(new Runnable() { public void run() { synchronized (viewer) { if (object != null) { viewer.refresh(object); } else { viewer.refresh(); } } } }); }
Source:
protected void processViewUpdate(Grid grid2) { logger.debug("Player: " + playerNumber + " - UPDATE VIEW EVENT"); if(grid != null){ Point p1 = new Point(0,0); Point p2 = new Point(0,0); Point p1New = new Point(0,0); Point p2New = new Point(0,0); for(int j = 0; j != grid.getSize().height;j++){ for(int i = 0; i != grid.getSize().width; i++){ Point p = new Point(i,j); ArrayList<Entity> old = (ArrayList<Entity>) grid.get(p); ArrayList<Entity> newSquare = (ArrayList<Entity>) grid2.get(p); for(Entity e: old){ if(e.toString().equals("0")){ p1 = new Point(p); } else if(e.toString().equals("1")){ p2 = new Point(p); } } for(Entity e: newSquare){ if(e.toString().equals("0")){ p1New = new Point(p); } else if(e.toString().equals("1")){ p2New = new Point(p); } } } } if(p1 != null && p1New != null && (p1.x != p1New.x || p1.y != p1New.y)){ logger.info("Player 1 has moved from " +p1.x + "," + p1.y + " to " + p1New.x + "," + p1New.y); } if(p2 != null && p2New != null && (p2.x != p2New.x || p2.y != p2New.y)){ logger.info("Player 2 has moved from " +p2.x + "," + p2.y + " to " + p2New.x + "," + p2New.y); } } else{ logger.info("Player " + playerNumber + " first view of the grid"); } this.grid = grid2; }

Target:
protected void processViewUpdate(Grid grid2) { logger.debug("Player: " + playerNumber + " - UPDATE VIEW EVENT"); if(grid != null){ Point p1 = null, p2 = null, p1New = null, p2New = null; for (Point p : grid.keySet()) { ArrayList<Entity> old = (ArrayList<Entity>) grid.get(p); ArrayList<Entity> newSquare = (ArrayList<Entity>) grid2.get(p); for (Entity e : old) { if (e.toString().equals("0")) { p1 = new Point(p); } else if (e.toString().equals("1")) { p2 = new Point(p); } } for (Entity e : newSquare) { if (e.toString().equals("0")) { p1New = new Point(p); } else if (e.toString().equals("1")) { p2New = new Point(p); } } } if(p1 != null && p1New != null && (p1.x != p1New.x || p1.y != p1New.y)){ logger.info("Player 1 has moved from " +p1.x + "," + p1.y + " to " + p1New.x + "," + p1New.y); } if(p2 != null && p2New != null && (p2.x != p2New.x || p2.y != p2New.y)){ logger.info("Player 2 has moved from " +p2.x + "," + p2.y + " to " + p2New.x + "," + p2New.y); } } else{ logger.info("Player " + playerNumber + " first view of the grid"); } this.grid = grid2; }
Source:
protected <X> X verifyEndpointReturningObject(final Function<T, X> methodRunner) { final X result = methodRunner.apply(clientBuilder.apply(localhost)); assertThat(methodRunner.apply(clientBuilder.apply(localhost)), notNullValue()); return result; }

Target:
protected <X> X verifyEndpointReturningObject(final Function<T, X> methodRunner) { final X result = methodRunner.apply(clientBuilder.apply(localhost)); assertThat(result, notNullValue()); return result; }
Source:
private static void fillResponses(Operation swaggerOperation, org.restlet.ext.apispark.internal.model.Operation operation, Contract contract, Map<String, Object> parameters) { if (swaggerOperation == null) { return; } if (swaggerOperation.getResponses() != null) { for (Entry<String, Response> responseEntry : swaggerOperation .getResponses().entrySet()) { String key = responseEntry.getKey(); Response swaggerResponse = responseEntry.getValue(); int statusCode; try { statusCode = Integer.parseInt(key); } catch (NumberFormatException e) { if (!key.equals("default")) { LOGGER.warning(String.format( "Response '%s' for operation '%s' " + "could not be retrieved because its " + "key is not a valid status code.", key, swaggerOperation.getOperationId())); } continue; } fillResponse(statusCode, responseEntry.getValue(), swaggerOperation, operation, contract, parameters); } Response defaultSwaggerResponse = swaggerOperation.getResponses().get( "default"); if (defaultSwaggerResponse != null && operation.getResponse(200) == null) { fillResponse(200, defaultSwaggerResponse, swaggerOperation, operation, contract, parameters); } else if (defaultSwaggerResponse != null) { LOGGER.warning(String.format( "The 'default' response for the operation '%s' was " + "ignored because there is already a response for 200 " + "OK and the Restlet Framework does not support " + "'default' responses for other status codes.", swaggerOperation.getOperationId())); } } }

Target:
private static void fillResponses(Operation swaggerOperation, org.restlet.ext.apispark.internal.model.Operation operation, Contract contract, Map<String, Object> parameters) { if (swaggerOperation == null) { return; } boolean operationHasSpecificSuccessResponse = false; if (swaggerOperation.getResponses() != null) { for (Entry<String, Response> responseEntry : swaggerOperation .getResponses().entrySet()) { String key = responseEntry.getKey(); Response swaggerResponse = responseEntry.getValue(); if ("default".equals(key)) { continue; } int statusCode; try { statusCode = Integer.parseInt(key); } catch (NumberFormatException e) { LOGGER.warning(String.format( "Response '%s' for operation '%s' " + "could not be retrieved because its " + "key is not a valid status code.", key, swaggerOperation.getOperationId())); continue; } if (Status.isSuccess(statusCode)) { operationHasSpecificSuccessResponse = true; } fillResponse(statusCode, swaggerResponse, swaggerOperation, operation, contract, parameters); } Response defaultSwaggerResponse = swaggerOperation.getResponses() .get("default"); if (defaultSwaggerResponse != null && !operationHasSpecificSuccessResponse) { fillResponse(200, defaultSwaggerResponse, swaggerOperation, operation, contract, parameters); } else if (defaultSwaggerResponse != null) { LOGGER.warning(String.format( "The 'default' response for the operation '%s' was " + "ignored because there is already a success response " + "and the Restlet Framework does not support " + "'default' responses for other status codes.", swaggerOperation.getOperationId())); } } }
Source:
public void rightClickAir(GlowPlayer player, ItemStack holding) { if (fastEquip) { equipStack(player, holding); } }

Target:
public void rightClickAir(GlowPlayer player, ItemStack holding) { }
Source:
public List<Pool> listBySourceEntitlements(List<Entitlement> ents) { if (ents.size() == 0) { return new ArrayList<Pool>(); } Iterable<List<Entitlement>> blocks = Iterables.partition(ents, IN_OPERATOR_BLOCK_SIZE); List<Pool> results = new LinkedList<Pool>(); for (List<Entitlement> block : blocks) { results.addAll( createSecureCriteria() .add(CPRestrictions.in("sourceEntitlement", block)) .setFetchMode("entitlements", FetchMode.JOIN) .list()); } if (results.size() > 0) { List<Pool> pools = listBySourceEntitlements(convertPoolsToEntitlements(results)); results.addAll(pools); } return results; }

Target:
public List<Pool> listBySourceEntitlements(List<Entitlement> ents) { if (ents.size() == 0) { return new ArrayList<Pool>(); } Iterable<List<Entitlement>> blocks = Iterables.partition(ents, QUERY_PARAMETER_LIMIT); List<Pool> results = new LinkedList<Pool>(); for (List<Entitlement> block : blocks) { results.addAll( createSecureCriteria() .add(CPRestrictions.in("sourceEntitlement", block)) .setFetchMode("entitlements", FetchMode.JOIN) .list()); } if (results.size() > 0) { List<Pool> pools = listBySourceEntitlements(convertPoolsToEntitlements(results)); results.addAll(pools); } return results; }
Source:
public void addContents(@NonNull Container container) { File[] agentDirs = new File(Helper.getActiveInstance().getRootDir(), "nodes").listFiles(); if (agentDirs == null) { return; } for(File agentDir : agentDirs) { File config = new File(agentDir, "config.xml"); try { File patchedConfig = SecretHandler.findSecrets(config); container.add(new TemporalFileContent("nodes/slave/" + agentDir.getName() + "/config.xml", patchedConfig)); } catch (IOException | ParserConfigurationException | XMLStreamException | SAXException | TransformerException e) { LOGGER.log(Level.WARNING, "could not add the {0} configuration file to the support bundle because of: {1}", new Object[]{ config.getAbsolutePath(), e }); } } }

Target:
public void addContents(@NonNull Container container) { File[] agentDirs = new File(Helper.getActiveInstance().getRootDir(), "nodes").listFiles(); if (agentDirs == null) { return; } for(File agentDir : agentDirs) { File config = new File(agentDir, "config.xml"); try { File patchedConfig = SecretHandler.findSecrets(config); container.add(new TemporaryFileContent("nodes/slave/" + agentDir.getName() + "/config.xml", patchedConfig)); } catch (IOException | SAXException | TransformerException e) { LogRecord record = new LogRecord(Level.WARNING, "Could not add the {0} configuration file to the support bundle because of: {1}"); record.setParameters(new Object[]{ config.getAbsolutePath(), e }); record.setThrown(e); LOGGER.log(record); } } }
Source:
public void start(BundleContext context) throws Exception { super.start(context); new WorkspaceArchivesCore(); ResourcesPlugin.getWorkspace().addResourceChangeListener(new WorkspaceChangeListener()); KeyManager.getInstance(); }

Target:
public void start(BundleContext context) throws Exception { super.start(context); new WorkspaceArchivesCore(); ResourcesPlugin.getWorkspace().addResourceChangeListener(new WorkspaceChangeListener()); Bundle bundle = context.getBundle(); BundleWiring bundleWiring = bundle.adapt(BundleWiring.class); ClassLoader bundleLoader = bundleWiring.getClassLoader(); ClassLoader originalTCCL = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(bundleLoader); KeyManager.getInstance(); } finally { Thread.currentThread().setContextClassLoader(originalTCCL); } }
Source:
public Dialog onCreateDialog(Bundle savedInstance) { if (savedInstance != null) { preSelectedTags = new HashSet<Keyword>(Arrays.asList( (Keyword[]) savedInstance.getParcelableArray("preSelectedTags"))); selectedTags = new HashSet<Keyword>(Arrays.asList( (Keyword[]) savedInstance.getParcelableArray("selectedTags"))); } LayoutInflater inflater = getActivity().getLayoutInflater(); View tagChoiceListView = inflater.inflate(R.layout.tag_choice_list, null); ImageButton buttonTagEditor = (ImageButton) tagChoiceListView.findViewById(R.id.button_keyword_editor); buttonTagEditor.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { listener.onStartKeywordEditor(); dismiss(); } }); tags = Keyword.getVisibleKeywords(); TagListAdapter adapter = new TagListAdapter(getActivity(), tags); ListView listView = (ListView) tagChoiceListView.findViewById( R.id.tag_choice_list_view); listView.setAdapter(adapter); listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick( AdapterView parent, View view, int position, long id) { ListView lv = (ListView) parent; Keyword clickedTag = tags.get(position); if (lv.isItemChecked(position)) { selectedTags.add(clickedTag); } else { selectedTags.remove(clickedTag); } } }); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.tag_choice_dialog_title) .setView(tagChoiceListView) .setPositiveButton( android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Set<Keyword> addedTags = new HashSet<Keyword>(selectedTags); addedTags.removeAll(preSelectedTags); Set<Keyword> deletedTags = new HashSet<Keyword>(preSelectedTags); deletedTags.removeAll(selectedTags); listener.onStoreTags(addedTags, deletedTags); } }) .setNegativeButton(android.R.string.cancel, null); return builder.create(); }

Target:
public Dialog onCreateDialog(Bundle savedInstance) { if (savedInstance != null) { preSelectedTags = new HashSet<Keyword>(Arrays.asList( (Keyword[]) savedInstance.getParcelableArray("preSelectedTags"))); selectedTags = new HashSet<Keyword>(Arrays.asList( (Keyword[]) savedInstance.getParcelableArray("selectedTags"))); } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle(R.string.tag_choice_dialog_title) .setView(getTagChoiceView()) .setPositiveButton(android.R.string.ok, new OkListener()) .setNegativeButton(android.R.string.cancel, null); return builder.create(); }
Source:
private void setTimeZone(final String zoneId) { if (StringUtils.isBlank(zoneId)) { timeZone = TimeZone.getDefault().toZoneId(); logger.warn("No time zone set, fallback to the system time zone '{}'.", timeZone.toString()); } else { try { timeZone = ZoneId.of(zoneId); } catch (DateTimeException e) { timeZone = TimeZone.getDefault().toZoneId(); logger.warn("Error setting time zone '{}', fallback to the system time zone '{}': {}", zoneId, timeZone.toString(), e.getMessage()); } } }

Target:
private void setTimeZone(final String zoneId) { if (StringUtils.isBlank(zoneId)) { timeZone = TimeZone.getDefault().toZoneId(); logger.debug("No time zone set, falling back to the default time zone '{}'.", timeZone.toString()); } else { try { timeZone = ZoneId.of(zoneId); } catch (DateTimeException e) { timeZone = TimeZone.getDefault().toZoneId(); logger.warn("Error setting time zone '{}', falling back to the default time zone '{}': {}", zoneId, timeZone.toString(), e.getMessage()); } } }
Source:
private void getMessageBodyBytes(MessageBodyBytesProcessor processor) throws IOException, XMLStreamException { int currentEventType; StringBuilder cdata = new StringBuilder(); while (reader.hasNext()) { currentEventType = reader.getEventType(); if (currentEventType == XMLStreamConstants.END_ELEMENT) { break; } else if (currentEventType == XMLStreamConstants.CHARACTERS && cdata.length() > 0) { processor.processBodyBytes(decode(cdata.toString())); cdata.setLength(0); } else { cdata.append(new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()).trim()); } reader.next(); } }

Target:
private void getMessageBodyBytes(MessageBodyBytesProcessor processor) throws IOException, XMLStreamException { int currentEventType; StringBuilder cdata = new StringBuilder(); while (reader.hasNext()) { currentEventType = reader.getEventType(); if (currentEventType == XMLStreamConstants.END_ELEMENT) { break; } else if (currentEventType == XMLStreamConstants.CHARACTERS && reader.isWhiteSpace() && cdata.length() > 0) { processor.processBodyBytes(decode(cdata.toString())); cdata.setLength(0); } else { cdata.append(new String(reader.getTextCharacters(), reader.getTextStart(), reader.getTextLength()).trim()); } reader.next(); } }
Source:
private void tryToUpdateParseForAppUpgrade(Context context){ PrefManager.AppInfoPrefManager pmanager = new PrefManager.AppInfoPrefManager(context); Long previousVersion = pmanager.getAppVersionCode(); boolean hadNotification = pmanager.isNotificationEnabled(); int curVersion = PropertyUtil.getManifestVersionCode(context); if ( previousVersion < curVersion ){ ParseInstallation installation = ParseInstallation.getCurrentInstallation(); Locale locale = Locale.getDefault(); installation.put("preferredLanguage",locale.getLanguage()); installation.put("preferredCountry",locale.getCountry()); if ( hadNotification ) { pmanager.setAppUpgradeNeedSyncWithParse(true); } installation.saveEventually(); } pmanager.setAppVersionCode(curVersion); pmanager.setNotificationEnabled(true); }

Target:
private void tryToUpdateParseForAppUpgrade(Context context){ PrefManager.AppInfoPrefManager pmanager = new PrefManager.AppInfoPrefManager(context); Long previousVersion = pmanager.getAppVersionCode(); boolean hadNotification = pmanager.isNotificationEnabled(); int curVersion = PropertyUtil.getManifestVersionCode(context); if ( previousVersion < curVersion ){ if ( hadNotification ) { pmanager.setAppUpgradeNeedSyncWithParse(true); } } ParseInstallation installation = ParseInstallation.getCurrentInstallation(); final String languageKey = "preferredLanguage"; final String countryKey = "preferredLanguage"; String savedPreferredLanguage = installation.getString(languageKey); String savedPreferredCountry = installation.getString(countryKey); Locale locale = Locale.getDefault(); String currentPreferredLanguage = locale.getLanguage(); String currentPreferredCountry = locale.getCountry(); boolean dirty = false; if (!currentPreferredLanguage.equals(savedPreferredLanguage) ) { installation.put(languageKey, currentPreferredLanguage); dirty = true; } if (!currentPreferredCountry.equals(savedPreferredCountry) ) { installation.put(countryKey, currentPreferredCountry); dirty = true; } if ( dirty ) { try { installation.saveInBackground(); }catch (Exception ex){ logger.error(ex); } } pmanager.setAppVersionCode(curVersion); pmanager.setNotificationEnabled(true); }
Source:
private void safelyAddProperty(Properties properties, String key, Integer value) { properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value.intValue()); }

Target:
private void safelyAddProperty(Properties properties, String key, Integer value) { properties.put(key, ObjectUtils.isNull(value) ? KFSConstants.EMPTY_STRING : value); }