auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { url = getRegistryUrl(url); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); } Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); String group = qs.get(GROUP_KEY); if (group != null && group.length() > 0) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(Cluster.getCluster("mergeable"), registry, type, url); } } Cluster cluster = Cluster.getCluster(qs.get(CLUSTER_KEY)); return doRefer(cluster, registry, type, url); }

Target:
public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { url = getRegistryUrl(url); Registry registry = registryFactory.getRegistry(url); if (RegistryService.class.equals(type)) { return proxyFactory.getInvoker((T) registry, type, url); } Map<String, String> qs = StringUtils.parseQueryString(url.getParameterAndDecoded(REFER_KEY)); String group = qs.get(GROUP_KEY); if (group != null && group.length() > 0) { if ((COMMA_SPLIT_PATTERN.split(group)).length > 1 || "*".equals(group)) { return doRefer(Cluster.getCluster(MergeableCluster.NAME), registry, type, url); } } Cluster cluster = Cluster.getCluster(qs.get(CLUSTER_KEY)); return doRefer(cluster, registry, type, url); }
Source:
private void saveHookContent(List<Callable<Pair<GlusterHookEntity, VDSReturnValue>>> contentTasksList) { if (contentTasksList.isEmpty()) { return; } List<Pair<GlusterHookEntity, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(contentTasksList); for (Pair<GlusterHookEntity, VDSReturnValue> pairResult: pairResults) { final GlusterHookEntity hook = pairResult.getFirst(); final String content = (String)pairResult.getSecond().getReturnValue(); getHooksDao().updateGlusterHookContent(hook.getId(), hook.getChecksum(), content); } }

Target:
private void saveHookContent(List<Callable<Pair<GlusterHookEntity, VDSReturnValue>>> contentTasksList) { if (contentTasksList.isEmpty()) { return; } List<Pair<GlusterHookEntity, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(contentTasksList); for (Pair<GlusterHookEntity, VDSReturnValue> pairResult: pairResults) { final GlusterHookEntity hook = pairResult.getFirst(); if (!pairResult.getSecond().getSucceeded()) { log.infoFormat("Failed to get content of hook {0} with error {1} ", hook.getHookKey(), pairResult.getSecond().getVdsError().getMessage()); logMessage(hook.getClusterId(), hook.getHookKey(), AuditLogType.GLUSTER_HOOK_GETCONTENT_FAILED); continue; } final String content = (String)pairResult.getSecond().getReturnValue(); getHooksDao().updateGlusterHookContent(hook.getId(), hook.getChecksum(), content); } }
Source:
public static BigDecimal numberToBigDecimal(Number number) { if (number instanceof QuantityType) { QuantityType<?> state = ((QuantityType<?>) number) .toUnit(((QuantityType<?>) number).getUnit().getSystemUnit()); if (state != null) { return new BigDecimal(state.doubleValue()); } return null; } if (number != null) { return new BigDecimal(number.toString()); } else { return null; } }

Target:
public static BigDecimal numberToBigDecimal(Number number) { if (number instanceof QuantityType) { QuantityType<?> state = ((QuantityType<?>) number) .toUnit(((QuantityType<?>) number).getUnit().getSystemUnit()); if (state != null) { return state.toBigDecimal(); } return null; } if (number != null) { return new BigDecimal(number.toString()); } else { return null; } }
Source:
public double getLogProb(int value) { return Math.log(getProb(value)); }

Target:
public double getLogProb(int value) { checkHasParams(); int k = value; if (k >= 0 && k <= n) { return Util.logPartialFactorial(n, k) - Util.logFactorial(k) + k * Math.log(p) + (n - k) * Math.log(1 - p); } else { return Double.NEGATIVE_INFINITY; } }
Source:
public long verify(CountWorkCall actualCall) { assertThat( actualCall.indexNames ) .as( "Search work did not target the expected indexes: " ) .isEqualTo( indexNames ); assertThat( actualCall.expectedResult ) .as( "Actual Call should not curry an expectedResult" ) .isNull(); return expectedResult; }

Target:
public long verify(CountWorkCall actualCall) { assertThat( actualCall.indexNames ) .as( "Count work did not target the expected indexes: " ) .isEqualTo( indexNames ); assertThat( actualCall.expectedResult ) .as( "Actual Call should not carry an expectedResult" ) .isNull(); return expectedResult; }
Source:
public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) { ParcelFileDescriptor input = null; ParcelFileDescriptor output = null; try { if (dataSource != null) { Long expectedSize = dataSource.getSizeForProgress(); if (expectedSize != null) { data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize); } else { data.removeExtra(EXTRA_PROGRESS_MESSENGER); } input = dataSource.startPumpThread(); } DataSinkTransferThread<T> pumpThread = null; int outputPipeId = 0; if (dataSink != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output); } Intent result = executeApi(data, input, outputPipeId); if (pumpThread == null) { return new OpenPgpDataResult<>(result, null); } pumpThread.join(); return new OpenPgpDataResult<>(result, pumpThread.getResult()); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return new OpenPgpDataResult<>(result, null); } finally { if (output != null) { try { output.close(); } catch (IOException e) { Log.e(OpenPgpApi.TAG, "IOException when closing ParcelFileDescriptor!", e); } } } }

Target:
public <T> OpenPgpDataResult<T> executeApi(Intent data, OpenPgpDataSource dataSource, OpenPgpDataSink<T> dataSink) { ParcelFileDescriptor input = null; ParcelFileDescriptor output = null; try { if (dataSource != null) { Long expectedSize = dataSource.getSizeForProgress(); if (expectedSize != null) { data.putExtra(EXTRA_DATA_LENGTH, (long) expectedSize); } else { data.removeExtra(EXTRA_PROGRESS_MESSENGER); } input = dataSource.startPumpThread(); } DataSinkTransferThread<T> pumpThread = null; int outputPipeId = 0; if (dataSink != null) { outputPipeId = mPipeIdGen.incrementAndGet(); output = mService.createOutputPipe(outputPipeId); pumpThread = ParcelFileDescriptorUtil.asyncPipeToDataSink(dataSink, output); } Intent result = executeApi(data, input, outputPipeId); if (pumpThread == null) { return new OpenPgpDataResult<>(result, null); } pumpThread.join(); return new OpenPgpDataResult<>(result, pumpThread.getResult()); } catch (Exception e) { Log.e(OpenPgpApi.TAG, "Exception in executeApi call", e); Intent result = new Intent(); result.putExtra(RESULT_CODE, RESULT_CODE_ERROR); result.putExtra(RESULT_ERROR, new OpenPgpError(OpenPgpError.CLIENT_SIDE_ERROR, e.getMessage())); return new OpenPgpDataResult<>(result, null); } finally { closeLoudly(output); } }
Source:
public PlainDoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage); final ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer(); doubleDictionaryContent = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); doubleReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, dictionaryByteBuf.position()); for (int i = 0; i < doubleDictionaryContent.length; i++) { doubleDictionaryContent[i] = doubleReader.readDouble(); } }

Target:
public PlainDoubleDictionary(DictionaryPage dictionaryPage) throws IOException { super(dictionaryPage); final ByteBuffer dictionaryByteBuf = dictionaryPage.getBytes().toByteBuffer(); doubleDictionaryContent = new double[dictionaryPage.getDictionarySize()]; DoublePlainValuesReader doubleReader = new DoublePlainValuesReader(); doubleReader.initFromPage(dictionaryPage.getDictionarySize(), dictionaryByteBuf, 0); for (int i = 0; i < doubleDictionaryContent.length; i++) { doubleDictionaryContent[i] = doubleReader.readDouble(); } }
Source:
public CollectedUpdateMetrics loadUrl(String sparql) { return execute("uri", UPDATE_METRICS_RESPONSE, sparql); }

Target:
public Integer loadUrl(String sparql) { return execute("uri", UPDATE_COUNT_RESPONSE, sparql); }
Source:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { String result = doRequestString("/ats/program/" + getSawTeam().getArtId() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }

Target:
public void testAtsProgramInsertionBadProgramIdRestCall() throws Exception { String result = doRequestString("/ats/program/" + getSawTeam() + "/insertion", HttpMethod.GET, null, javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); Assert.assertTrue(result.contains("SERVER_ERROR")); }
Source:
public static World readWorld(GlowServer server, CompoundTag compound) { final World[] world = {null}; compound.readUuid("WorldUUIDMost", "WorldUUIDLeast", uuid -> world[0] = server.getWorld(uuid)); if (world[0] == null) { compound.readString("World", name -> world[0] = server.getWorld(name)); } if (world[0] == null) { compound.readInt("Dimension", dim -> { for (World serverWorld : server.getWorlds()) { if (serverWorld.getEnvironment().getId() == dim) { world[0] = serverWorld; break; } } }); } return world[0]; }

Target:
public static World readWorld(GlowServer server, CompoundTag compound) { World world = compound .tryGetUuid("WorldUUIDMost", "WorldUUIDLeast") .map(server::getWorld) .orElseGet(() -> compound.tryGetString("World") .map(server::getWorld) .orElse(null)); if (world == null) { world = compound .tryGetInt("Dimension") .map(World.Environment::getEnvironment) .flatMap(env -> server.getWorlds().stream() .filter(serverWorld -> env == serverWorld.getEnvironment()) .findFirst()) .orElse(null); } return world; }
Source:
private LockManager getLockManager() { try { return (LockManager) new InitialContext().lookup("java:global/engine/bll/LockManager"); } catch (NamingException e) { return null; } }

Target:
private LockManager getLockManager() { try { return (LockManager) new InitialContext().lookup("java:global/engine/bll/LockManager"); } catch (NamingException e) { throw new RuntimeException("Could not find LockManager via JNDI lookup", e); } }
Source:
public void testGetBucketLocation() { assertEquals("us-west-1", s3.getBucketLocation(EXPECTED_BUCKET_NAME)); }

Target:
public void testGetBucketLocation() { assertEquals(Regions.US_WEST_1.getName(), s3.getBucketLocation(EXPECTED_BUCKET_NAME)); }
Source:
public ActivityCalendar convertTo(final com.alliander.osgp.dto.valueobjects.smartmetering.ActivityCalendar source, final Type<ActivityCalendar> destinationType) { if (source == null) { return null; } final ActivityCalendar activityCalendar = new ActivityCalendar(); return activityCalendar; }

Target:
public ActivityCalendar convertTo(final com.alliander.osgp.dto.valueobjects.smartmetering.ActivityCalendar source, final Type<ActivityCalendar> destinationType) { throw new IllegalStateException("convertTo is not supported"); }
Source:
protected void pushLiveInstancedata() throws AmazonClientException { Instance inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); if (inst != null && tags != null && !tags.isEmpty()) { HashSet<Tag> instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); } List<String> resources = getResourcesToTag(inst); CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(resources).setTags(instTags); getCloud().connect().createTags(tagRequest); } }

Target:
protected void pushLiveInstancedata() throws AmazonClientException { Instance inst = null; try { inst = CloudHelper.getInstanceWithRetry(getInstanceId(), getCloud()); } catch (InterruptedException e) { LOGGER.fine("InterruptedException while get " + getInstanceId() + " Exception: " + e); } if (inst != null && tags != null && !tags.isEmpty()) { HashSet<Tag> instTags = new HashSet<Tag>(); for (EC2Tag t : tags) { instTags.add(new Tag(t.getName(), t.getValue())); } List<String> resources = getResourcesToTag(inst); CreateTagsRequest tagRequest = new CreateTagsRequest(); tagRequest.withResources(resources).setTags(instTags); getCloud().connect().createTags(tagRequest); } }
Source:
public MinecraftVersion getMinecraftVersion() { MinecraftVersion mcvToReturn; ServerStatusResponse.MinecraftProtocolVersionIdentifier protocolVersionInfo = MinecraftServer.getServer().getServerStatusResponse().getProtocolVersionInfo(); String name = protocolVersionInfo.getName(); int protocolVersion = protocolVersionInfo.getProtocol(); double numberVersion = Double.valueOf(name); if (numberVersion < 1.7) { if (numberVersion >= 1.6) mcvToReturn = SpongeLegacyMinecraftVersion.V1_6; else if (numberVersion >= 1.4 && numberVersion <= 1.5) mcvToReturn = SpongeLegacyMinecraftVersion.V1_5; else mcvToReturn = SpongeLegacyMinecraftVersion.V1_3; } else { mcvToReturn = new SpongeMinecraftVersion(name, protocolVersion); } return mcvToReturn; }

Target:
public MinecraftVersion getMinecraftVersion() { return (MinecraftVersion) MinecraftServer.getServer().getServerStatusResponse().getProtocolVersionInfo(); }
Source:
public void raiseAlert(Alert a) throws AlertingException { if (!mailProps.containsKey("mail.smtp.host")) { log.error("No SMTP host specified in the mail.properties configuration file. Cannot send email."); throw new AlertingException("No SMTP host specified in the mail.properties configuration file. Cannot send email."); } else { String from = mailProps.getProperty("mail.from"); if (!isStringEmptyOrNull(from)) { from = "miso@your.miso.server"; } String to = a.getAlertUser().getEmail(); String subject = "MISO ALERT: " + a.getAlertTitle(); String text = "Hello " + a.getAlertUser().getFullName() + ",\n\nMISO would like to tell you about something:\n\n" + a.getAlertTitle() + " (" + a.getAlertDate() + ")" + "\n\n" + a.getAlertText(); try { EmailUtils.send(to, from, subject, text, mailProps); } catch (MessagingException e) { log.error("Cannot send email to alert recipients", e); throw new AlertingException("Cannot send email to alert recipients", e); } } }

Target:
public void raiseAlert(Alert a) throws AlertingException { if (!mailProps.containsKey("mail.smtp.host")) { log.error("No SMTP host specified in the mail.properties configuration file. Cannot send email."); throw new AlertingException("No SMTP host specified in the mail.properties configuration file. Cannot send email."); } else { String from = mailProps.getProperty("mail.from", "miso@your.miso.server"); String to = a.getAlertUser().getEmail(); String subject = "MISO ALERT: " + a.getAlertTitle(); String text = "Hello " + a.getAlertUser().getFullName() + ",\n\nMISO would like to tell you about something:\n\n" + a.getAlertTitle() + " (" + a.getAlertDate() + ")" + "\n\n" + a.getAlertText(); try { EmailUtils.send(to, from, subject, text, mailProps); } catch (MessagingException e) { log.error("Cannot send email to alert recipients", e); throw new AlertingException("Cannot send email to alert recipients", e); } } }
Source:
public static Object unmarshall(ByteBuffer payload) { try { return new ObjectInputStream(new ByteBufferInputStream(payload)).readObject(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException(ex); } }

Target:
public static Object unmarshall(ByteBuffer payload) { ObjectInputStream objectInputStream = null; try { objectInputStream = new ObjectInputStream(new ByteBufferInputStream(payload)); return objectInputStream.readObject(); } catch (IOException ex) { throw new IllegalArgumentException(ex); } catch (ClassNotFoundException ex) { throw new IllegalArgumentException(ex); } finally { closeSilently(objectInputStream); } }
Source:
public static FtRemote secure(final Take take) throws IOException { final ServerSocket skt = SSLServerSocketFactory.getDefault() .createServerSocket(0); return new FtRemote( new FtSecure(new BkBasic(take), skt), skt, true ); }

Target:
private static FtRemote secure(final Take take) throws IOException { final ServerSocket skt = SSLServerSocketFactory.getDefault() .createServerSocket(0); return new FtRemote( new FtSecure(new BkBasic(take), skt), skt, true ); }
Source:
public synchronized void checkAssignFrom(String nodeIdentifier) { int currentNodeCount = nodeSupplier.getWorkerNodes().size(); if (currentNodeCount < minimumNodeCount) { throw new PrestoException(RAPTOR_NOT_ENOUGH_NODES, format("Too many nodes down (required: %s, current: %s)", minimumNodeCount, currentNodeCount)); } if (offlineNodes.contains(nodeIdentifier)) { return; } long now = ticker.read(); long start = delayedNodes.computeIfAbsent(nodeIdentifier, key -> now); Duration delay = new Duration(now - start, NANOSECONDS); if (delay.compareTo(reassignmentDelay) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_DELAY, format( "Reassignment delay is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } if (lastOfflined.isPresent()) { delay = new Duration(now - lastOfflined.getAsLong(), NANOSECONDS); if (delay.compareTo(reassignmentInterval) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_THROTTLE, format( "Reassignment throttle is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } } delayedNodes.remove(nodeIdentifier); offlineNodes.add(nodeIdentifier); lastOfflined = OptionalLong.of(now); }

Target:
public synchronized void checkAssignFrom(String nodeIdentifier) { int currentNodeCount = nodeSupplier.getWorkerNodes().size(); if (currentNodeCount < minimumNodeCount) { throw new PrestoException(RAPTOR_NOT_ENOUGH_NODES, format("Not enough nodes available (required: %s, current: %s)", minimumNodeCount, currentNodeCount)); } if (offlineNodes.contains(nodeIdentifier)) { return; } long now = ticker.read(); long start = delayedNodes.computeIfAbsent(nodeIdentifier, key -> now); Duration delay = new Duration(now - start, NANOSECONDS); if (delay.compareTo(reassignmentDelay) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_DELAY, format( "Reassignment delay is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } if (lastOfflined.isPresent()) { delay = new Duration(now - lastOfflined.getAsLong(), NANOSECONDS); if (delay.compareTo(reassignmentInterval) < 0) { throw new PrestoException(RAPTOR_REASSIGNMENT_THROTTLE, format( "Reassignment throttle is in effect for node %s (elapsed: %s)", nodeIdentifier, delay.convertToMostSuccinctTimeUnit())); } } delayedNodes.remove(nodeIdentifier); offlineNodes.add(nodeIdentifier); lastOfflined = OptionalLong.of(now); }
Source:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addKeyDownHandler(keyDownEvent -> { final int keyCode = keyDownEvent.getNativeKeyCode(); if (keyCode == KeyCodes.KEY_TAB) { destroyResources(); gridPanel.setFocus(true); keyDownEvent.preventDefault(); } keyDownEvent.stopPropagation(); }); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }

Target:
public TextArea createWidget() { final TextArea textArea = GWT.create(TextArea.class); textArea.addMouseDownHandler(DomEvent::stopPropagation); return textArea; }
Source:
public void readEmptyMetadataInOtherTransaction() { String testValue = "testValue"; String testKey = "test"; GraphDatabaseFacade localGraph = neo.getLocalGraph(); try ( Transaction transaction = localGraph.beginTx() ) { localGraph.execute( "CALL dbms.setTXMetaData", map( "data", map( testKey, testValue ) ) ); transaction.success(); } try ( Transaction ignored = localGraph.beginTx() ) { Map<String,Object> metadata = (Map<String,Object>) localGraph.execute( "CALL dbms.getTXMetaData " ).next().get( "metadata" ); assertNull( metadata.get( testKey ) ); } }

Target:
public void readEmptyMetadataInOtherTransaction() { String testValue = "testValue"; String testKey = "test"; assertEmpty( writeSubject, "CALL dbms.setTXMetaData({" + testKey + ":'" + testValue + "'})" ); assertSuccess( writeSubject, "CALL dbms.getTXMetaData", mapResourceIterator -> { Map<String,Object> metadata = mapResourceIterator.next(); assertNull( metadata.get( testKey ) ); mapResourceIterator.close(); } ); }
Source:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { return expirationTimeInMs < referenceTimeInMs && expirationTimeInMs != Utils.Infinite_Time; }

Target:
private boolean isExpired(long expirationTimeInMs, long referenceTimeInMs) { return expirationTimeInMs != Utils.Infinite_Time && expirationTimeInMs < referenceTimeInMs; }
Source:
private String buildLargeString(int sizeInMB) { char[] filler = new char[sizeInMB * 1024 * 1024]; for (int i = 0; i < filler.length; i++) { filler[i] = '0'; } return new String(filler); }

Target:
private String buildLargeString(int sizeInMB) { char[] filler = new char[sizeInMB * 1024 * 1024]; Arrays.fill(filler, '0'); return new String(filler); }
Source:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}", ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool.setContractNumber(inputPoolDTO.getContractNumber()); pool.setOrderNumber(inputPoolDTO.getOrderNumber()); pool.setAccountNumber(inputPoolDTO.getAccountNumber()); pool.setUpstreamPoolId(inputPoolDTO.getUpstreamPoolId()); pool.setSubscriptionSubKey(inputPoolDTO.getSubscriptionSubKey()); pool.setSubscriptionId(inputPoolDTO.getSubscriptionId()); pool.setLocked(false); if (inputPoolDTO.getProductId() == null || inputPoolDTO.getProductId().isEmpty()) { throw new BadRequestException(i18n.tr("Pool product ID not specified")); } pool.setProduct(findProduct(pool.getOwner(), inputPoolDTO.getProductId())); if (inputPoolDTO.getDerivedProductId() != null) { pool.setDerivedProduct(findProduct(pool.getOwner(), inputPoolDTO.getDerivedProductId())); } if (inputPoolDTO.getSourceEntitlement() != null) { pool.setSourceEntitlement(findEntitlement(inputPoolDTO.getSourceEntitlement().getId())); } pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }

Target:
public PoolDTO createPool(@PathParam("owner_key") @Verify(Owner.class) String ownerKey, @ApiParam(name = "pool", required = true) PoolDTO inputPoolDTO) { log.info("Creating custom pool for owner {}: {}", ownerKey, inputPoolDTO); Pool pool = new Pool(); Owner owner = findOwnerByKey(ownerKey); pool.setOwner(owner); this.populateEntity(pool, inputPoolDTO); pool.setContractNumber(inputPoolDTO.getContractNumber()); pool.setOrderNumber(inputPoolDTO.getOrderNumber()); pool.setAccountNumber(inputPoolDTO.getAccountNumber()); pool.setUpstreamPoolId(inputPoolDTO.getUpstreamPoolId()); pool.setSubscriptionSubKey(inputPoolDTO.getSubscriptionSubKey()); pool.setSubscriptionId(inputPoolDTO.getSubscriptionId()); if (inputPoolDTO.getProductId() == null || inputPoolDTO.getProductId().isEmpty()) { throw new BadRequestException(i18n.tr("Pool product ID not specified")); } pool.setProduct(findProduct(pool.getOwner(), inputPoolDTO.getProductId())); if (inputPoolDTO.getDerivedProductId() != null) { pool.setDerivedProduct(findProduct(pool.getOwner(), inputPoolDTO.getDerivedProductId())); } if (inputPoolDTO.getSourceEntitlement() != null) { pool.setSourceEntitlement(findEntitlement(inputPoolDTO.getSourceEntitlement().getId())); } pool = poolManager.createAndEnrichPools(pool); return this.translator.translate(pool, PoolDTO.class); }
Source:
private void recoverFromTranslogInternal(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException { final int opsRecovered; final long localCheckpoint = getProcessedLocalCheckpoint(); if (localCheckpoint < recoverUpToSeqNo) { try (Translog.Snapshot snapshot = translog.newSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) { opsRecovered = translogRecoveryRunner.run(this, snapshot); } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } } else { opsRecovered = 0; } assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); logger.trace(() -> new ParameterizedMessage( "flushing post recovery from translog: ops recovered [{}], current translog generation [{}]", opsRecovered, translog.currentFileGeneration())); flush(false, true); if (opsRecovered > 0) { refresh("translog_recovery"); } translog.trimUnreferencedReaders(); }

Target:
private void recoverFromTranslogInternal(TranslogRecoveryRunner translogRecoveryRunner, long recoverUpToSeqNo) throws IOException { final int opsRecovered; final long localCheckpoint = getProcessedLocalCheckpoint(); if (localCheckpoint < recoverUpToSeqNo) { try (Translog.Snapshot snapshot = translog.newSnapshot(localCheckpoint + 1, recoverUpToSeqNo)) { opsRecovered = translogRecoveryRunner.run(this, snapshot); } catch (Exception e) { throw new EngineException(shardId, "failed to recover from translog", e); } } else { opsRecovered = 0; } assert pendingTranslogRecovery.get() : "translogRecovery is not pending but should be"; pendingTranslogRecovery.set(false); logger.trace(() -> new ParameterizedMessage( "flushing post recovery from translog: ops recovered [{}], current translog generation [{}]", opsRecovered, translog.currentFileGeneration())); flush(false, true); translog.trimUnreferencedReaders(); }
Source:
public void doesNotReuseResiduesIfNotNeeded() { givenGeneratorHasModulus(3); requestResiduesAndAssertBalanced(3); }

Target:
public void doesNotReuseResiduesIfNotNeeded() { setupGeneratorWithModulus(3); requestResiduesAndAssertEachUsedOnce(3); }
Source:
public static void main(String[] args) { LoadBalancerExtension extension = null; try { File configFile = new File(getFilePathOfConfigFile(Constants.CONFIG_FILE_NAME)); OMElement documentElement = AxiomXpathParserUtil.parse(configFile); GCEConfigParser.parse(documentElement); PropertyConfigurator.configure(getFilePathOfConfigFile(GCEContext.getInstance().getLog4jPropertiesFileName())); if (log.isInfoEnabled()) { log.info("GCE extension started"); } final Thread mainThread = Thread.currentThread(); final LoadBalancerExtension finalExtension = extension; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { if (finalExtension != null) { log.info("GCE instance is stopping..."); finalExtension.stop(); } mainThread.join(); } catch (Exception e) { log.error(e); } } }); executorService = StratosThreadPool.getExecutorService("gce.extension.thread.pool", 10); TopologyProvider topologyProvider = new TopologyProvider(); GCEStatisticsReader statisticsReader = GCEContext.getInstance().isCEPStatsPublisherEnabled() ? new GCEStatisticsReader(topologyProvider) : null; extension = new LoadBalancerExtension(new GCELoadBalancer(), statisticsReader, topologyProvider); extension.setExecutorService(executorService); extension.execute(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } if (extension != null) { log.info("Shutting GCE instance..."); extension.stop(); } } }

Target:
public static void main(String[] args) { LoadBalancerExtension extension = null; try { File configFile = new File(getFilePathOfConfigFile(Constants.CONFIG_FILE_NAME)); OMElement documentElement = AxiomXpathParserUtil.parse(configFile); GCEConfigParser.parse(documentElement); PropertyConfigurator.configure(System.getProperty("log4j.properties.file.path")); if (log.isInfoEnabled()) { log.info("GCE extension started"); } final Thread mainThread = Thread.currentThread(); final LoadBalancerExtension finalExtension = extension; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { if (finalExtension != null) { log.info("GCE instance is stopping..."); finalExtension.stop(); } mainThread.join(); } catch (Exception e) { log.error(e); } } }); executorService = StratosThreadPool.getExecutorService("gce.extension.thread.pool", 10); TopologyProvider topologyProvider = new TopologyProvider(); GCEStatisticsReader statisticsReader = GCEContext.getInstance().isCEPStatsPublisherEnabled() ? new GCEStatisticsReader(topologyProvider) : null; extension = new LoadBalancerExtension(new GCELoadBalancer(), statisticsReader, topologyProvider); extension.setExecutorService(executorService); extension.execute(); } catch (Exception e) { if (log.isErrorEnabled()) { log.error(e); } if (extension != null) { log.info("Shutting GCE instance..."); extension.stop(); } } }
Source:
private static ConcurrentMap<String, String> asMap( final Iterable<String> args) throws IllegalStateException { final ConcurrentMap<String, String> map = new ConcurrentHashMap<String, String>(0); final Pattern ptn = Pattern.compile("--([a-z\\-]+)(=.+)?"); for (final String arg : args) { final Matcher matcher = ptn.matcher(arg); if (!matcher.matches()) { throw new IllegalStateException( String.format("can't parse this argument: '%s'", arg) ); } final String value = matcher.group(2); if (value == null) { map.put(matcher.group(1), ""); } else { map.put(matcher.group(1), value.substring(1)); } } return map; }

Target:
private static Map<String, String> asMap(final Iterable<String> args) { final Map<String, String> map = new HashMap<String, String>(0); final Pattern ptn = Pattern.compile("--([a-z\\-]+)(=.+)?"); for (final String arg : args) { final Matcher matcher = ptn.matcher(arg); if (!matcher.matches()) { throw new IllegalStateException( String.format("can't parse this argument: '%s'", arg) ); } final String value = matcher.group(2); if (value == null) { map.put(matcher.group(1), ""); } else { map.put(matcher.group(1), value.substring(1)); } } return map; }
Source:
public void setMessage(String message) { messageLabel.getElement().setInnerHTML(message != null ? message.replace("\n", "<br/>") : ""); }

Target:
public void setMessage(String message) { messageHTML.setHTML(SafeHtmlUtils.fromString(message != null ? message : "").asString().replace("\n", "<br>")); }
Source:
protected SimpleDictionaryDialog(@Nullable SimpleDictionary dictionary, MutableReferenceDataCatalog catalog, WindowContext windowContext) { super(windowContext, ImageManager.get().getImage(IconUtils.DICTIONARY_SIMPLE_IMAGEPATH)); _originalDictionary = dictionary; _catalog = catalog; _nameTextField = WidgetFactory.createTextField("Dictionary name"); _valuesTextArea = WidgetFactory.createTextArea("Values"); _valuesTextArea.setRows(14); _caseSensitiveCheckBox = new DCCheckBox<>("Case-sensitive?", false); _caseSensitiveCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _caseSensitiveCheckBox.setOpaque(false); _caseSensitiveCheckBox.setToolTipText("Only match on dictionary terms when text-case is the same."); if (dictionary != null) { _nameTextField.setText(dictionary.getName()); Collection<String> values = dictionary.getValueSet(); StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (first) { first = false; } else { sb.append('\n'); } sb.append(value); } _valuesTextArea.setText(sb.toString()); _caseSensitiveCheckBox.setSelected(dictionary.isCaseSensitive()); } }

Target:
protected SimpleDictionaryDialog(@Nullable SimpleDictionary dictionary, MutableReferenceDataCatalog catalog, WindowContext windowContext) { super(windowContext, ImageManager.get().getImage(IconUtils.DICTIONARY_SIMPLE_IMAGEPATH)); _originalDictionary = dictionary; _catalog = catalog; _nameTextField = WidgetFactory.createTextField("Dictionary name"); _valuesTextArea = WidgetFactory.createTextArea("Values"); _valuesTextArea.setRows(14); _caseSensitiveCheckBox = new DCCheckBox<>("Case-sensitive?", false); _caseSensitiveCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _caseSensitiveCheckBox.setOpaque(false); _caseSensitiveCheckBox.setToolTipText("Only match on dictionary terms when text-case is the same."); if (dictionary != null) { _nameTextField.setText(dictionary.getName()); final Collection<String> values = dictionary.getValueSet(); final StringBuilder sb = new StringBuilder(); boolean first = true; for (String value : values) { if (first) { first = false; } else { sb.append('\n'); } sb.append(value); } _valuesTextArea.setText(sb.toString()); _caseSensitiveCheckBox.setSelected(dictionary.isCaseSensitive()); } }
Source:
protected Pool initSourceObject() { Pool source = new Pool(); source.setId("pool-id"); source.setQuantity(1L); source.setStartDate(new Date()); source.setEndDate(new Date()); Map<String, String> attributes = new HashMap<>(); attributes.put(Pool.Attributes.SOURCE_POOL_ID, "true"); source.setAttributes(attributes); source.setRestrictedToUsername("restricted-to-username-value"); source.setConsumed(6L); source.setAttribute(Pool.Attributes.DEVELOPMENT_POOL, "true"); Product product = new Product(); product.setId("product-id-2"); product.setName("product-name-2"); source.setProduct(product); Product derivedProduct = new Product(); derivedProduct.setId("derived-product-id-2"); derivedProduct.setName("derived-product-name-2"); derivedProduct.setAttributes(new HashMap<>()); derivedProduct.setAttribute(Product.Attributes.ARCHITECTURE, "POWER"); derivedProduct.setAttribute(Product.Attributes.STACKING_ID, "2221"); source.setDerivedProduct(derivedProduct); Product providedProd = new Product(); providedProd.setId("provided-product-id-1"); providedProd.setName("provided-product-name-1"); source.getProduct().addProvidedProduct(providedProd); Product derivedProvidedProd = new Product(); derivedProvidedProd.setId("derived-provided-product-id-1"); derivedProvidedProd.setName("derived-provided-product-name-1"); source.getDerivedProduct().addProvidedProduct(derivedProvidedProd); return source; }

Target:
protected Pool initSourceObject() { Pool source = new Pool(); source.setId("pool-id"); source.setQuantity(1L); source.setStartDate(new Date()); source.setEndDate(new Date()); Map<String, String> attributes = new HashMap<>(); attributes.put(Pool.Attributes.SOURCE_POOL_ID, "true"); source.setAttributes(attributes); source.setRestrictedToUsername("restricted-to-username-value"); source.setConsumed(6L); source.setAttribute(Pool.Attributes.DEVELOPMENT_POOL, "true"); Product providedProd = new Product(); providedProd.setId("provided-product-id-1"); providedProd.setName("provided-product-name-1"); Product product = new Product(); product.setId("product-id-2"); product.setName("product-name-2"); product.addProvidedProduct(providedProd); source.setProduct(product); Product derivedProvidedProd = new Product(); derivedProvidedProd.setId("derived-provided-product-id-1"); derivedProvidedProd.setName("derived-provided-product-name-1"); Product derivedProduct = new Product(); derivedProduct.setId("derived-product-id-2"); derivedProduct.setName("derived-product-name-2"); derivedProduct.setAttributes(new HashMap<>()); derivedProduct.setAttribute(Product.Attributes.ARCHITECTURE, "POWER"); derivedProduct.setAttribute(Product.Attributes.STACKING_ID, "2221"); derivedProduct.addProvidedProduct(derivedProvidedProd); source.setDerivedProduct(derivedProduct); return source; }
Source:
public Future<Void> login(final String user, final String password) { return (Future<Void>) executor.submit(new Runnable() { @Override public void run() { try { receiveTokenFromKeycloak("client_id=" + appName + "&username=" + user + "&password=" + password + "&grant_type=password"); } catch (IOException e) { throw new DolphinRuntimeException("Error in security", e); } } }); }

Target:
public Future<Void> login(final String user, final String password) { return (Future<Void>) executor.submit(() -> { try { receiveTokenFromKeycloak("client_id=" + appName + "&username=" + user + "&password=" + password + "&grant_type=password"); } catch (IOException e) { throw new DolphinRuntimeException("Error in security", e); } }); }
Source:
public List<Encounter> getTransferHistory(Patient patient) { EncounterService encounterService = Context.getEncounterService(); Collection<EncounterType> encounterTypes = new ArrayList<>(); List<Encounter> encounters = new ArrayList<>(); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_IN.uuid())); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_OUT.uuid())); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder().setPatient(patient).setIncludeVoided(false).setEncounterTypes(encounterTypes).createEncounterSearchCriteria(); if (!encounterTypes.isEmpty()) { encounters = encounterService.getEncounters(encounterSearchCriteria); } return encounters; }

Target:
public List<Encounter> getTransferHistory(Patient patient) { EncounterService encounterService = Context.getEncounterService(); Collection<EncounterType> encounterTypes = new ArrayList<>(); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_IN.uuid())); encounterTypes.add(encounterService.getEncounterTypeByUuid(TRANSFER_OUT.uuid())); EncounterSearchCriteria encounterSearchCriteria = new EncounterSearchCriteriaBuilder().setPatient(patient).setIncludeVoided(false).setEncounterTypes(encounterTypes).createEncounterSearchCriteria(); List<Encounter> encounters = encounterService.getEncounters(encounterSearchCriteria); return encounters; }
Source:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { try { return Timestamp.valueOf(LocalDateTime.parse(defaultStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]"))); } catch (NumberFormatException e) { throw SqlExceptionUtil.create("Problems with field " + fieldType + " parsing default LocalDateTime value: " + defaultStr, e); } }

Target:
public Object parseDefaultString(FieldType fieldType, String defaultStr) throws SQLException { return Timestamp.valueOf((LocalDateTime) super.parseDefaultString(fieldType, defaultStr)); }
Source:
public boolean[] encode(String contents) { int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); if (indexInString < 0) { contents = tryToConvertToExtendedMode(contents); length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length + " (extended full ascii mode)"); } break; } } int[] widths = new int[9]; int codeWidth = 24 + 1 + length; for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); for (int width : widths) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.ASTERISK_ENCODING, widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.ASTERISK_ENCODING, widths); appendPattern(result, pos, widths, true); return result; }

Target:
public boolean[] encode(String contents) { int length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length); } for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); if (indexInString < 0) { contents = tryToConvertToExtendedMode(contents); length = contents.length(); if (length > 80) { throw new IllegalArgumentException( "Requested contents should be less than 80 digits long, but got " + length + " (extended full ASCII mode)"); } break; } } int[] widths = new int[9]; int codeWidth = 24 + 1 + length; for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); for (int width : widths) { codeWidth += width; } } boolean[] result = new boolean[codeWidth]; toIntArray(Code39Reader.ASTERISK_ENCODING, widths); int pos = appendPattern(result, 0, widths, true); int[] narrowWhite = {1}; pos += appendPattern(result, pos, narrowWhite, false); for (int i = 0; i < length; i++) { int indexInString = Code39Reader.ALPHABET_STRING.indexOf(contents.charAt(i)); toIntArray(Code39Reader.CHARACTER_ENCODINGS[indexInString], widths); pos += appendPattern(result, pos, widths, true); pos += appendPattern(result, pos, narrowWhite, false); } toIntArray(Code39Reader.ASTERISK_ENCODING, widths); appendPattern(result, pos, widths, true); return result; }
Source:
private boolean executeSshReboot(String version) { try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream() ) { try { log.info("Opening SSH reboot session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH reboot command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshHostRebootCommand, version), null, cmdOut, cmdErr ); return true; } catch (Exception ex) { log.error("SSH reboot command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException"); log.debug("Exception", e); } return false; }

Target:
private boolean executeSshReboot(String version) { try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream() ) { try { log.info("Opening SSH reboot session on host {}", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH reboot command on host {}", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshHostRebootCommand, version), null, cmdOut, cmdErr ); return true; } catch (Exception ex) { log.error("SSH reboot command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch (IOException e) { log.error("Error opening SSH connection to '{}': {}", getVds().getHostName(), e.getMessage()); log.debug("Exception", e); } return false; }
Source:
public void runScript(String scriptContent, Consumer<Exception> errorCallback) { final String scriptContenti18n = "var tr = Packages.org.phoenicis.configuration.localisation.Localisation.tr;" + scriptContent; nashornEngineFactory.createEngine().eval(scriptContenti18n, errorCallback); }

Target:
public void runScript(String scriptContent, Consumer<Exception> errorCallback) { nashornEngineFactory.createEngine().eval(scriptContent, errorCallback); }
Source:
public Set<Integer> getLinesWithNoSonar() { return noSonar; }

Target:
public Set<Integer> getLinesWithNoSonar() { return ImmutableSet.copyOf(noSonar); }
Source:
public RankingWidget(Context context, QuestionDetails prompt) { super(context, prompt); getOrderedItems(); setUpLayout(); }

Target:
public RankingWidget(Context context, QuestionDetails prompt) { super(context, prompt); setUpLayout(getOrderedItems()); }
Source:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { if (launch instanceof GdbLaunch) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); } return null; }

Target:
protected Sequence getServicesSequence(DsfSession session, ILaunch launch, IProgressMonitor rm) { return new ServicesLaunchSequence(session, (GdbLaunch)launch, rm); }
Source:
protected void doInit() { oldNumaNodeIds = LinqUtils.transformToList(getVmNumaNodesForValidation(), new Function<VmNumaNode, Guid>() { @Override public Guid eval(VmNumaNode vmNumaNode) { return vmNumaNode.getId(); } }); setVmNumaNodesForValidation(getParameters().getVmNumaNodeList()); }

Target:
protected void doInit() { oldNumaNodeIds = Entities.getIds(getVmNumaNodesForValidation()); setVmNumaNodesForValidation(getParameters().getVmNumaNodeList()); }
Source:
public String getProductName(String languageCode) { if (!languageCode.equals("en") && additionalProperties.get("product_name_" + languageCode) != null && isNotBlank(additionalProperties.get("product_name_" + languageCode).toString())) { return additionalProperties.get("product_name_" + languageCode) .toString() .replace("\\'", "'") .replace("&quot", "'"); } else if (additionalProperties.get("product_name_en") != null && isNotBlank(additionalProperties.get("product_name_en").toString())) { return additionalProperties.get("product_name_en") .toString() .replace("\\'", "'") .replace("&quot", "'"); } else { return getProductName(); } }

Target:
public String getProductName(String languageCode) { String result = getFieldHelper("product_name", languageCode); if (result != null) { return result; } else { return getProductName(); } }
Source:
public static JSONObject read(final String url) throws IOException, JSONException { final InputStream is = new URL(url).openStream(); try { final BufferedReader rd = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF-8"))); final String jsonText = readAll(rd); final JSONObject json = new JSONObject(jsonText); return json; } finally { is.close(); } }

Target:
public static JSONObject read(final String url) throws IOException, JSONException { final InputStream is = new URL(url).openStream(); try { final BufferedReader rd = new BufferedReader( new InputStreamReader(is, Charset.forName("UTF-8"))); final String jsonText = readAll(rd); final JSONObject json = new JSONObject(jsonText); return json; } finally { try { is.close(); } catch (Throwable ex) { } } }
Source:
public static Partition fromProto(alluxio.grpc.table.layout.hive.PartitionInfo info) { Partition.Builder builder = Partition.builder() .setColumns(info.getDataColsList().stream().map(AlluxioProtoUtils::fromProto).collect(Collectors.toList())) .setDatabaseName(info.getDbName()) .setParameters(info.getParametersMap()) .setValues(Lists.newArrayList(info.getValuesList())) .setTableName(info.getTableName()); builder.getStorageBuilder() .setSkewed(info.getStorage().getSkewed()) .setStorageFormat(fromProto(info.getStorage().getStorageFormat())) .setLocation(info.getStorage().getLocation()) .setBucketProperty(info.getStorage().hasBucketProperty() ? fromProto(info.getStorage().getBucketProperty()) : Optional.empty()) .setSerdeParameters(info.getStorage().getStorageFormat().getSerdelibParametersMap()); return builder.build(); }

Target:
public static Partition fromProto(alluxio.grpc.table.layout.hive.PartitionInfo info) { Partition.Builder builder = Partition.builder() .setColumns(info.getDataColsList().stream().map(AlluxioProtoUtils::fromProto).collect(toImmutableList())) .setDatabaseName(info.getDbName()) .setParameters(info.getParametersMap()) .setValues(Lists.newArrayList(info.getValuesList())) .setTableName(info.getTableName()); builder.getStorageBuilder() .setSkewed(info.getStorage().getSkewed()) .setStorageFormat(fromProto(info.getStorage().getStorageFormat())) .setLocation(info.getStorage().getLocation()) .setBucketProperty(info.getStorage().hasBucketProperty() ? fromProto(info.getStorage().getBucketProperty()) : Optional.empty()) .setSerdeParameters(info.getStorage().getStorageFormat().getSerdelibParametersMap()); return builder.build(); }