auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean validate() throws IntegerValidationException { for (int i = 0; i < numberOfKeys; i++) { final int result = parameterWorker.pull(startKey + i); if (expectedResult != result) { LOG.log(Level.WARNING, "For key {0}, expected value {1} but received {2}", new Object[]{startKey + i, expectedResult, result}); throw new IntegerValidationException(startKey + i, expectedResult, result); } else { LOG.log(Level.INFO, "For key {0}, received expected value {1}.", new Object[]{startKey + i, expectedResult}); } } return true; }

Target:
private boolean validate() { for (int i = 0; i < numberOfKeys; i++) { final int result = parameterWorker.pull(startKey + i); if (expectedResult != result) { LOG.log(Level.WARNING, "For key {0}, expected value {1} but received {2}", new Object[]{startKey + i, expectedResult, result}); return false; } else { LOG.log(Level.INFO, "For key {0}, received expected value {1}.", new Object[]{startKey + i, expectedResult}); } } return true; }
Source:
private Object[][] placedTests() { return new Object[][] { {false, false, false, false}, {true, false, false, true} }; }

Target:
private Object[][] placedTests() { final List<Object[]> retval = new ArrayList<>(); final int validSeqId = 0; final int[] sequenceIds = new int[]{ SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX, validSeqId }; final int validAlignmentStart = 1; final int[] starts = new int[]{ SAMRecord.NO_ALIGNMENT_START, validAlignmentStart }; final boolean[] deltas = new boolean[] { true, false }; final boolean[] mappeds = new boolean[] { true, false }; for (final int sequenceId : sequenceIds) { for (final int start : starts) { for (final boolean delta : deltas) { for (final boolean mapped : mappeds) { boolean placementExpectation = true; if (sequenceId == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) { placementExpectation = false; } if (!delta && start == SAMRecord.NO_ALIGNMENT_START) { placementExpectation = false; } retval.add(new Object[]{sequenceId, start, mapped, delta, placementExpectation}); } } } } return retval.toArray(new Object[0][0]); }
Source:
private void eventuallyAssertEvictions(float expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); assert expectedValue == advanced.getStats().getEvictions(); }

Target:
private void eventuallyAssertEvictions(float expectedValue) { eventuallyAssertAttributeValue("Evictions", expectedValue); assertEquals(expectedValue, (float) advanced.getStats().getEvictions()); }
Source:
public DbUser(DbUser dbUser) { if (dbUser == null) { loginName = ""; firstName = ""; lastName = ""; department = ""; groupNames = Collections.emptyList(); groupIds = Collections.emptyList(); note = ""; userOptions = new HashMap<>(); } else { id = dbUser.getId(); externalId = dbUser.getExternalId(); domain = dbUser.getDomain(); namespace = dbUser.getNamespace(); loginName = dbUser.getLoginName(); setFirstName(firstName = dbUser.getFirstName()); setLastName(lastName = dbUser.getLastName()); setDepartment(dbUser.getDepartment()); email = dbUser.getEmail(); note = dbUser.getNote(); groupIds = new ArrayList<>(dbUser.getGroupIds()); groupNames = new ArrayList<>(dbUser.getGroupNames()); isAdmin = dbUser.isAdmin(); userOptions = new HashMap<>(dbUser.getUserOptions()); } }

Target:
public DbUser(DbUser dbUser) { if (dbUser == null) { loginName = ""; firstName = ""; lastName = ""; department = ""; groupNames = Collections.emptyList(); groupIds = Collections.emptyList(); note = ""; userOptions = Collections.emptyMap(); } else { id = dbUser.getId(); externalId = dbUser.getExternalId(); domain = dbUser.getDomain(); namespace = dbUser.getNamespace(); loginName = dbUser.getLoginName(); setFirstName(firstName = dbUser.getFirstName()); setLastName(lastName = dbUser.getLastName()); setDepartment(dbUser.getDepartment()); email = dbUser.getEmail(); note = dbUser.getNote(); groupIds = new ArrayList<>(dbUser.getGroupIds()); groupNames = new ArrayList<>(dbUser.getGroupNames()); isAdmin = dbUser.isAdmin(); userOptions = new HashMap<>(dbUser.getUserOptions()); } }
Source:
public boolean openPort() throws Exception { responseMessageHandler = new ResponseMessageHandler(); try { client = new Socket(host, port); } catch( BindException e) { throw new ConnectionException("Could not bind a local port."); } catch( NoRouteToHostException e) { throw new ConnectionException("No route to host. The remote host may not be running, blocked by a firewall, or disconnected."); } catch( PortUnreachableException e) { throw new ConnectionException("The port is unreachable on the remote host. The server may not be running, or blocked by a firewall."); } catch (SocketException e) { e.printStackTrace(); } if (client == null) { throw new ConnectionException("Socket unable to connect."); } bufOut = client.getOutputStream(); inStream = new InputStreamReader(client.getInputStream()); bufIn = new BufferedReader(inStream); replyThread = new Thread(this); replyThread.start(); return client.isConnected(); }

Target:
public boolean openPort() throws Exception { responseMessageHandler = new ResponseMessageHandler(); try { client = new Socket(host, port); } catch( BindException e) { throw new ConnectionException("Could not bind a local port.", e); } catch( NoRouteToHostException e) { throw new ConnectionException("No route to host. The remote host may not be running, blocked by a firewall, or disconnected.", e); } catch( ConnectException e) { throw new ConnectionException("The port is unreachable on the remote host. The server may not be running, or blocked by a firewall.", e); } if (client == null) { throw new ConnectionException("Socket unable to connect."); } bufOut = client.getOutputStream(); inStream = new InputStreamReader(client.getInputStream()); bufIn = new BufferedReader(inStream); replyThread = new Thread(this); replyThread.start(); return client.isConnected(); }
Source:
public void setBaudRate(int b) { baudRate = b; }

Target:
public void setBaudRate(int b) { }
Source:
private void stageSchemaFiles(Configuration config) { if (config.m_userSchema == null) { return; } assert( config.m_userSchema.isFile() ); File stagedCatalogFH = new VoltFile(getStagedCatalogPath(getVoltDBRootPath())); if (!config.m_forceVoltdbCreate && stagedCatalogFH.exists()) { VoltDB.crashLocalVoltDB("A previous database was initialized with a schema. You must init with --force to overwrite the schema."); } final boolean standalone = false; final boolean isXCDR = false; VoltCompiler compiler = new VoltCompiler(standalone, isXCDR); if (!compiler.compileFromDDL(true, stagedCatalogFH.getAbsolutePath(), config.m_userSchema.getAbsolutePath())) { VoltDB.crashLocalVoltDB("Could not compile specified schema " + config.m_userSchema); } }

Target:
private void stageSchemaFiles(Configuration config) { if (config.m_userSchema == null) { return; } assert( config.m_userSchema.isFile() ); File stagedCatalogFH = new VoltFile(getStagedCatalogPath(getVoltDBRootPath())); if (!config.m_forceVoltdbCreate && stagedCatalogFH.exists()) { VoltDB.crashLocalVoltDB("A previous database was initialized with a schema. You must init with --force to overwrite the schema."); } final boolean standalone = false; final boolean isXCDR = false; VoltCompiler compiler = new VoltCompiler(standalone, isXCDR); compiler.setInitializeDDLWithFiltering(true); if (!compiler.compileFromSchemaAndClasses(config.m_userSchema, config.m_stagedClassesPath, stagedCatalogFH)) { VoltDB.crashLocalVoltDB("Could not compile specified schema " + config.m_userSchema); } }
Source:
protected E[] loadServices(final Class<E> service, final ClassLoader classLoader) { ArrayList<E> list = new ArrayList<>(); ServiceLoader<E> loader = ServiceLoader.load(service, classLoader); Iterator<E> iterator = loader.iterator(); for (;;) try { if (! iterator.hasNext()) { return list.toArray(Arrays2.createArray(service, list.size())); } list.add(iterator.next()); } catch (ServiceConfigurationError ignored) { } }

Target:
E[] loadServices(final Class<E> service, final ClassLoader classLoader) { ArrayList<E> list = new ArrayList<>(); ServiceLoader<E> loader = ServiceLoader.load(service, classLoader); Iterator<E> iterator = loader.iterator(); for (;;) try { if (! iterator.hasNext()) { return list.toArray(Arrays2.createArray(service, list.size())); } list.add(iterator.next()); } catch (ServiceConfigurationError ignored) { } }
Source:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { List<TmfAnalysisRequirement> requirements = new LinkedList<>(); List<String> eventNames = new LinkedList<>(); eventNames.add(LttngStrings.EXIT_SYSCALL); eventNames.add(LttngStrings.IRQ_HANDLER_ENTRY); eventNames.add(LttngStrings.IRQ_HANDLER_EXIT); eventNames.add(LttngStrings.SOFTIRQ_ENTRY); eventNames.add(LttngStrings.SOFTIRQ_EXIT); eventNames.add(LttngStrings.SOFTIRQ_RAISE); eventNames.add(LttngStrings.SCHED_SWITCH); eventNames.add(LttngStrings.SCHED_PROCESS_FORK); eventNames.add(LttngStrings.SCHED_PROCESS_EXIT); eventNames.add(LttngStrings.SCHED_PROCESS_FREE); eventNames.add(LttngStrings.STATEDUMP_PROCESS_STATE); eventNames.add(LttngStrings.SCHED_WAKEUP); eventNames.add(LttngStrings.SCHED_WAKEUP_NEW); eventNames.add(LttngStrings.SYSCALL_PREFIX); TmfAnalysisRequirement domainReq = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN); domainReq.addValue(SessionConfigStrings.CONFIG_DOMAIN_TYPE_KERNEL, ValuePriorityLevel.MANDATORY); requirements.add(domainReq); requirements.add(new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT, eventNames, ValuePriorityLevel.MANDATORY)); return requirements; }

Target:
public Iterable<TmfAnalysisRequirement> getAnalysisRequirements() { if (fRequirements == null) { ImmutableList<String> eventNames = ImmutableList.of(LttngStrings.EXIT_SYSCALL, LttngStrings.IRQ_HANDLER_ENTRY, LttngStrings.IRQ_HANDLER_EXIT, LttngStrings.SOFTIRQ_ENTRY, LttngStrings.SOFTIRQ_EXIT, LttngStrings.SOFTIRQ_RAISE, LttngStrings.SCHED_SWITCH, LttngStrings.SCHED_PROCESS_FORK, LttngStrings.SCHED_PROCESS_EXIT, LttngStrings.SCHED_PROCESS_FREE, LttngStrings.STATEDUMP_PROCESS_STATE, LttngStrings.SCHED_WAKEUP, LttngStrings.SCHED_WAKEUP_NEW, LttngStrings.SYSCALL_PREFIX); TmfAnalysisRequirement domainReq = new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_DOMAIN); domainReq.addValue(SessionConfigStrings.CONFIG_DOMAIN_TYPE_KERNEL, ValuePriorityLevel.MANDATORY); fRequirements = ImmutableList.of(domainReq, new TmfAnalysisRequirement(SessionConfigStrings.CONFIG_ELEMENT_EVENT, eventNames, ValuePriorityLevel.MANDATORY)); } return fRequirements; }
Source:
private static String normalizeIfBracketed(String value) { if (value.startsWith("(") && value.endsWith(")")) { return "-" + value.replace("(", "").replace(")", ""); } else { return value; } }

Target:
private static String normalizeIfBracketed(String value) { if (value.length() > 2 && value.startsWith("(") && value.endsWith(")")) { String valueWithoutBrackets = value.substring(1, value.length() - 1); return "-" + valueWithoutBrackets; } else { return value; } }
Source:
public synchronized void internalCallScene(Short sceneNumber) { logger.debug("call Scene id dSID {}", sceneNumber, dsid.getValue()); if (isDeviceWithOutput()) { activeSceneNumber = sceneNumber; informLastSceneAboutSceneCall(sceneNumber); if (!isShade()) { outputValueBeforeSceneCall = this.outputValue; } else { outputValueBeforeSceneCall = this.slatPosition; if (isBlind()) { slatAngleBeforeSceneCall = this.slatAngle; } } if (!checkSceneNumber(sceneNumber)) { if (containsSceneConfig(sceneNumber)) { if (doIgnoreScene(sceneNumber)) { return; } } else { this.deviceStateUpdates.add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_CONFIG, new Short[] { sceneNumber, 0 })); } if (sceneOutputMap.get(sceneNumber) != null) { if (!isShade()) { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.OUTPUT, sceneOutputMap.get(sceneNumber)[0])); } else { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.SLATPOSITION, sceneOutputMap.get(sceneNumber)[0])); if (isBlind()) { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.SLAT_ANGLE, sceneOutputMap.get(sceneNumber)[1])); } } } else { this.deviceStateUpdates.add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_OUTPUT, new Short[] { sceneNumber, 0 })); } } } }

Target:
public synchronized void internalCallScene(Short sceneNumber) { logger.debug("call Scene id dSID {}", sceneNumber, dsid.getValue()); if (isDeviceWithOutput()) { activeSceneNumber = sceneNumber; informLastSceneAboutSceneCall(sceneNumber); if (!isShade()) { outputValueBeforeSceneCall = this.outputValue; } else { outputValueBeforeSceneCall = this.slatPosition; if (isBlind()) { slatAngleBeforeSceneCall = this.slatAngle; } } if (!checkSceneNumber(sceneNumber)) { if (containsSceneConfig(sceneNumber)) { if (doIgnoreScene(sceneNumber)) { return; } } else { this.deviceStateUpdates.add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_CONFIG, new Short[] { sceneNumber, GeneralLibConstance.HIGHEST_READ_OUT_PRIORITY })); } if (sceneOutputMap.get(sceneNumber) != null) { if (!isShade()) { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.OUTPUT, sceneOutputMap.get(sceneNumber)[GeneralLibConstance.SCENE_ARRAY_INDEX_VALUE])); } else { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.SLATPOSITION, sceneOutputMap.get(sceneNumber)[GeneralLibConstance.SCENE_ARRAY_INDEX_VALUE])); if (isBlind()) { updateInternalDeviceState(new DeviceStateUpdateImpl(DeviceStateUpdate.SLAT_ANGLE, sceneOutputMap.get(sceneNumber)[GeneralLibConstance.SCENE_ARRAY_INDEX_ANGLE])); } } } else { this.deviceStateUpdates.add(new DeviceStateUpdateImpl(DeviceStateUpdate.UPDATE_SCENE_OUTPUT, new Short[] { sceneNumber, GeneralLibConstance.HIGHEST_READ_OUT_PRIORITY })); } } } }
Source:
private void onMatchingPipeline(Pipeline pipeline) { log.info("Found matching pipeline {}:{}", pipeline.getApplication(), pipeline.getName()); val id = registry.createId("pipelines.triggered") .withTag("application", pipeline.getApplication()) .withTag("name", pipeline.getName()); if (pipeline.getTrigger().getType() == JENKINS_TRIGGER_TYPE) { id.withTag("job", pipeline.getTrigger().getJob()); } if (pipeline.getTrigger().getType() == GIT_TRIGGER_TYPE) { id.withTag("repository", pipeline.getTrigger().getProject() + ' ' + pipeline.getTrigger().getSlug()); } registry.counter(id).increment(); }

Target:
private void onMatchingPipeline(Pipeline pipeline) { log.info("Found matching pipeline {}:{}", pipeline.getApplication(), pipeline.getName()); val id = registry.createId("pipelines.triggered") .withTag("application", pipeline.getApplication()) .withTag("name", pipeline.getName()); if (pipeline.getTrigger().getType() == JENKINS_TRIGGER_TYPE) { id.withTag("job", pipeline.getTrigger().getJob()); } else if (pipeline.getTrigger().getType() == GIT_TRIGGER_TYPE) { id.withTag("repository", pipeline.getTrigger().getProject() + ' ' + pipeline.getTrigger().getSlug()); } registry.counter(id).increment(); }
Source:
public int furnaceminecart$getFuel() { return this.fuel; }

Target:
public int getFuel() { return this.fuel; }
Source:
public static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService) { try { if (CREATE_STL != null) { return (SimpleTimeLimiter) CREATE_STL.invoke(null, executorService); } else if (CONSTRUCT_STL != null) { return CONSTRUCT_STL.newInstance(executorService); } } catch (IllegalAccessException iae) { } catch (InstantiationException ie) { } catch (InvocationTargetException ite) { throw Throwables.propagate(ite.getCause()); } throw new UnsupportedOperationException("Can't construct SimpleTimeLimiter"); }

Target:
public static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService) { try { if (CREATE_STL != null) { return (SimpleTimeLimiter) CREATE_STL.invoke(null, executorService); } else if (CONSTRUCT_STL != null) { return CONSTRUCT_STL.newInstance(executorService); } throw new UnsupportedOperationException( "Can't find SimpleTimeLimiter creator or constructor taking ExecutorService"); } catch (IllegalAccessException iae) { throw new UnsupportedOperationException("Can't access SimpleTimeLimiter method/ctor", iae); } catch (InstantiationException ie) { throw new UnsupportedOperationException("Can't construct SimpleTimeLimiter", ie); } catch (InvocationTargetException ite) { Throwable throwable = ite.getCause(); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } if (throwable instanceof Error) { throw (Error) throwable; } throw new UnsupportedOperationException( "Checked exception thrown while creating SimpleTimeLimiter", throwable); } }
Source:
public void testReturnKey() throws Exception { long[] ids = b.insertNames("a", "b", "c", "d", "e"); assertThat(ids).containsExactly(new long[] { 1, 2, 3, 4, 5 }); }

Target:
public void testReturnKey() throws Exception { long[] ids = b.insertNames("a", "b", "c", "d", "e"); assertThat(ids).containsExactly(1, 2, 3, 4, 5); }
Source:
public void onStarted(Run r, TaskListener listener) { if (r instanceof AbstractBuild) { Node node = getCurrentNode(); if (node instanceof MesosSlave) { try { Computer computer = node.toComputer(); if (computer != null) { EnvVars environment = computer.getEnvironment(); String hostname; if(isBuildRunningInsideContainer(environment)) { hostname = environment.get(HOSTNAME); }else { hostname = node.toComputer().getHostName(); } listener.getLogger().println("Mesos slave(hostname): " + hostname); } else { listener.getLogger().println("Mesos slave(computer is null)"); } } catch (IOException e) { LOGGER.warning("IOException while trying to get hostname: " + e); e.printStackTrace(); } catch (InterruptedException e) { LOGGER.warning("InterruptedException while trying to get hostname: " + e); } } } }

Target:
public void onStarted(Run r, TaskListener listener) { if (r instanceof AbstractBuild) { Node node = getCurrentNode(); if (node instanceof MesosSlave) { try { String hostname = null; Computer computer = node.toComputer(); MesosSlave mesosSlave = (MesosSlave) node; if (mesosSlave.getSlaveInfo().getContainerInfo() != null && DOCKER.equals(mesosSlave.getSlaveInfo().getContainerInfo().getType())) { if (computer != null) { EnvVars environment = computer.getEnvironment(); hostname = environment.get(HOSTNAME); } } else { if(computer != null) { hostname = computer.getHostName(); } } listener.getLogger().println("Mesos slave(hostname): " + hostname); } catch (IOException e) { LOGGER.warning("IOException while trying to get hostname: " + e); e.printStackTrace(); } catch (InterruptedException e) { LOGGER.warning("InterruptedException while trying to get hostname: " + e); } } } }
Source:
public Order cloneForDiscontinuing() { DrugOrder newOrder = new DrugOrder(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setDrug(this.getDrug()); newOrder.setStartDate(this.getStartDate()); newOrder.setOrderer(this.getOrderer()); return newOrder; }

Target:
public Order cloneForDiscontinuing() { DrugOrder newOrder = new DrugOrder(); newOrder.setCareSetting(this.getCareSetting()); newOrder.setConcept(this.getConcept()); newOrder.setAction(Action.DISCONTINUE); newOrder.setPreviousOrder(this); newOrder.setPatient(this.getPatient()); newOrder.setDrug(this.getDrug()); newOrder.setStartDate(this.getStartDate()); return newOrder; }
Source:
public void copyAndVerify(Path destRoot, List<ReplChangeManager.FileInfo> srcFiles) throws IOException, LoginException, HiveFatalException { Map<FileSystem, Map< Path, List<ReplChangeManager.FileInfo>>> map = fsToFileMap(srcFiles, destRoot); UserGroupInformation proxyUser = getProxyUser(); try { for (Map.Entry<FileSystem, Map<Path, List<ReplChangeManager.FileInfo>>> entry : map.entrySet()) { Map<Path, List<ReplChangeManager.FileInfo>> destMap = entry.getValue(); for (Map.Entry<Path, List<ReplChangeManager.FileInfo>> destMapEntry : destMap.entrySet()) { Path destination = destMapEntry.getKey(); List<ReplChangeManager.FileInfo> fileInfoList = destMapEntry.getValue(); if (fileInfoList.isEmpty()) { continue; } FileSystem sourceFs = fileInfoList.get(0).getSourcePath().getFileSystem(hiveConf); boolean useRegularCopy = regularCopy(sourceFs, fileInfoList); if (!destinationFs.exists(destination) && !FileUtils.mkdir(destinationFs, destination, hiveConf)) { LOG.error("Failed to create destination directory: " + destination); throw new IOException("Destination directory creation failed"); } doCopyRetry(sourceFs, fileInfoList, destination, proxyUser, useRegularCopy); } } } finally { if (proxyUser != null) { FileSystem.closeAllForUGI(proxyUser); } } }

Target:
public void copyAndVerify(Path destRoot, List<ReplChangeManager.FileInfo> srcFiles) throws IOException, LoginException, HiveFatalException { Map<FileSystem, Map< Path, List<ReplChangeManager.FileInfo>>> map = fsToFileMap(srcFiles, destRoot); UserGroupInformation proxyUser = getProxyUser(); try { for (Map.Entry<FileSystem, Map<Path, List<ReplChangeManager.FileInfo>>> entry : map.entrySet()) { Map<Path, List<ReplChangeManager.FileInfo>> destMap = entry.getValue(); for (Map.Entry<Path, List<ReplChangeManager.FileInfo>> destMapEntry : destMap.entrySet()) { Path destination = destMapEntry.getKey(); List<ReplChangeManager.FileInfo> fileInfoList = destMapEntry.getValue(); FileSystem sourceFs = fileInfoList.get(0).getSourcePath().getFileSystem(hiveConf); boolean useRegularCopy = regularCopy(sourceFs, fileInfoList); if (!destinationFs.exists(destination) && !FileUtils.mkdir(destinationFs, destination, hiveConf)) { LOG.error("Failed to create destination directory: " + destination); throw new IOException("Destination directory creation failed"); } doCopyRetry(sourceFs, fileInfoList, destination, proxyUser, useRegularCopy); } } } finally { if (proxyUser != null) { FileSystem.closeAllForUGI(proxyUser); } } }
Source:
public void doCreateAdminUser(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins j = Jenkins.getInstance(); j.checkPermission(Jenkins.ADMINISTER); HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm)j.getSecurityRealm(); User admin = securityRealm.getUser(SetupWizard.initialSetupAdminUserName); try { if(admin != null) { admin.delete(); } User u = securityRealm.createAccountByAdmin(req, rsp, "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly", j.getRootUrl()); if (u != null) { if(admin != null) { admin = null; } j.setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = securityRealm.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); } } finally { if(admin != null) { admin.save(); } } }

Target:
public void doCreateAdminUser(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { Jenkins j = Jenkins.getInstance(); j.checkPermission(Jenkins.ADMINISTER); HudsonPrivateSecurityRealm securityRealm = (HudsonPrivateSecurityRealm)j.getSecurityRealm(); User admin = securityRealm.getUser(SetupWizard.initialSetupAdminUserName); try { if(admin != null) { admin.delete(); } User u = securityRealm.createAccountByAdmin(req, rsp, "/jenkins/install/SetupWizard/setupWizardFirstUser.jelly", req.getContextPath() + "/"); if (u != null) { if(admin != null) { admin = null; } j.setInstallState(InstallState.CREATE_ADMIN_USER.getNextState()); Authentication a = new UsernamePasswordAuthenticationToken(u.getId(),req.getParameter("password1")); a = securityRealm.getSecurityComponents().manager.authenticate(a); SecurityContextHolder.getContext().setAuthentication(a); } } finally { if(admin != null) { admin.save(); } } }
Source:
public synchronized String toString(LocalTime localTime) { sbuf.setLength(0); if (localTime.isAfter(MAX_TIME)) { return "24:00:00"; } int nano = localTime.getNano(); if (nano % 1000 >= 500) { localTime = localTime.plus(ONE_MICROSECOND); } appendTime(sbuf, localTime); return sbuf.toString(); }

Target:
public synchronized String toString(LocalTime localTime) { sbuf.setLength(0); if (localTime.isAfter(MAX_TIME)) { return "24:00:00"; } int nano = localTime.getNano(); if (nanosExceed499(nano)) { localTime = localTime.plus(ONE_MICROSECOND); } appendTime(sbuf, localTime); return sbuf.toString(); }
Source:
public void uncaughtException(Thread thread, Throwable exception) { try { handleException(thread, exception); } catch (Throwable t) { LOG.log(Level.SEVERE, "Failed to handle exception. Process halting", t); Runtime.getRuntime().halt(1); } }

Target:
public void uncaughtException(Thread thread, Throwable exception) { try { LOG.log(Level.SEVERE, "Exception caught in thread: " + thread.getName() + " with thread id: " + thread.getId(), exception); } finally { Runtime.getRuntime().halt(1); } }
Source:
public void test_ipv4_cidr_operator() throws Throwable { test(COLUMN_NAME, new String[]{"192.168.0.1", "192.168.1.1", "192.168.1.7", "192.168.1.255", "192.168.2.0", "10.0.0.1"}, String.format("%s << '192.168.1.1/24'", COLUMN_NAME), "192.168.1.1", "192.168.1.7", "192.168.1.255"); }

Target:
public void test_ipv4_cidr_operator() throws Throwable { test("ip_addr", new String[]{"192.168.0.1", "192.168.1.1", "192.168.1.7", "192.168.1.255", "192.168.2.0", "10.0.0.1"}, "ip_addr << '192.168.1.1/24'", "192.168.1.1", "192.168.1.7", "192.168.1.255"); }
Source:
public void onFailure(@NonNull final Call<T> call, @NonNull final Throwable error) { if (progressCallback != null) { progressCallback.finishProcess(); } if (errorNotification != null) { if (refreshListener != null) { errorNotification.showError(R.string.reset_no_network_message, FontAwesomeIcons.fa_wifi, R.string.lbl_reload, new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkUtil.isConnected(context)) { refreshListener.onRefresh(); } } }); } else { errorNotification.showError(context, error); } } onFailure(error); }

Target:
public void onFailure(@NonNull final Call<T> call, @NonNull final Throwable error) { if (progressCallback != null) { progressCallback.finishProcess(); } if (messageCallback != null && callTrigger != null && !call.isCanceled()) { messageCallback.onMessage(callTrigger.getMessageType(), ErrorUtils.getErrorMessage(error, callTrigger, context)); } if (errorNotification != null) { if (refreshListener != null) { errorNotification.showError(context, error, R.string.lbl_reload, new View.OnClickListener() { @Override public void onClick(View v) { if (NetworkUtil.isConnected(context)) { refreshListener.onRefresh(); } } }); } else { errorNotification.showError(context, error); } } onFailure(error); onFinish(); }
Source:
public void addLocalAuthentication(UserEntity userEntity, String password, boolean persist) throws AmbariException { validatePassword(password); String encodedPassword = passwordEncoder.encode(password); addAuthentication(userEntity, UserAuthenticationType.LOCAL, encodedPassword, new Validator() { @Override public void validate(UserEntity userEntity, String key) throws AmbariException { List<UserAuthenticationEntity> authenticationEntities = userEntity.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.LOCAL) { throw new AmbariException("The authentication type already exists for this user"); } } } }, persist); }

Target:
public void addLocalAuthentication(UserEntity userEntity, String password, boolean persist) throws AmbariException { validatePassword(password); String encodedPassword = passwordEncoder.encode(password); addAuthentication(userEntity, UserAuthenticationType.LOCAL, encodedPassword, (user, key) -> { List<UserAuthenticationEntity> authenticationEntities = user.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if (entity.getAuthenticationType() == UserAuthenticationType.LOCAL) { throw new AmbariException("The authentication type already exists for this user"); } } }, persist); }
Source:
private static void checkSingleData(XmlContext context, Element data) { for (String name : PATH_ATTR_LIST) { if (data.hasAttributeNS(ANDROID_URI, name)) { Attr attr = data.getAttributeNodeNS(ANDROID_URI, name); String path = tryLookUpStringInResource(context, attr.getValue()); if (!path.startsWith("/")) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), "android:" + name + " attribute should start with /"); } } } if (data.hasAttributeNS(ANDROID_URI, ATTRIBUTE_PORT)) { Attr attr = data.getAttributeNodeNS(ANDROID_URI, ATTRIBUTE_PORT); try { String port = tryLookUpStringInResource(context, attr.getValue()); Integer.parseInt(port); } catch (NumberFormatException e) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), "android:port is not a legal number"); } } NamedNodeMap attrs = data.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node item = attrs.item(i); if (item.getNodeType() == Node.ATTRIBUTE_NODE) { Attr attr = (Attr) attrs.item(i); if (attr.getValue().isEmpty()) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), attr.getName() + " cannot be empty"); } } } }

Target:
private static void checkSingleData(XmlContext context, Element data) { for (String name : PATH_ATTR_LIST) { if (data.hasAttributeNS(ANDROID_URI, name)) { Attr attr = data.getAttributeNodeNS(ANDROID_URI, name); String path = replaceUrlWithValue(context, attr.getValue()); if (!path.startsWith("/") && !path.startsWith(SdkConstants.PREFIX_RESOURCE_REF)) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), "android:" + name + " attribute should start with '/', which is :" + path); } } } if (data.hasAttributeNS(ANDROID_URI, ATTRIBUTE_PORT)) { Attr attr = data.getAttributeNodeNS(ANDROID_URI, ATTRIBUTE_PORT); try { String port = replaceUrlWithValue(context, attr.getValue()); Integer.parseInt(port); } catch (NumberFormatException e) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), "android:port is not a legal number"); } } NamedNodeMap attrs = data.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node item = attrs.item(i); if (item.getNodeType() == Node.ATTRIBUTE_NODE) { Attr attr = (Attr) attrs.item(i); if (attr.getValue().isEmpty()) { context.report(ISSUE_ERROR, attr, context.getLocation(attr), attr.getName() + " cannot be empty"); } } } }
Source:
public void testWorkIdempotentConcurrent() throws InterruptedException { MetricsTracker tracker = new MetricsTracker(); tracker.assertDiff(0, 0, 0, 0); SleepWork work1 = new SleepWork(getDurationMillis()); SleepWork work2 = new SleepWork(getDurationMillis()); service.schedule(work1); service.schedule(work1); service.schedule(work1); service.schedule(work2); service.schedule(work2); service.schedule(work2); assertTrue(service.awaitCompletion(getDurationMillis() * 3, TimeUnit.MILLISECONDS)); tracker.assertDiff(0, 0, 6, 0); }

Target:
public void testWorkIdempotentConcurrent() throws InterruptedException { MetricsTracker tracker = new MetricsTracker(); tracker.assertDiff(0, 0, 0, 0); SleepWork work1 = new SleepWork(getDurationMillis()); SleepWork work2 = new SleepWork(getDurationMillis()); service.schedule(work1); service.schedule(work1); service.schedule(work1); service.schedule(work2); service.schedule(work2); service.schedule(work2); assertTrue(service.awaitCompletion(getDurationMillis() * 3 - 200, TimeUnit.MILLISECONDS)); tracker.assertDiff(0, 0, 6, 0); }
Source:
public Host lookup(final String hostName) { if (cache == null || userConfigFile.hasChanged()) updateCache(); Host h = cache.get(hostName); if (h == null) h = new Host(); if (h.patternsApplied) return h; for (final Map.Entry<String, Host> e : cache.entrySet()) { if (!isHostPattern(e.getKey())) continue; if (!isHostMatch(e.getKey(), hostName)) continue; h.copyFrom(e.getValue()); } if (h.hostName == null) h.hostName = hostName; if (h.user == null) h.user = OpenSshConfig.userName(); if (h.port == 0) h.port = OpenSshConfig.SSH_PORT; h.patternsApplied = true; return h; }

Target:
public Host lookup(final String hostName) { if (userConfigFile.hasChanged()) updateCache(); Host h = cache.get(hostName); if (h == null) h = new Host(); if (h.patternsApplied) return h; for (final Map.Entry<String, Host> e : cache.entrySet()) { if (!isHostPattern(e.getKey())) continue; if (!isHostMatch(e.getKey(), hostName)) continue; h.copyFrom(e.getValue()); } if (h.hostName == null) h.hostName = hostName; if (h.user == null) h.user = OpenSshConfig.userName(); if (h.port == 0) h.port = OpenSshConfig.SSH_PORT; h.patternsApplied = true; return h; }
Source:
private static String[][] uncheckedApproveSignature(ScriptApproval target, String signature) { try { return target.approveSignature(signature); } catch (IOException e) { throw new UncheckedIOException(e); } }

Target:
private static String[][] uncheckedApproveSignature(ScriptApproval target, String signature) { try { return target.approveSignature(signature); } catch (IOException e) { LOGGER.warning("Could not approve signature: " + signature + " ScriptApproval threw IOException: " + e.getMessage()); throw new UncheckedIOException(e); } }
Source:
public void putMetrics(MetricsRecord metricsRecord) { try { CollectorRegistry registry = new CollectorRegistry(); for (AbstractMetric metrics : metricsRecord.metrics()) { if (metrics.type() == COUNTER || metrics.type() == GAUGE) { String key = getMetricsName( metricsRecord.name(), metrics.name()).replace(" ", ""); int tagSize = metricsRecord.tags().size(); String[] labelNames = new String[tagSize]; String[] labelValues = new String[tagSize]; int index = 0; for (MetricsTag tag : metricsRecord.tags()) { String tagName = tag.name().toLowerCase(); if (NUM_OPEN_CONNECTION_SPERUSER.equals(tagName)) { continue; } labelNames[index] = tagName; labelValues[index] = tag.value() == null ? NULL : tag.value(); index++; } switch (metrics.type()) { case GAUGE: Gauge.build(key, key) .labelNames(labelNames) .register(registry) .labels(labelValues) .set(metrics.value().doubleValue()); break; case COUNTER: Counter.build(key, key) .labelNames(labelNames) .register(registry) .labels(labelValues) .inc(metrics.value().doubleValue()); break; default: break; } LOG.debug( "register succeed, metrics name is: " + key + " Type is :" + metrics.type().toString() + " tag is: " + Arrays.toString(labelNames) + " tagValue is " + Arrays.toString(labelValues) + " Value is : " + metrics.value().toString()); } } pg.push(registry, jobName, groupingKey); LOG.info("pushing succeed"); } catch (Exception e) { LOG.error("pushing job's metrics to gateway is failed ", e); } }

Target:
public void putMetrics(MetricsRecord metricsRecord) { try { CollectorRegistry registry = new CollectorRegistry(); for (AbstractMetric metrics : metricsRecord.metrics()) { if (metrics.type() == COUNTER || metrics.type() == GAUGE) { String key = getMetricsName( metricsRecord.name(), metrics.name()).replace(" ", ""); int tagSize = metricsRecord.tags().size(); String[] labelNames = new String[tagSize]; String[] labelValues = new String[tagSize]; int index = 0; for (MetricsTag tag : metricsRecord.tags()) { String tagName = tag.name().toLowerCase(); if (NUM_OPEN_CONNECTION_SPERUSER.equals(tagName)) { continue; } labelNames[index] = tagName; labelValues[index] = tag.value() == null ? NULL : tag.value(); index++; } switch (metrics.type()) { case GAUGE: Gauge.build(key, key) .labelNames(labelNames) .register(registry) .labels(labelValues) .set(metrics.value().doubleValue()); break; case COUNTER: Counter.build(key, key) .labelNames(labelNames) .register(registry) .labels(labelValues) .inc(metrics.value().doubleValue()); break; default: break; } if (LOG.isDebugEnabled()) { LOG.debug("register succeed, metrics name is: Type is :{} tag is: tagValue is Value is : {}" , key, metrics.type(), Arrays.toString(labelNames), Arrays.toString(labelValues), metrics.value()); } } } pg.push(registry, jobName, groupingKey); } catch (Exception e) { LOG.error("pushing job's metrics to gateway is failed ", e); } }
Source:
public static String rpad(String base, Integer len, String pad) { if (len < 0) { return null; } else if (len == 0) { return ""; } char[] data = new char[len]; char[] baseChars = base.toCharArray(); char[] padChars = pad.toCharArray(); int pos = 0; while (pos < base.length() && pos < len) { data[pos] = baseChars[pos]; pos += 1; } while (pos < len) { int i = 0; while (i < pad.length() && i < len - pos) { data[pos + i] = padChars[i]; i += 1; } pos += pad.length(); } return new String(data); }

Target:
public static String rpad(String base, Integer len, String pad) { if (len < 0) { return null; } else if (len == 0) { return ""; } char[] data = new char[len]; int pos = 0; for ( ; pos < base.length() && pos < len; pos++) { data[pos] = base.charAt(pos); } for ( ; pos < len; pos += pad.length()) { for (int i = 0; i < pad.length() && i < len - pos; i++) { data[pos + i] = pad.charAt(i); } } return new String(data); }
Source:
public void run() { path = withoutQuery(path); try { ByteBuffer content = null; if (!exists()) { notFound(); } else if ((content = fileBytes()) != null) { serve(guessMimeType(path), content, control, response, request); } else { if (!path.endsWith("/")) { response.status(301).header("Location", path + "/").end(); return; } if ((content = welcomeBytes()) != null) { serve(guessMimeType(welcomeFileName), content, control, response, request); } else if (isDirectoryListingEnabled && (content = directoryListingBytes()) != null) { serve(guessMimeType(".html"), content, control, response, request); } else { notFound(); } } } catch (IOException e) { error(e); } }

Target:
public void run() { String pathWithQuery = path; path = withoutQuery(path); try { ByteBuffer content = null; if (!exists()) { notFound(); return; } if (isDirectory()) { if (!path.endsWith("/")) { response.status(301).header("Location", path + "/" + extractQuery(pathWithQuery)).end(); return; } else if ((content = welcomeBytes()) != null) { serve(guessMimeType(welcomeFileName), content, control, response, request); return; } else if (isDirectoryListingEnabled && (content = directoryListingBytes()) != null) { serve(guessMimeType(".html"), content, control, response, request); return; } } else if ((content = fileBytes()) != null) { serve(guessMimeType(path), content, control, response, request); return; } else if ((content = welcomeBytes()) != null) { serve(guessMimeType(welcomeFileName), content, control, response, request); return; } notFound(); } catch (IOException e) { error(e); } }
Source:
public String getDisplayNameForValue(final String value) { for (Map.Entry<String, String> entry : mapDisplayValuesToValues.entrySet()) { if (entry.getValue().equals(value)) { return entry.getKey(); } } return value; }

Target:
public String getDisplayNameForValue(final String value) { return mapDisplayValuesToValues.entrySet().stream() .filter(v -> v.getValue().equals(value)) .map(Map.Entry::getKey) .findFirst() .orElse(value); }
Source:
LatLon getWorkPointLatLon() { LatLon workPointLatLon; if (hasWorkPoint()) { workPointLatLon = new LatLon(getWorkPoint().getLatitude(), getWorkPoint().getLongitude()); } else { workPointLatLon = new LatLon(0, 0); } return workPointLatLon; }

Target:
public LatLon getWorkPointLatLon() { LatLon workPointLatLon; if (hasWorkPoint()) { workPointLatLon = new LatLon(getWorkPoint().getLatitude(), getWorkPoint().getLongitude()); } else { workPointLatLon = null; } return workPointLatLon; }
Source:
private void bridgePollableToSubscribableChannel(MessageChannel pollableChannel, MessageChannel subscribableChannel) { ConsumerEndpointFactoryBean consumerEndpointFactoryBean = new ConsumerEndpointFactoryBean(); consumerEndpointFactoryBean.setInputChannel(pollableChannel); PollerMetadata pollerMetadata = new PollerMetadata(); pollerMetadata.setTrigger(new PeriodicTrigger(1000)); consumerEndpointFactoryBean.setPollerMetadata(pollerMetadata); consumerEndpointFactoryBean .setHandler(new MessageChannelBinderSupport.DirectHandler( subscribableChannel)); consumerEndpointFactoryBean.setBeanFactory(beanFactory); try { consumerEndpointFactoryBean.afterPropertiesSet(); } catch (Exception e) { e.printStackTrace(); } consumerEndpointFactoryBean.start(); }

Target:
private void bridgePollableToSubscribableChannel(MessageChannel pollableChannel, MessageChannel subscribableChannel) { ConsumerEndpointFactoryBean consumerEndpointFactoryBean = new ConsumerEndpointFactoryBean(); consumerEndpointFactoryBean.setInputChannel(pollableChannel); PollerMetadata pollerMetadata = new PollerMetadata(); pollerMetadata.setTrigger(new PeriodicTrigger(pollableBridgeDefaultFrequency)); consumerEndpointFactoryBean.setPollerMetadata(pollerMetadata); consumerEndpointFactoryBean .setHandler(new MessageChannelBinderSupport.DirectHandler( subscribableChannel)); consumerEndpointFactoryBean.setBeanFactory(beanFactory); try { consumerEndpointFactoryBean.afterPropertiesSet(); } catch (Exception e) { throw new IllegalStateException(e); } consumerEndpointFactoryBean.start(); }
Source:
public EnginesPreferencePage() { }

Target:
public EnginesPreferencePage() { super(); }
Source:
private GitModelObject extractFromCache(TreeWalk tw) throws IOException { DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth, DirCacheIterator.class); if (cacheIterator == null) return null; DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry(); if (cacheEntry == null) return null; if (shouldIncludeEntry(tw)) { String path = tw.getPathString(); ObjectId repoId = tw.getObjectId(BASE_NTH); ObjectId cacheId = tw.getObjectId(REMOTE_NTH); if (path.split("/").length > 1) return handleCacheTree(repoId, cacheId, path); return fileFactory.createFileModel(this, baseCommit, repoId, cacheId, getLocation().append(path)); } return null; }

Target:
private GitModelObject extractFromCache(TreeWalk tw) throws IOException { DirCacheIterator cacheIterator = tw.getTree(dirCacheIteratorNth, DirCacheIterator.class); if (cacheIterator == null) return null; DirCacheEntry cacheEntry = cacheIterator.getDirCacheEntry(); if (cacheEntry == null) return null; if (shouldIncludeEntry(tw)) { String path = tw.getPathString(); ObjectId repoId = tw.getObjectId(BASE_NTH); ObjectId cacheId = tw.getObjectId(REMOTE_NTH); if (path.contains("/")) return handleCacheTree(repoId, cacheId, path); return fileFactory.createFileModel(this, baseCommit, repoId, cacheId, getLocation().append(path)); } return null; }
Source:
public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(amCreateAccountResult, 0); parcel.writeParcelable(legacyCreateAccountResult, 0); }

Target:
public void writeToParcel(Parcel parcel, int i) { parcel.writeParcelable(amCreateAccountResult, i); parcel.writeParcelable(legacyCreateAccountResult, i); }
Source:
public ImageDescriptor getImageDescripterFromPath(String path) { return Objects.requireNonNull(AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path)); }

Target:
public @Nullable ImageDescriptor getImageDescripterFromPath(String path) { return AbstractUIPlugin.imageDescriptorFromPlugin(PLUGIN_ID, path); }
Source:
public Versions() { ClassLoader classLoader = EnvironmentInformation.class.getClassLoader(); try(InputStream propFile = classLoader.getResourceAsStream(PROP_FILE)) { if (propFile != null) { Properties properties = new Properties(); properties.load(propFile); projectVersion = getProperty(properties, "project.version"); scalaVersion = getProperty(properties, "scala.binary.version"); gitCommitId = getProperty(properties, "git.commit.id"); gitCommitIdAbbrev = getProperty(properties, "git.commit.id.abbrev"); DateTimeFormatter gitDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"); DateTimeFormatter BERLIN_DATE_TIME = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Europe/Berlin")); try { String propGitCommitTime = properties.getProperty("git.commit.time", DEFAULT_TIME_STRING); gitCommitTime = gitDateTimeFormatter.parse(propGitCommitTime, Instant::from); gitCommitTimeStr = BERLIN_DATE_TIME.format(gitCommitTime); String propGitBuildTime = properties.getProperty("git.build.time", DEFAULT_TIME_STRING); gitBuildTime = gitDateTimeFormatter.parse(propGitBuildTime, Instant::from); gitBuildTimeStr = BERLIN_DATE_TIME.format(gitBuildTime); } catch (DateTimeParseException dtpe) { LOG.error("{} : {}", FAIL_MESSAGE, dtpe); throw new IllegalStateException(FAIL_MESSAGE); } } } catch(IOException ioe) { if (LOG.isDebugEnabled()) { LOG.debug("Cannot determine code revision: Unable to read version property file.: {}", ioe.getMessage()); } else { LOG.info("Cannot determine code revision: Unable to read version property file.: {}", ioe.getMessage()); } } }

Target:
public Versions() { ClassLoader classLoader = EnvironmentInformation.class.getClassLoader(); try (InputStream propFile = classLoader.getResourceAsStream(PROP_FILE)) { if (propFile != null) { Properties properties = new Properties(); properties.load(propFile); projectVersion = getProperty(properties, "project.version", UNKNOWN); scalaVersion = getProperty(properties, "scala.binary.version", UNKNOWN); gitCommitId = getProperty(properties, "git.commit.id", UNKNOWN_COMMIT_ID); gitCommitIdAbbrev = getProperty(properties, "git.commit.id.abbrev", UNKNOWN_COMMIT_ID_ABBREV); DateTimeFormatter gitDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ"); DateTimeFormatter berlinDateTime = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Europe/Berlin")); try { String propGitCommitTime = getProperty(properties, "git.commit.time", DEFAULT_TIME_STRING); gitCommitTime = gitDateTimeFormatter.parse(propGitCommitTime, Instant::from); gitCommitTimeStr = berlinDateTime.format(gitCommitTime); String propGitBuildTime = getProperty(properties, "git.build.time", DEFAULT_TIME_STRING); gitBuildTime = gitDateTimeFormatter.parse(propGitBuildTime, Instant::from); gitBuildTimeStr = berlinDateTime.format(gitBuildTime); } catch (DateTimeParseException dtpe) { LOG.error("{} : {}", FAIL_MESSAGE, dtpe); throw new IllegalStateException(FAIL_MESSAGE); } } } catch (IOException ioe) { LOG.info("Cannot determine code revision: Unable to read version property file.: {}", ioe.getMessage()); } }
Source:
public Response getPropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!ZooKeeperAccessor.isPathValid(path)) { LOG.error("The propertyStore path is invalid for cluster {}", path, clusterId); return badRequest( "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode"); } final String recordPath = PropertyPathBuilder.propertyStore(clusterId) + path; ZkBaseDataAccessor<byte[]> propertyStoreDataAccessor = getByteArrayDataAccessor(); if (propertyStoreDataAccessor.exists(recordPath, AccessOption.PERSISTENT)) { byte[] bytes = propertyStoreDataAccessor.get(recordPath, null, AccessOption.PERSISTENT); ZNRecord znRecord = (ZNRecord) ZN_RECORD_SERIALIZER.deserialize(bytes); if (znRecord == null) { ObjectNode jsonNode = OBJECT_MAPPER.createObjectNode(); jsonNode.put(CONTENT_KEY, new String(bytes)); return JSONRepresentation(jsonNode); } return JSONRepresentation(znRecord); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity(String.format("The property store path %s doesn't exist", recordPath)).build()); } }

Target:
public Response getPropertyByPath(@PathParam("clusterId") String clusterId, @PathParam("path") String path) { path = "/" + path; if (!ZooKeeperAccessor.isPathValid(path)) { LOG.info("The propertyStore path is invalid for cluster {}", path, clusterId); return badRequest( "Invalid path string. Valid path strings use slash as the directory separator and names the location of ZNode"); } final String recordPath = PropertyPathBuilder.propertyStore(clusterId) + path; ZkBaseDataAccessor<byte[]> propertyStoreDataAccessor = getByteArrayDataAccessor(); if (propertyStoreDataAccessor.exists(recordPath, AccessOption.PERSISTENT)) { byte[] bytes = propertyStoreDataAccessor.get(recordPath, null, AccessOption.PERSISTENT); ZNRecord znRecord = (ZNRecord) ZN_RECORD_SERIALIZER.deserialize(bytes); if (znRecord == null) { ObjectNode jsonNode = OBJECT_MAPPER.createObjectNode(); jsonNode.put(CONTENT_KEY, new String(bytes)); return JSONRepresentation(jsonNode); } return JSONRepresentation(znRecord); } else { throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND) .entity(String.format("The property store path %s doesn't exist", recordPath)).build()); } }