auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object[] getElements(final Object inputElement) { if (needsRecompute) { needsRecompute = false; FileDiffInput input = currentInput; if (input != null) { cancel(); FileDiffLoader job = new FileDiffLoader(input, markTreeFilter); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (!event.getResult().isOK()) { return; } UIJob updater = new UIJob(MessageFormat.format( UIText.FileDiffContentProvider_updatingFileDiffs, input.getCommit().getName())) { @Override public IStatus runInUIThread( IProgressMonitor monitor) { if (!viewer.getControl().isDisposed() && loader == job) { diff = job.getDiffs(); viewer.refresh(); FileDiff interesting = getFirstInterestingElement(); if (interesting != null) { if (input.isSelectMarked()) { viewer.setSelection( new StructuredSelection( interesting), true); } else { viewer.reveal(interesting); } } } return Status.OK_STATUS; } }; updater.schedule(); } }); job.setUser(false); job.setSystem(true); loader = job; loader.schedule(); } else { diff = null; } } return diff != null ? diff : new Object[0]; }

Target:
public Object[] getElements(final Object inputElement) { if (!needsRecompute) { return diff != null ? diff : new Object[0]; } needsRecompute = false; FileDiffInput input = currentInput; if (input == null) { diff = null; return new Object[0]; } cancel(); FileDiffLoader job = new FileDiffLoader(input, markTreeFilter); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent event) { if (!event.getResult().isOK()) { return; } UIJob updater = new UpdateJob(MessageFormat.format( UIText.FileDiffContentProvider_updatingFileDiffs, input.getCommit().getName()), job); updater.schedule(); } }); job.setUser(false); job.setSystem(true); loader = job; loader.schedule(); return new Object[0]; }
Source:
public static <T> CompositeSubscription manageMultiViewModel( final Observable<? extends T> external, final Consumer<? super T> onExternal, final Scheduler externalScheduler, final Observable<? extends T> internal, final Consumer<? super T> onInternal, final Scheduler internalScheduler ) { final SupressObservable<? extends T> es = new SupressObservable<>(external, externalScheduler, SUPPRESS_LEN); final SupressObservable<? extends T> is = new SupressObservable<>(internal, internalScheduler, SUPPRESS_LEN); final CompositeSubscription sub = new CompositeSubscription(); sub.addAll( es.get().subscribe(v -> { is.supress(); onExternal.accept(v); }), is.get().subscribe(v -> { es.supress(); onInternal.accept(v); })); return sub; }

Target:
public static <T> CompositeSubscription manageMultiViewModel( final Observable<? extends T> external, final Consumer<? super T> onExternal, final Scheduler externalScheduler, final Observable<? extends T> internal, final Consumer<? super T> onInternal, final Scheduler internalScheduler ) { final SuppressObservable<? extends T> es = new SuppressObservable<>(external, externalScheduler, SUPPRESS_LEN); final SuppressObservable<? extends T> is = new SuppressObservable<>(internal, internalScheduler, SUPPRESS_LEN); final CompositeSubscription sub = new CompositeSubscription(); sub.addAll( es.get().subscribe(v -> { is.supress(); onExternal.accept(v); }), is.get().subscribe(v -> { es.supress(); onInternal.accept(v); })); return sub; }
Source:
private static long parseLimit(String limitStr, Map<String, Long> cvt) throws RetentionLimitException { if (StringUtils.isEmpty(limitStr)) { throw new RetentionLimitException("empty retention limit"); } String parse = limitStr.trim().toLowerCase(); if (parse.length() <= 2) { throw new RetentionLimitException("\"" + limitStr + "\" is too short for a retention limit"); } String qualifier = parse.substring(parse.length() - 2); if (!cvt.keySet().contains(qualifier)) { throw new RetentionLimitException("\"" + qualifier + "\" is not a valid limit qualifier: " + cvt.keySet() + " are the valid values"); } String valStr = parse.substring(0, parse.length() - 2); long limit = 0; try { limit = Long.parseLong(valStr.trim()); limit *= cvt.get(qualifier); } catch (Exception ex) { throw new RetentionLimitException("Failed to parse\"" + limitStr + "\": " + ex); } if (limit <= 0) { throw new RetentionLimitException("A retention limit must have a positive value"); } return limit; }

Target:
private static long parseLimit(String limitStr, Map<String, Long> cvt) throws RetentionLimitException { if (StringUtils.isEmpty(limitStr)) { throw new RetentionLimitException("empty retention limit"); } String parse = limitStr.trim().toLowerCase(); if (parse.length() <= 2) { throw new RetentionLimitException("\"" + limitStr + "\" is too short for a retention limit"); } String qualifier = parse.substring(parse.length() - 2); if (!cvt.keySet().contains(qualifier)) { throw new RetentionLimitException("\"" + qualifier + "\" is not a valid limit qualifier: " + cvt.keySet() + " are the valid values"); } String valStr = parse.substring(0, parse.length() - 2); long limit = 0; try { limit = Long.parseLong(valStr.trim()); limit *= cvt.get(qualifier); } catch (NumberFormatException ex) { throw new RetentionLimitException("Failed to parse\"" + limitStr + "\": " + ex); } if (limit <= 0) { throw new RetentionLimitException("A retention limit must have a positive value"); } return limit; }
Source:
public void tokenRevocation(@PathVariable("id") final String id, @RequestHeader("Authorization") final String authorization) { User user = resourceServerConnector.getUserById(id); String searchKey = new User.Builder(user.getUserName()).setId(id).build().toString(); Collection<OAuth2AccessToken> tokens = tokenServices.findTokensByUserName(searchKey); if (tokens == null) { return; } for (OAuth2AccessToken token : new ArrayList<OAuth2AccessToken>(tokens)) { tokenServices.revokeToken(token.getValue()); } }

Target:
public void tokenRevocation(@PathVariable("id") final String id, @RequestHeader("Authorization") final String authorization) { User user = resourceServerConnector.getUserById(id); String searchKey = new User.Builder(user.getUserName()).setId(id).build().toString(); Collection<OAuth2AccessToken> tokens = tokenServices.findTokensByUserName(searchKey); for (OAuth2AccessToken token : new ArrayList<OAuth2AccessToken>(tokens)) { tokenServices.revokeToken(token.getValue()); } }
Source:
public void onResume() { super.onResume(); themeUtils.onResume(this); setupStatusView(); initializeGpsDataCollection(); }

Target:
public void onResume() { super.onResume(); themeUtils.onResume(this); setupStatusView(); initializeGPSDataCollection(); }
Source:
public void testCreateLargeMatrix(){ final int numRows = 2500000; final int numCols = 10; final double mean = 3e-7; final RealMatrix bigCounts = new Array2DRowRealMatrix(numRows, numCols); final RandomDataGenerator randomDataGenerator = new RandomDataGenerator(); randomDataGenerator.reSeed(337337337); bigCounts.walkInColumnOrder(new DefaultRealMatrixChangingVisitor() { @Override public double visit(int row, int column, double value) { return randomDataGenerator.nextGaussian(mean, 1e-9); } }); final File tempOutputHD5 = IOUtils.createTempFile("big-ol-", ".hd5"); final HDF5File hdf5File = new HDF5File(tempOutputHD5, HDF5File.OpenMode.CREATE); final String hdf5Path = "/test/m"; hdf5File.makeDoubleMatrix(hdf5Path, bigCounts.getData()); hdf5File.close(); final HDF5File hdf5FileForReading = new HDF5File(tempOutputHD5, HDF5File.OpenMode.READ_ONLY); final double[][] result = hdf5FileForReading.readDoubleMatrix(hdf5Path); Assert.assertTrue(result.length == numRows); Assert.assertTrue(result[0].length == numCols); final RealMatrix readMatrix = new Array2DRowRealMatrix(result); final double[] colMeans = GATKProtectedMathUtils.columnMeans(readMatrix); for (double m: colMeans) { Assert.assertEquals(m, mean, 1e-4); } }

Target:
public void testCreateLargeMatrix(){ final int numRows = 2500000; final int numCols = 10; final double mean = 3e-7; final double sigma = 1e-9; final RealMatrix bigCounts = createMatrixOfGaussianValues(numRows, numCols, mean, sigma); final File tempOutputHD5 = IOUtils.createTempFile("big-ol-", ".hd5"); final HDF5File hdf5File = new HDF5File(tempOutputHD5, HDF5File.OpenMode.CREATE); final String hdf5Path = "/test/m"; hdf5File.makeDoubleMatrix(hdf5Path, bigCounts.getData()); hdf5File.close(); final HDF5File hdf5FileForReading = new HDF5File(tempOutputHD5, HDF5File.OpenMode.READ_ONLY); final double[][] result = hdf5FileForReading.readDoubleMatrix(hdf5Path); final RealMatrix resultAsRealMatrix = new Array2DRowRealMatrix(result); Assert.assertTrue(resultAsRealMatrix.getRowDimension() == numRows); Assert.assertTrue(resultAsRealMatrix.getColumnDimension() == numCols); final RealMatrix readMatrix = new Array2DRowRealMatrix(result); PoNTestUtils.assertEqualsMatrix(readMatrix, bigCounts, false); }
Source:
private RepositoryMapping(final @NonNull IContainer mappedContainer, final @NonNull IPath location, final @NonNull File gitDir) { container = mappedContainer; containerPathString = container.getProjectRelativePath() .toPortableString(); if (!gitDir.isAbsolute()) { gitDirPathString = Path.fromOSString(gitDir.getPath()) .removeTrailingSeparator().toPortableString(); return; } java.nio.file.Path gPath = gitDir.toPath(); java.nio.file.Path lPath = location.toFile().toPath(); if (lPath.getNameCount() > 0 && gPath.getNameCount() > 0 && gPath.getRoot() != null && gPath.getRoot().equals(lPath.getRoot()) && gPath.getName(0).equals(lPath.getName(0))) { gPath = lPath.relativize(gPath); } gitDirPathString = Path.fromOSString(gPath.toString()) .removeTrailingSeparator().toPortableString(); }

Target:
private RepositoryMapping(final @NonNull IContainer mappedContainer, final @NonNull IPath location, final @NonNull File gitDir) { container = mappedContainer; containerPathString = container.getProjectRelativePath() .toPortableString(); if (!gitDir.isAbsolute()) { gitDirPathString = Path.fromOSString(gitDir.getPath()) .removeTrailingSeparator().toPortableString(); return; } java.nio.file.Path gPath = gitDir.toPath(); java.nio.file.Path lPath = location.toFile().toPath(); if (lPath.getNameCount() > 0 && gPath.getNameCount() > 0 && (gPath.getRoot() == lPath.getRoot() || gPath.getRoot() != null && gPath.getRoot().equals(lPath.getRoot())) && gPath.getName(0).equals(lPath.getName(0))) { gPath = lPath.relativize(gPath); } gitDirPathString = Path.fromOSString(gPath.toString()) .removeTrailingSeparator().toPortableString(); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); if (mShowNewEditor || mShowAztecEditor || mShowGutenbergEditor) { inflater.inflate(R.menu.edit_post, menu); } else { inflater.inflate(R.menu.edit_post_legacy, menu); } return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); if (isModernEditor()) { inflater.inflate(R.menu.edit_post, menu); } else { inflater.inflate(R.menu.edit_post_legacy, menu); } return true; }
Source:
public Double getTruncatedMean(double lowerQuantile, double upperQuantile) { double sum = 0; double count = 0; double mean = 0; compress(); if (totalWeight == 0 || lowerQuantile >= upperQuantile) { return null; } AtomicDouble meanResult = new AtomicDouble(); double lowerRank = lowerQuantile * totalWeight; double upperRank = upperQuantile * totalWeight; for (int i = 0; i < activeCentroids; i++) { double centroidWeight = weight[i]; sum += centroidWeight; double amountOverLower = Math.max(sum - lowerRank, 0); double amountOverUpper = Math.max(sum - upperRank, 0); centroidWeight = Math.max(0, Math.min(Math.min(centroidWeight, amountOverLower), centroidWeight - amountOverUpper)); if (amountOverLower > 0) { mean = weightedAverage(mean, count, this.mean[i], centroidWeight); count += centroidWeight; } if (amountOverUpper > 0 || sum == totalWeight) { meanResult.set(mean); break; } } return meanResult.get(); }

Target:
public double getTruncatedMean(double lowerQuantile, double upperQuantile) { double sum = 0; double count = 0; double mean = 0; compress(); checkArgument(totalWeight != 0, "t-digest is empty"); checkArgument(lowerQuantile < upperQuantile, "lower quantile must be strictly less than upper quantile"); double lowerRank = lowerQuantile * totalWeight; double upperRank = upperQuantile * totalWeight; for (int i = 0; i < activeCentroids; i++) { double centroidWeight = weight[i]; sum += centroidWeight; double amountOverLower = Math.max(sum - lowerRank, 0); double amountOverUpper = Math.max(sum - upperRank, 0); centroidWeight = Math.max(0, Math.min(Math.min(centroidWeight, amountOverLower), centroidWeight - amountOverUpper)); if (amountOverLower > 0) { mean = weightedAverage(mean, count, this.mean[i], centroidWeight); count += centroidWeight; } if (amountOverUpper > 0 || sum == totalWeight) { break; } } return mean; }
Source:
public static ReplicaMetadataResponseInfo readFrom(DataInputStream stream, FindTokenHelper helper, ClusterMap clusterMap, short replicaMetadataResponseVersion) throws IOException, ReflectiveOperationException { PartitionId partitionId = clusterMap.getPartitionIdFromStream(stream); ServerErrorCode error = ServerErrorCode.values()[stream.readShort()]; if (error != ServerErrorCode.No_Error) { return new ReplicaMetadataResponseInfo(partitionId, error); } else { FindToken token = helper.getFindTokenFromStream(stream); MessageInfoAndMetadataListSerde messageInfoAndMetadataList = MessageInfoAndMetadataListSerde.deserializeMessageInfoAndMetadataList(stream, clusterMap, getMessageInfoAndMetadataListSerDeVersion(replicaMetadataResponseVersion)); long remoteReplicaLag = stream.readLong(); return new ReplicaMetadataResponseInfo(partitionId, token, messageInfoAndMetadataList.getMessageInfoList(), remoteReplicaLag, replicaMetadataResponseVersion); } }

Target:
public static ReplicaMetadataResponseInfo readFrom(DataInputStream stream, FindTokenHelper helper, ClusterMap clusterMap, short replicaMetadataResponseVersion) throws IOException { PartitionId partitionId = clusterMap.getPartitionIdFromStream(stream); ReplicaType replicaType; if (replicaMetadataResponseVersion == ReplicaMetadataResponse.REPLICA_METADATA_RESPONSE_VERSION_V_6) { replicaType = ReplicaType.values()[stream.readShort()]; } else { replicaType = ReplicaType.DISK_BACKED; } ServerErrorCode error = ServerErrorCode.values()[stream.readShort()]; if (error != ServerErrorCode.No_Error) { return new ReplicaMetadataResponseInfo(partitionId, replicaType, error, replicaMetadataResponseVersion); } else { FindTokenFactory findTokenFactory = helper.getFindTokenFactoryFromReplicaType(replicaType); FindToken token = findTokenFactory.getFindToken(stream); MessageInfoAndMetadataListSerde messageInfoAndMetadataList = MessageInfoAndMetadataListSerde.deserializeMessageInfoAndMetadataList(stream, clusterMap, getMessageInfoAndMetadataListSerDeVersion(replicaMetadataResponseVersion)); long remoteReplicaLag = stream.readLong(); return new ReplicaMetadataResponseInfo(partitionId, replicaType, token, messageInfoAndMetadataList.getMessageInfoList(), remoteReplicaLag, replicaMetadataResponseVersion); } }
Source:
public void testStartFetcherWith_NullToken_ShouldStartFromBeginning() throws InterruptedException { CountDownLatch messageCounter = new CountDownLatch(1); KafkaTrackingToken endToken = KafkaTrackingToken.newInstance(new HashMap<Integer, Long>() {{ put(0, 0L); }}); String topic = "foo"; ConsumerFactory<String, String> cf = mockConsumerFactory(topic); SortedKafkaMessageBuffer<KafkaEventMessage> buffer = new SortedKafkaMessageBuffer<>(1); Fetcher testSubject = AsyncFetcher.<String, String>builder() .consumerFactory(cf) .bufferFactory(() -> buffer) .executorService(newSingleThreadExecutor()) .messageConverter(new ValueConverter()) .topic(topic) .consumerRecordCallback(countMessage(messageCounter)) .pollTimeout(3000, TimeUnit.MILLISECONDS) .build(); testSubject.start(null); messageCounter.await(); assertThat(buffer.size()).isOne(); assertThat(currentToken).isEqualTo(endToken); testSubject.shutdown(); }

Target:
public void testStartFetcherWith_NullToken_ShouldStartFromBeginning() throws InterruptedException { CountDownLatch messageCounter = new CountDownLatch(1); KafkaTrackingToken endToken = KafkaTrackingToken.newInstance(new HashMap<Integer, Long>() {{ put(0, 0L); }}); String topic = "foo"; ConsumerFactory<String, String> consumerFactory = mockConsumerFactory(topic); SortedKafkaMessageBuffer<KafkaEventMessage> buffer = new SortedKafkaMessageBuffer<>(1); Fetcher testSubject = AsyncFetcher.<String, String>builder() .consumerFactory(consumerFactory) .bufferFactory(() -> buffer) .executorService(newSingleThreadExecutor()) .messageConverter(new ValueConverter()) .topic(topic) .consumerRecordCallback(countMessage(messageCounter)) .pollTimeout(3000, TimeUnit.MILLISECONDS) .build(); testSubject.start(null); messageCounter.await(); assertThat(buffer.size()).isOne(); assertThat(currentToken).isEqualTo(endToken); testSubject.shutdown(); }
Source:
public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCPlayerVelocityEvent) { if(key.equalsIgnoreCase("velocity")) { Vector3D v3d = ObjectGenerator.GetGenerator().vector(value, Target.UNKNOWN); Vector vector = new Vector(v3d.X(), v3d.Y(), v3d.Z()); ((MCPlayerVelocityEvent) event).setVelocity(vector); return true; } } return false; }

Target:
public boolean modifyEvent(String key, Construct value, BindableEvent event) { if(event instanceof MCPlayerVelocityEvent) { if(key.equalsIgnoreCase("velocity")) { Vector3D vector = ObjectGenerator.GetGenerator().vector(value, Target.UNKNOWN); ((MCPlayerVelocityEvent) event).setVelocity(vector); return true; } } return false; }
Source:
public void start(Xid xid, int flags) throws XAException { System.out.println("[" + Thread.currentThread().getName() + "] DummyXAResource (" + serverId + ") XA_START [" + xid + "] Flags=" + flags); }

Target:
public void start(Xid xid, int flags) throws XAException { }
Source:
public int setPaddingSize(int len) { if (buffer == null || buffer.length < offset + FIXED_HEADER_SIZE + len || len < 0 || len > 0xFF) { return -1; } buffer[offset] |= 0x20; buffer[offset + length - 1] = (byte) len; return 2; }

Target:
public boolean setPaddingSize(int len) { if (buffer == null || buffer.length < offset + FIXED_HEADER_SIZE + len || len < 0 || len > 0xFF) { return false; } buffer[offset] |= 0x20; buffer[offset + length - 1] = (byte) len; return true; }
Source:
public static void writeRecord(ObjectDataOutput out, Record record, Data dataValue) throws IOException { getById(record.getMatchingRecordReaderWriterId()).writeRecord(out, record, dataValue); }

Target:
public static void writeRecord(ObjectDataOutput out, Record record, Data dataValue) throws IOException { out.writeByte(record.getMatchingRecordReaderWriter().getId()); record.getMatchingRecordReaderWriter().writeRecord(out, record, dataValue); }
Source:
public Map<Guid, Integer> getHostsViolations(boolean enforcing, List<VDS> hosts, VM vm, PerHostMessages messages) { Map<Guid, Integer> hostViolations = new HashMap<>(); List<AffinityGroup> affinityGroups = affinityGroupDao.getAllAffinityGroupsByVmId(vm.getId()); if (affinityGroups.isEmpty()) { return hostViolations; } Map<Guid, VDS> hostMap = hosts.stream().collect(Collectors.toMap(VDS::getId, h -> h)); for (AffinityGroup affinityGroup : affinityGroups) { if (affinityGroup.isVdsEnforcing() == enforcing) { List vdsIds = affinityGroup.getVdsIds(); if (affinityGroup.isVdsPositive()) { hostMap.keySet().stream() .filter(host_id -> !vdsIds.contains(host_id)) .forEach(id -> { messages.addMessage(id, String.format("$affinityRules %1$s", "")); messages.addMessage(id, EngineMessage.VAR__DETAIL__AFFINITY_FAILED_POSITIVE.toString()); hostViolations.put(id, 1 + hostViolations.getOrDefault(id, INITIAL_HOST_SCORE)); }); } else { hostMap.keySet().stream() .filter(host_id -> vdsIds.contains(host_id)) .forEach(id -> { messages.addMessage(id, String.format("$affinityRules %1$s", "")); messages.addMessage(id, EngineMessage.VAR__DETAIL__AFFINITY_FAILED_NEGATIVE.toString()); hostViolations.put(id, 1 + hostViolations.getOrDefault(id, INITIAL_HOST_SCORE)); }); } } } return hostViolations; }

Target:
public Map<Guid, Integer> getHostsViolations(boolean enforcing, List<VDS> hosts, VM vm, PerHostMessages messages) { Map<Guid, Integer> hostViolations = new HashMap<>(); List<AffinityGroup> affinityGroups = affinityGroupDao.getAllAffinityGroupsByVmId(vm.getId()); if (affinityGroups.isEmpty()) { return hostViolations; } Map<Guid, VDS> hostMap = hosts.stream().collect(Collectors.toMap(VDS::getId, h -> h)); for (AffinityGroup affinityGroup : affinityGroups) { if (affinityGroup.isVdsEnforcing() == enforcing) { List<Guid> vdsIds = affinityGroup.getVdsIds(); if (affinityGroup.isVdsPositive()) { hostMap.keySet().stream() .filter(host_id -> !vdsIds.contains(host_id)) .forEach(id -> { messages.addMessage(id, String.format("$affinityRules %1$s", "")); messages.addMessage(id, EngineMessage.VAR__DETAIL__AFFINITY_FAILED_POSITIVE.toString()); hostViolations.put(id, 1 + hostViolations.getOrDefault(id, INITIAL_HOST_SCORE)); }); } else { hostMap.keySet().stream() .filter(host_id -> vdsIds.contains(host_id)) .forEach(id -> { messages.addMessage(id, String.format("$affinityRules %1$s", "")); messages.addMessage(id, EngineMessage.VAR__DETAIL__AFFINITY_FAILED_NEGATIVE.toString()); hostViolations.put(id, 1 + hostViolations.getOrDefault(id, INITIAL_HOST_SCORE)); }); } } } return hostViolations; }
Source:
public ScheduleBootstrapController scheduleBootstrapController() { return new ScheduleBootstrapController( workers.scheduleBootstrapTaskFactory(), persistence.channelStore(), executorService(2, "ScheduleBootstrapController"), scheduleBootstrapper() ); }

Target:
public ScheduleBootstrapController scheduleBootstrapController() { return new ScheduleBootstrapController( workers.scheduleBootstrapTaskFactory(), persistence.channelStore(), executorService(NUMBER_OF_SCHECHULE_CONTROLLER_THREADS, "ScheduleBootstrapController"), scheduleBootstrapper() ); }
Source:
protected AzureADToken refreshToken() throws IOException { LOG.debug("AADToken: refreshing custom based token"); AzureADToken azureADToken = new AzureADToken(); String accessToken = null; Exception ex; boolean succeeded = false; int retryCount = fetchTokenRetryCount; do { ex = null; try { accessToken = adaptee.getAccessToken(); LOG.trace("CustomTokenProvider Access token fetch was successful with retry count {}", retryCount); } catch (Exception e) { LOG.debug("CustomTokenProvider Access token fetch failed with retry count {}", retryCount); ex = e; } succeeded = (ex == null); retryCount--; } while (!succeeded && (retryCount) >= 0); if (!succeeded) { HttpException httpEx = new HttpException( -1, "", String.format("CustomTokenProvider getAccessToken threw %s : %s", ex.getClass().getTypeName(), ex.getMessage()), "", "", "" ); throw httpEx; } azureADToken.setAccessToken(accessToken); azureADToken.setExpiry(adaptee.getExpiryTime()); return azureADToken; }

Target:
protected AzureADToken refreshToken() throws IOException { LOG.debug("AADToken: refreshing custom based token"); AzureADToken azureADToken = new AzureADToken(); String accessToken = null; Exception ex; boolean succeeded = false; int retryCount = fetchTokenRetryCount; do { ex = null; try { accessToken = adaptee.getAccessToken(); LOG.trace("CustomTokenProvider Access token fetch was successful with retry count {}", (fetchTokenRetryCount - retryCount)); } catch (Exception e) { LOG.debug("CustomTokenProvider Access token fetch failed with retry count {}", (fetchTokenRetryCount - retryCount)); ex = e; } succeeded = (ex == null); retryCount--; } while (!succeeded && (retryCount) >= 0); if (!succeeded) { HttpException httpEx = new HttpException( -1, "", String.format("CustomTokenProvider getAccessToken threw %s : %s", ex.getClass().getTypeName(), ex.getMessage()), "", "", "" ); throw httpEx; } azureADToken.setAccessToken(accessToken); azureADToken.setExpiry(adaptee.getExpiryTime()); return azureADToken; }
Source:
public void write(byte[] ba, int off, int len) throws IOException { while(true) { if(lastWriteFuture.isDone() && !isClosed) { ByteBuffer bb = ByteBuffer.wrap(ba, off, len); lastWriteFuture = c.write(bb); return; } else { try { lastWriteFuture.get(1000, TimeUnit.MILLISECONDS); } catch (Exception e) { ExceptionUtils.handleException(e); } } } }

Target:
public void write(byte[] ba, int off, int len) throws IOException { while(true) { if(lastWriteFuture.isDone() && !isClosed) { ByteBuffer bb = ByteBuffer.wrap(ba, off, len); lastWriteFuture = c.write(bb); return; } else { blockWriteFuture(lastWriteFuture); } } }
Source:
private void getConfigParameters(Map<String, Object> parameters) { minThreadsShared = (int) parameters.get(CONFIG_MIN_THREADS_SHARED); maxThreadsShared = (int) parameters.get(CONFIG_MAX_THREADS_SHARED); keepAliveTimeoutShared = (int) parameters.get(CONFIG_KEEP_ALIVE_SHARED); minThreadsCustom = (int) parameters.get(CONFIG_MIN_THREADS_CUSTOM); maxThreadsCustom = (int) parameters.get(CONFIG_MAX_THREADS_CUSTOM); keepAliveTimeoutCustom = (int) parameters.get(CONFIG_KEEP_ALIVE_CUSTOM); }

Target:
private void getConfigParameters(Map<String, Object> parameters) { minThreadsShared = getConfigParameter(parameters, CONFIG_MIN_THREADS_SHARED, 10); maxThreadsShared = getConfigParameter(parameters, CONFIG_MAX_THREADS_SHARED, 40); keepAliveTimeoutShared = getConfigParameter(parameters, CONFIG_KEEP_ALIVE_SHARED, 60); minThreadsCustom = getConfigParameter(parameters, CONFIG_MIN_THREADS_CUSTOM, 5); maxThreadsCustom = getConfigParameter(parameters, CONFIG_MAX_THREADS_CUSTOM, 10); keepAliveTimeoutCustom = getConfigParameter(parameters, CONFIG_KEEP_ALIVE_CUSTOM, 60); }
Source:
public void queryDocumentsPojo(){ FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); String query = "Select * from c"; Flux<FeedResponse<TestObject>> queryObservable = createdCollection.queryItems(query, options, TestObject.class); List<TestObject> fetchedResults = new ArrayList<>(); queryObservable.map(feedResponse -> fetchedResults.addAll(feedResponse.getResults())).blockLast(); System.out.println("fetchedResults = " + fetchedResults); }

Target:
public void queryDocumentsPojo(){ FeedOptions options = new FeedOptions(); options.setEnableCrossPartitionQuery(true); options.setMaxDegreeOfParallelism(2); String query = "Select * from c"; Flux<FeedResponse<TestObject>> queryObservable = createdCollection.queryItems(query, options, TestObject.class); List<TestObject> fetchedResults = new ArrayList<>(); queryObservable.map(feedResponse -> fetchedResults.addAll(feedResponse.getResults())).blockLast(); List<Tuple> assertTuples = createdDocuments.stream() .map(cosmosItemProperties -> tuple(cosmosItemProperties.getId(), cosmosItemProperties.get("mypk"), cosmosItemProperties.get("prop"), cosmosItemProperties.get("boolProp"))) .collect(Collectors.toList()); assertThat(fetchedResults).extracting(TestObject::getId, TestObject::getMypk, TestObject::getProp, TestObject::getBoolProp) .containsAll(assertTuples); }
Source:
private boolean storeFluid( IAEFluidStack stack, boolean modulate ) { try { final IStorageGrid storage = this.getProxy().getStorage(); final IMEInventory<IAEFluidStack> inv = storage.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); if( modulate ) { final IEnergyGrid energy = this.getProxy().getEnergy(); return Platform.poweredInsert( energy, inv, stack, this.mySrc ) == null; } else { final float requiredPower = stack.getStackSize() / Math.min( 1, stack.getChannel().transferFactor() ); final IEnergyGrid energy = this.getProxy().getEnergy(); if( energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) < requiredPower ) { return false; } return inv.injectItems( stack, Actionable.SIMULATE, this.mySrc ) == null; } } catch( final GridAccessException e ) { } return false; }

Target:
private boolean storeFluid( IAEFluidStack stack, boolean modulate ) { try { final IStorageGrid storage = this.getProxy().getStorage(); final IMEInventory<IAEFluidStack> inv = storage.getInventory( AEApi.instance().storage().getStorageChannel( IFluidStorageChannel.class ) ); if( modulate ) { final IEnergyGrid energy = this.getProxy().getEnergy(); return Platform.poweredInsert( energy, inv, stack, this.mySrc ) == null; } else { final float requiredPower = (float) stack.getStackSize() / Math.min( 1.0f, stack.getChannel().transferFactor() ); final IEnergyGrid energy = this.getProxy().getEnergy(); if( energy.extractAEPower( requiredPower, Actionable.SIMULATE, PowerMultiplier.CONFIG ) < requiredPower ) { return false; } return inv.injectItems( stack, Actionable.SIMULATE, this.mySrc ) == null; } } catch( final GridAccessException e ) { } return false; }
Source:
public void testPredicateOnNonDeterministicSymbolsPushedDown() { assertPlan( "SELECT * FROM (" + "SELECT randcustkey, orderkey, rank() OVER (PARTITION BY randcustkey ORDER BY orderdate ASC)" + "FROM (select round(custkey*rand()) randcustkey, * from orders) " + ") WHERE randcustkey > 100", anyTree( window(builder -> {}, anyTree( filter("\"ROUND\" > 1E2", project(ImmutableMap.of("ROUND", expression("round(CAST(CUST_KEY AS double) * rand())")), tableScan("orders", ImmutableMap.of("CUST_KEY", "custkey")))))))); }

Target:
public void testPredicateOnNonDeterministicSymbolsPushedDown() { assertPlan( "SELECT * FROM (" + "SELECT random_column, orderkey, rank() OVER (PARTITION BY random_column ORDER BY orderdate ASC)" + "FROM (select round(custkey*rand()) random_column, * from orders) " + ") WHERE random_column > 100", anyTree( node(WindowNode.class, anyTree( filter("\"ROUND\" > 1E2", project(ImmutableMap.of("ROUND", expression("round(CAST(CUST_KEY AS double) * rand())")), tableScan( "orders", ImmutableMap.of("CUST_KEY", "custkey")))))))); }
Source:
protected ResultSetFuture newFuture() { return factory.session.executeAsync(factory.preparedStatement .bind() .setString("service", service) .setInt("limit_", 10000)); }

Target:
protected ResultSetFuture newFuture() { return factory.session.executeAsync(factory.preparedStatement .bind() .setString("service", service) .setInt("limit_", 1000)); }
Source:
public DataSet next(int num) { String currentValStr = ""; INDArray features = Nd4j.create(new int[]{num-1, lotteryLength, 10}); INDArray labels = Nd4j.create(new int[]{num-1, lotteryLength, 10}); for (int i =0; i < num - 1 && iter.hasNext(); i ++) { String featureStr = ""; if (null == currentValStr || "".equals(currentValStr)) { currentValStr = iter.next(); currentCursor ++; } featureStr = currentValStr; featureStr = featureStr.split(",")[2]; String[] featureAry = featureStr.split(""); for (int j = 0; j < lotteryLength; j ++) { int l = Integer.parseInt(featureAry[j]); features.putScalar(new int[]{i, j, l}, 1); } String labelStr = iter.next(); currentCursor ++; currentValStr = labelStr; labelStr = labelStr.split(",")[2]; String[] labelAry = labelStr.split(""); for (int j = 0; j < lotteryLength; j ++) { int l = Integer.parseInt(labelAry[j]); labels.putScalar(new int[]{i, j, l}, 1); } } DataSet result = new DataSet(features, labels); return result; }

Target:
public DataSet next(int num) { int lotteryLength = 5; String currentValStr = ""; INDArray features = Nd4j.create(new int[]{num-1, lotteryLength, 10}); INDArray labels = Nd4j.create(new int[]{num-1, lotteryLength, 10}); for (int i =0; i < num - 1 && iter.hasNext(); i ++) { if ("".equals(currentValStr)) { currentValStr = iter.next(); currentCursor ++; } String featureStr = currentValStr; featureStr = featureStr.split(",")[2]; String[] featureAry = featureStr.split(""); for (int j = 0; j < lotteryLength; j ++) { int l = Integer.parseInt(featureAry[j]); features.putScalar(new int[]{i, j, l}, 1); } String labelStr = iter.next(); currentCursor ++; currentValStr = labelStr; labelStr = labelStr.split(",")[2]; String[] labelAry = labelStr.split(""); for (int j = 0; j < lotteryLength; j ++) { int l = Integer.parseInt(labelAry[j]); labels.putScalar(new int[]{i, j, l}, 1); } } return new DataSet(features, labels); }
Source:
private void logEvent( String type, String page, String method, User user, String ip, String referer, String agent, Date date) { Validate.isTrue(type != null, "Type of suspicious activity was not set"); Validate.isTrue(page != null, "Page should be non null"); SuspiciousActivity activity = new SuspiciousActivity(); SuspiciousActivityType activityType = new SuspiciousActivityType(); activityType.setName(type); activity.setType(activityType); activity.setOccurredAt(date == null ? new Date() : date); activity.setPage(abbreviatePage(page)); activity.setMethod(method); activity.setUser(user); activity.setIp(StringUtils.defaultString(ip)); activity.setRefererPage(abbreviateRefererPage(referer)); activity.setUserAgent(abbreviateUserAgent(agent)); suspiciousActivities.add(activity); }

Target:
private void logEvent( String type, String page, String method, User user, String ip, String referer, String agent, Date date) { Validate.isTrue(type != null, "Type of suspicious activity was not set"); Validate.isTrue(page != null, "Page should be non null"); SuspiciousActivity activity = new SuspiciousActivity(); SuspiciousActivityType activityType = new SuspiciousActivityType(); activityType.setName(type); activity.setType(activityType); activity.setOccurredAt(date == null ? new Date() : date); activity.setPage(abbreviatePage(page)); activity.setMethod(method); activity.setUser(user); activity.setIp(StringUtils.defaultString(ip)); activity.setRefererPage(StringUtils.stripToNull(abbreviateRefererPage(referer))); activity.setUserAgent(StringUtils.stripToNull(abbreviateUserAgent(agent))); suspiciousActivities.add(activity); }
Source:
public void testConcurrentCInvalidateRepositories() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); final List<RepositoryInfo> repositoryInfos = env.getRepositories(); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { env.applyConfig(false, false); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(100, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }

Target:
public void testConcurrentCInvalidateRepositories() throws InterruptedException, ExecutionException { final ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); final List<RepositoryInfo> repositoryInfos = env.getRepositories(); List<Future<?>> futures = new LinkedList<>(); for (int i = 0; i < TASK_COUNT; i++) { futures.add(threadPool.submit(() -> { env.applyConfig(false, false); assertTestedProjects(); })); } threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.MINUTES); for (Future<?> future : futures) { future.get(); } }
Source:
public void onFailure(Exchange exchange) { boolean connected = AccessController.doPrivileged((PrivilegedAction<Boolean>) contentFile::checkNetwork); if (!connected) { LOGGER.warn("a network error occurred. The Content Directory Monitor may be out of sync!"); } cb.accept(contentFile, false); }

Target:
public void onFailure(Exchange exchange) { boolean connected = AccessController.doPrivileged((PrivilegedAction<Boolean>) asyncFileEntry::checkNetwork); if (!connected) { LOGGER.debug( "a network error occurred, The file failed to process", asyncFileEntry.getName()); } callback.accept(asyncFileEntry, false); }
Source:
public void testBindNestedNestedNull() throws Exception { Object bean = new Object() { @SuppressWarnings("unused") public Object getFoo() { return null; } }; exception.expect(IllegalArgumentException.class); new BeanPropertyArguments("", bean).find("foo.bar.id", ctx).get().apply(3, stmt, null); }

Target:
public void testBindNestedNestedNull() { Object bean = new Object() { @SuppressWarnings("unused") public Object getFoo() { return null; } }; assertThatThrownBy(() -> new BeanPropertyArguments("", bean).find("foo.bar.id", ctx).get().apply(3, stmt, null)) .isInstanceOf(IllegalArgumentException.class); }
Source:
public TableFacade createTable(HttpServletRequest request, HttpServletResponse response) { locale = LocaleResolver.getLocale(request); session = request.getSession(); TableFacade tableFacade = null; String matchedStudyOID = null; if(request.getParameter("maxRows") != null) { tableFacade = prepareNewTableFacade(request, response); }else { TableFacade tableFacadeInSession = (TableFacade) request.getSession().getAttribute("LSStableFacade"); tableFacade = getTableFacadeImpl(request, response); matchedStudyOID = (String) request.getSession().getAttribute("matchedStudyOID"); String currentStudyOID = getStudyBean().getOid(); if(matchedStudyOID != null && matchedStudyOID.equals(currentStudyOID)) { if(tableFacadeInSession != null) { Limit limitInSession = tableFacadeInSession.getLimit(); tableFacade.setStateAttr("restore"); tableFacade.setLimit(limitInSession); } }else { tableFacade = prepareNewTableFacade(request, response); } } setDataAndLimitVariables(tableFacade); configureTableFacade(response, tableFacade); if (!tableFacade.getLimit().isExported()) { configureColumns(tableFacade, locale); tableFacade.setMaxRowsIncrements(getMaxRowIncrements()); configureTableFacadePostColumnConfiguration(tableFacade); configureTableFacadeCustomView(tableFacade, request); configureUnexportedTable(tableFacade, locale); } else { configureExportColumns(tableFacade, locale); } return tableFacade; }

Target:
public TableFacade createTable(HttpServletRequest request, HttpServletResponse response) { locale = LocaleResolver.getLocale(request); session = request.getSession(); TableFacade tableFacade = getTableFacadeImpl(request, response); tableFacade.setStateAttr("restore"); try { String maxrows = WebUtils.findParameterValue(request, "maxRows"); Integer.parseInt(maxrows); Cookie cookie = new Cookie("maxrows", maxrows); cookie.setMaxAge(7 * 24 * 60 * 60); response.addCookie(cookie); } catch (Exception e) { } try { tableFacade.setMaxRows(Integer.parseInt(WebUtils.getCookie(request, "maxrows").getValue())); } catch (Exception e) { tableFacade.setMaxRows(50); } setDataAndLimitVariables(tableFacade); configureTableFacade(response, tableFacade); if (!tableFacade.getLimit().isExported()) { configureColumns(tableFacade, locale); tableFacade.setMaxRowsIncrements(getMaxRowIncrements()); configureTableFacadePostColumnConfiguration(tableFacade); configureTableFacadeCustomView(tableFacade, request); configureUnexportedTable(tableFacade, locale); } else { configureExportColumns(tableFacade, locale); } return tableFacade; }
Source:
void flushState() { try { stateMgr.flush(); } catch (final ProcessorStateException e) { if (e.getCause() instanceof RetriableException) { log.warn("Caught a retriable Kafka exception while flushing state. Initiating a rebalance to attempt recovery.", e); throw new TaskMigratedException(this, e); } } }

Target:
void flushState() { try { stateMgr.flush(); } catch (final ProcessorStateException e) { if (e.getCause() instanceof RecoverableClientException) { throw new TaskMigratedException(this, e); } } }
Source:
public Guid getId() { return this.id; }

Target:
public Guid getId() { return id; }
Source:
public void testCurrentClientToOldServer() throws Exception { IgniteProcessProxy proxy = null; try { if (verFormatted.equals(IgniteVersionUtils.VER_STR)) { Ignite ignite = startGrid(0); initNode(ignite); } else { Ignite ignite = startGrid(1, verFormatted, this::processRemoteConfiguration, this::initNode); proxy = IgniteProcessProxy.ignite(ignite.name()); } testClient(verFormatted); } finally { stopAllGrids(); if (proxy != null) { Process proc = proxy.getProcess().getProcess(); GridTestUtils.waitForCondition(() -> !proc.isAlive(), 5_000L); } } }

Target:
public void testCurrentClientToOldServer() throws Exception { IgniteProcessProxy proxy = null; try { if (verFormatted.equals(IgniteVersionUtils.VER_STR)) { Ignite ignite = startGrid(0); initNode(ignite); } else { Ignite ignite = startGrid(1, verFormatted, this::processRemoteConfiguration, this::initNode); proxy = IgniteProcessProxy.ignite(ignite.name()); } testClient(verFormatted); } finally { stopAllGrids(); if (proxy != null) { Process proc = proxy.getProcess().getProcess(); assertTrue(GridTestUtils.waitForCondition(() -> !proc.isAlive(), 5_000L)); } } }
Source:
public void testCollectionOfEmbeddable() { AtomicReference<User> user = new AtomicReference<>(new User()); doInJPA( this::entityManagerFactory, entityManager -> { user.get().id = 1; user.get().userDetails = new UserDetails(); user.get().contactAddresses = new ArrayList<>(); user.get().contactAddresses.add(new ContactAddress()); user.get().contactAddresses.add(new ContactAddress()); entityManager.persist( user.get() ); user.get().contactAddresses.forEach( e -> assertEquals(1, e.prePersist)); } ); user.get().contactAddresses.forEach( e -> assertEquals(1, e.postPersist)); doInJPA( this::entityManagerFactory, entityManager -> { User entity = entityManager.find( User.class, 1 ); assertEquals( "George", entity.name ); assertEquals("London", entity.contactAddresses.get(0).city); assertEquals("test@test.com", entity.userDetails.email); entity.contactAddresses.forEach( e -> assertEquals(1, e.postLoad)); } ); doInJPA( this::entityManagerFactory, entityManager -> { user.set(entityManager.find(User.class, 1)); user.get().name = "Nick"; user.get().contactAddresses.get(0).city = "Athens"; entityManager.persist( user.get() ); } ); user.get().contactAddresses.forEach( e -> assertEquals(1, e.preUpdate)); user.get().contactAddresses.forEach( e -> assertEquals(1, e.postUpdate)); doInJPA( this::entityManagerFactory, entityManager -> { user.set(entityManager.find(User.class, 1)); entityManager.remove(user.get()); user.get().contactAddresses.forEach( e -> assertEquals(1, e.preRemove)); } ); user.get().contactAddresses.forEach( e -> assertEquals(1, e.postRemove)); }

Target:
public void testCollectionOfEmbeddable() { User user = fromTransaction( this.entityManagerFactory(), entityManager -> { final User u = new User(); u.id = 1; u.userDetails = new UserDetails(); u.contactAddresses = new ArrayList<>(); u.contactAddresses.add( new ContactAddress() ); u.contactAddresses.add( new ContactAddress() ); entityManager.persist( u ); u.contactAddresses.forEach( e -> assertEquals( 1, e.prePersist ) ); return u; } ); user.contactAddresses.forEach( e -> assertEquals( 1, e.postPersist ) ); doInJPA( this::entityManagerFactory, entityManager -> { User entity = entityManager.find( User.class, 1 ); assertEquals( "George", entity.name ); assertEquals("London", entity.contactAddresses.get( 0 ).city ); assertEquals("test@test.com", entity.userDetails.email ); entity.contactAddresses.forEach( e -> assertEquals( 1, e.postLoad ) ); } ); user = fromTransaction( this.entityManagerFactory(), entityManager -> { User u = entityManager.find( User.class, 1 ); u.name = "Nick"; u.contactAddresses.get( 0 ).city = "Athens"; entityManager.persist( u ); return u; } ); user.contactAddresses.forEach( e -> assertEquals( 1, e.preUpdate ) ); user.contactAddresses.forEach( e -> assertEquals( 1, e.postUpdate ) ); user = fromTransaction( this.entityManagerFactory(), entityManager -> { User u = entityManager.find( User.class, 1 ); assertEquals( "Nick", u.name ); assertEquals( "Athens", u.contactAddresses.get( 0 ).city ); entityManager.remove( u ); u.contactAddresses.forEach( e -> assertEquals( 1, e.preRemove ) ); return u; } ); user.contactAddresses.forEach( e -> assertEquals( 1, e.postRemove ) ); }
Source:
public URI getPictureUrl() { final LinkedIn2ProfilePicture pp = getProfilePicture(); if (pp == null) return null; final DisplayImageTilde displayImageTilde = pp.getDisplayImageTilde(); if (displayImageTilde == null) return null; final Element[] elements = displayImageTilde.getElements(); if (elements == null || elements.length == 0) return null; final Element element = elements[0]; if (element == null) return null; final Identifier[] identifiers = element.getIdentifiers(); if (identifiers == null || identifiers.length == 0) return null; final Identifier identifier = identifiers[0]; if (identifier == null) return null; final String identifier2 = identifier.getIdentifier(); if (identifier2 == null) return null; return CommonHelper.asURI(identifier2); }

Target:
public URI getPictureUrl() { final LinkedIn2ProfilePicture pp = getProfilePicture(); if (pp == null) { return null; } final DisplayImageTilde displayImageTilde = pp.getDisplayImageTilde(); if (displayImageTilde == null) { return null; } final Element[] elements = displayImageTilde.getElements(); if (elements == null || elements.length == 0) { return null; } final Element element = elements[0]; if (element == null) { return null; } final Identifier[] identifiers = element.getIdentifiers(); if (identifiers == null || identifiers.length == 0) { return null; } final Identifier identifier = identifiers[0]; if (identifier == null) { return null; } final String identifier2 = identifier.getIdentifier(); if (identifier2 == null) { return null; } return CommonHelper.asURI(identifier2); }
Source:
private void setCommitBody(List<BoxUploadSessionPart> parts, Map<String, String> attributes) { JsonArray array = new JsonArray(); for (BoxUploadSessionPart part : parts) { JsonObject partObj = new JsonObject(); partObj.add("part_id", part.getPartId()); partObj.add("offset", part.getOffset()); partObj.add("size", part.getSize()); array.add(partObj); } mBodyMap.put("parts", array); if (attributes != null) { JsonObject attrObj = new JsonObject(); for (String key : attributes.keySet()) { attrObj.add(key, attributes.get(key)); } mBodyMap.put("attributes", attrObj); } }

Target:
private void setCommitBody(List<BoxUploadSessionPart> parts, Map<String, String> attributes) { JsonArray array = new JsonArray(); for (BoxUploadSessionPart part : parts) { JsonObject partObj = new JsonObject(); partObj.add(BoxUploadSessionPart.FIELD_PART_ID, part.getPartId()); partObj.add(BoxUploadSessionPart.FIELD_OFFSET, part.getOffset()); partObj.add(BoxUploadSessionPart.FIELD_SIZE, part.getSize()); array.add(partObj); } mBodyMap.put("parts", array); if (attributes != null) { JsonObject attrObj = new JsonObject(); for (String key : attributes.keySet()) { attrObj.add(key, attributes.get(key)); } mBodyMap.put("attributes", attrObj); } }