auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public LanePhasingMetricsCollector(final Collection<Tile> laneTiles, boolean usePercentage) { final Map<TileTemplateRead, Float> medianPhasingMap = new TreeMap<TileTemplateRead, Float>(); final Map<TileTemplateRead, Float> medianPrePhasingMap = new TreeMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> phasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> prePhasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); for (final Tile tile : laneTiles) { for (final TileTemplateRead tileTemplateRead : tile.getPhasingMap().keySet()) { phasingValues.append(tileTemplateRead, tile.getPhasingMap().get(tileTemplateRead)); prePhasingValues.append(tileTemplateRead, tile.getPrePhasingMap().get(tileTemplateRead)); } } for (final TileTemplateRead tileTemplateRead : phasingValues.keySet()) { if (usePercentage) { medianPhasingMap.put(tileTemplateRead, medianPercentage(phasingValues.get(tileTemplateRead))); medianPrePhasingMap.put(tileTemplateRead, medianPercentage(prePhasingValues.get(tileTemplateRead))); } else { medianPhasingMap.put(tileTemplateRead, median(phasingValues.get(tileTemplateRead))); medianPrePhasingMap.put(tileTemplateRead, median(prePhasingValues.get(tileTemplateRead))); } } this.medianPhasingMap = Collections.unmodifiableMap(medianPhasingMap); this.medianPrePhasingMap = Collections.unmodifiableMap(medianPrePhasingMap); }

Target:
public LanePhasingMetricsCollector(final Collection<Tile> laneTiles, boolean usePercentage) { final Map<TileTemplateRead, Float> medianPhasingMap = new TreeMap<TileTemplateRead, Float>(); final Map<TileTemplateRead, Float> medianPrePhasingMap = new TreeMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> phasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); final CollectionUtil.MultiMap<TileTemplateRead, Float> prePhasingValues = new CollectionUtil.MultiMap<TileTemplateRead, Float>(); for (final Tile tile : laneTiles) { for (final TileTemplateRead tileTemplateRead : tile.getPhasingMap().keySet()) { phasingValues.append(tileTemplateRead, tile.getPhasingMap().get(tileTemplateRead)); prePhasingValues.append(tileTemplateRead, tile.getPrePhasingMap().get(tileTemplateRead)); } } for (final TileTemplateRead tileTemplateRead : phasingValues.keySet()) { medianPhasingMap.put(tileTemplateRead, median(phasingValues.get(tileTemplateRead), usePercentage)); medianPrePhasingMap.put(tileTemplateRead, median(prePhasingValues.get(tileTemplateRead), usePercentage)); } this.medianPhasingMap = Collections.unmodifiableMap(medianPhasingMap); this.medianPrePhasingMap = Collections.unmodifiableMap(medianPrePhasingMap); }
Source:
private void configureCommandFactoryProviders() { if (getEditingDomain() != null) { IDiagramCommandFactory diagramCommandFactory = emfCommandFactoryProvider.getCommandFactory(getEditingDomain()); diagramCommandFactory.setUserInterfaceCallBack(new EMFCommandFactoryUI()); } }

Target:
private void configureCommandFactoryProviders() { TransactionalEditingDomain domain = getEditingDomain(); if (domain != null) { IDiagramCommandFactory diagramCommandFactory = emfCommandFactoryProvider.getCommandFactory(domain); diagramCommandFactory.setUserInterfaceCallBack(new EMFCommandFactoryUI()); } }
Source:
public HashMap<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<String, String>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }

Target:
public Map<String, String> createImageServerContent(String scheme) throws IOException { HashMap<String, String> map = new HashMap<>(); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml", createServerEntry("WikiToDocTaskIntegrationTest1.xml")); map.put(scheme + "://wiki.eclipse.org/api.php?action=query&titles=Some%2FMy_Page&generator=images&prop=imageinfo&iiprop=url&format=xml&gimcontinue=49671%7Cpict1.gif", createServerEntry("WikiToDocTaskIntegrationTest2.xml")); return map; }
Source:
private Set<String> parseClientTags(HttpServletRequest servletRequest) { Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); return ImmutableSet.copyOf(splitter.splitToList(nullToEmpty(servletRequest.getHeader(PRESTO_CLIENT_TAGS)))); }

Target:
private Set<String> parseClientTags(HttpServletRequest servletRequest) { Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings(); return ImmutableSet.copyOf(splitter.split(nullToEmpty(servletRequest.getHeader(PRESTO_CLIENT_TAGS)))); }
Source:
public void run() { WeakReference<Object> reference = new WeakReference<Object>(new Object()); Runtime runtime = Runtime.getRuntime(); for (int i = 0; i < 20; ++i) { runtime.gc(); System.runFinalization(); try { Thread.sleep(1); } catch (InterruptedException e) { throw new AssertionError(e); } if (reference.get() == null) { System.logI("Sentry object has been freed so assuming CloseGuards have reported" + " any resource leakages"); break; } } CloseGuard.setReporter(closeGuardReporter); if (!closeGuardAllocationSites.isEmpty()) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); int i = 0; for (Throwable allocationSite : closeGuardAllocationSites) { printWriter.print(++i); printWriter.print(") "); allocationSite.printStackTrace(printWriter); printWriter.println(" --------------------------------"); } throw new AssertionError("Potential resource leakage detected:\n" + writer); } }

Target:
public void run() { WeakReference<Object> reference = new WeakReference<Object>(new Object()); try { Runtime runtime = Runtime.getRuntime(); for (int i = 0; i < 20; ++i) { runtime.gc(); System.runFinalization(); try { Thread.sleep(1); } catch (InterruptedException e) { throw new AssertionError(e); } if (reference.get() == null) { System.logI("Sentry object has been freed so assuming CloseGuards have reported" + " any resource leakages"); break; } } } finally { CloseGuard.setReporter(closeGuardReporter); } if (!closeGuardAllocationSites.isEmpty()) { StringWriter writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); int i = 0; for (Throwable allocationSite : closeGuardAllocationSites) { printWriter.print(++i); printWriter.print(") "); allocationSite.printStackTrace(printWriter); printWriter.println(" --------------------------------"); } throw new AssertionError("Potential resource leakage detected:\n" + writer); } }
Source:
public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mUser, flags); dest.writeString(mToken); dest.writeString(mSecret); try { ObjectOutputStream oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(mException); oos.close(); dest.writeSerializable(mException); } catch (IOException e) { dest.writeSerializable(new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR)); } }

Target:
public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(mUser, flags); dest.writeString(mToken); dest.writeString(mSecret); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new ByteArrayOutputStream()); oos.writeObject(mException); dest.writeSerializable(mException); } catch (IOException e) { dest.writeSerializable(new FirebaseUiException(ErrorCodes.UNKNOWN_ERROR)); } finally { if (oos != null) { try { oos.close(); } catch (IOException ignored) } } }
Source:
protected boolean setAndValidateDiskProfiles() { if (getImage() != null && DiskStorageType.IMAGE == getImage().getDiskStorageType()) { DiskImage diskImage = new DiskImage(); diskImage.setDiskProfileId(getParameters().getDiskProfileId()); Map<DiskImage, Guid> map = new HashMap<>(); map.put(diskImage, getParameters().getStorageDomainId()); return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }

Target:
protected boolean setAndValidateDiskProfiles() { getImage().setDiskProfileId(getParameters().getDiskProfileId()); return validate(DiskProfileHelper.setAndValidateDiskProfiles(Collections.singletonMap(getImage(), getParameters().getStorageDomainId()))); }
Source:
public void run() { try { InetSocketAddress connectAddr = new InetSocketAddress("127.0.0.1", 5140); ByteChannel out; if("tcp".equals(transport)) { SocketChannel channel = SocketChannel.open(); channel.connect(connectAddr); out = channel; } else { DatagramChannel channel = DatagramChannel.open(); channel.connect(connectAddr); out = channel; } ByteBuffer buff = ByteBuffer.wrap( ("<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8\n").getBytes() ); for (int i = 0; i < runs; i++) { out.write(buff); buff.flip(); if("udp".equals(transport)) { Thread.sleep(5); } } out.close(); } catch (IOException | InterruptedException e) { throw new IllegalStateException(e); } }

Target:
public void run() { try { InetSocketAddress connectAddr = new InetSocketAddress("127.0.0.1", 5140); ByteChannel out; if("tcp".equals(transport)) { SocketChannel channel = SocketChannel.open(); channel.connect(connectAddr); out = channel; } else { DatagramChannel channel = DatagramChannel.open(); channel.connect(connectAddr); out = channel; } ByteBuffer buff = ByteBuffer.wrap( ("<34>Oct 11 22:14:15 mymachine su: 'su root' failed for lonvick on /dev/pts/8\n").getBytes() ); for (int i = 0; i < runs; i++) { out.write(buff); buff.flip(); if("udp".equals(transport)) { Thread.sleep(5); } } out.close(); } catch (Exception e) { throw new IllegalStateException(e); } }
Source:
public void testMqttSink() throws Exception { final int numSinks = 4; final List<String> outputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(numSinks * outputStream.size()); final Map<String, List<String>> topicListMap = new ConcurrentHashMap<>(); final String topic = "topic"; subscriber.connect(); subscriber.setCallback(new TestMqttSubscriber(topicListMap, countDownLatch)); final List<Sink<MqttMessage>> sinks = new LinkedList<>(); for (int i = 0; i < numSinks; i++) { final Sink<MqttMessage> publisher = new MqttSink(MqttUtils.BROKER_URI, topic+i, mqttSharedResource); topicListMap.put(topic+i, new LinkedList<>()); sinks.add(publisher); subscriber.subscribe(topic+i); } outputStream.forEach((output) -> { for (final Sink<MqttMessage> sink : sinks) { sink.handle(new MqttMessage(output.getBytes())); } }); countDownLatch.await(); for (List<String> received : topicListMap.values()) { Assert.assertEquals(outputStream, received); } for (final Sink<MqttMessage> sink : sinks) { sink.close(); } }

Target:
public void testMqttSink() throws Exception { final int numSinks = 4; final List<String> outputStream = Arrays.asList( "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", "In in leo nec erat fringilla mattis eu non massa.", "Cras quis diam suscipit, commodo enim id, pulvinar nunc."); final CountDownLatch countDownLatch = new CountDownLatch(numSinks * outputStream.size()); final Map<String, List<String>> topicListMap = new ConcurrentHashMap<>(); final String topic = "topic"; subscriber.connect(); subscriber.setCallback(new TestMqttSubscriber(topicListMap, countDownLatch)); final List<Sink<MqttMessage>> sinks = new LinkedList<>(); for (int i = 0; i < numSinks; i++) { final Sink<MqttMessage> publisher = new MqttSink(MqttUtils.BROKER_URI, topic+i, mqttSharedResource); topicListMap.put(topic+i, new LinkedList<>()); sinks.add(publisher); subscriber.subscribe(topic+i); } outputStream.forEach((output) -> { for (final Sink<MqttMessage> sink : sinks) { sink.handle(new MqttMessage(output.getBytes())); } }); countDownLatch.await(); for (final List<String> received : topicListMap.values()) { Assert.assertEquals(outputStream, received); } for (final Sink<MqttMessage> sink : sinks) { sink.close(); } }
Source:
public void openFileOnGitHubTest() { projectExplorer.openItemByPath(PROJECT_NAME + "/src/main/java/che/eclipse/sample/Aclass.java"); editor.selectLines(14, 8); editor.openContextMenuInEditor(); editor.clickOnItemInContextMenu(OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); Assert.assertEquals( seleniumWebDriver.getCurrentUrl(), testRepo.getHtmlUrl() + "/blob/master" + PATH_TO_EXPAND + "/Aclass.java#L14-L16"); }

Target:
public void openFileOnGitHubTest() { projectExplorer.openItemByPath(PROJECT_NAME + "/" + PATH_TO_EXPAND + "/Aclass.java"); editor.selectLines(14, 1); editor.openContextMenuInEditor(); editor.clickOnItemInContextMenu(OPEN_ON_GITHUB); seleniumWebDriverHelper.switchToNextWindow(seleniumWebDriver.getWindowHandle()); seleniumWebDriverHelper.waitSuccessCondition( urlToBe(testRepo.getHtmlUrl() + "/blob/master/" + PATH_TO_EXPAND + "/Aclass.java#L15-L15")); }
Source:
public RunResult runTests(Path path) { Path shadowDir = makeShadowBuildDir(path); try { ProcessResult qmakeBuild = buildWithQmake(shadowDir); if (qmakeBuild.statusCode != 0) { log.error("Building project with qmake failed: {}", qmakeBuild.errorOutput); return filledFailure(qmakeBuild.errorOutput); } } catch (Exception e) { log.error("Building project with qmake failed", e); throw new RuntimeException(e); } try { ProcessResult makeBuild = buildWithMake(shadowDir); if (makeBuild.statusCode != 0) { log.error("Building project with make failed: {}", makeBuild.errorOutput); return filledFailure(makeBuild.errorOutput); } } catch (Exception e) { log.error("Building project with make failed", e); throw new RuntimeException(e); } Path testResults = path.resolve(TMC_TEST_RESULTS); String target = "check"; String config = "TESTARGS=-o " + testResults.toString() + ",xml"; String[] makeCommand = {"make", target, config}; log.info("Testing project with command {}", Arrays.toString(makeCommand)); try { ProcessResult testRun = run(makeCommand, shadowDir); if (!Files.exists(testResults)) { log.error("Failed to get test output at {}", testResults); return filledFailure(testRun.output); } } catch (Exception e) { log.error("Testing with make check failed", e); throw new RuntimeException(e); } QTestResultParser parser = new QTestResultParser(); parser.loadTests(testResults); return parser.result(); }

Target:
public RunResult runTests(Path path) { Path shadowDir = makeShadowBuildDir(path); try { ProcessResult qmakeBuild = buildWithQmake(shadowDir); if (qmakeBuild.statusCode != 0) { log.error("Building project with qmake failed: {}", qmakeBuild.errorOutput); return filledFailure(qmakeBuild.errorOutput); } } catch (IOException | InterruptedException e) { log.error("Building project with qmake failed", e); throw new QmakeBuildException(e); } try { ProcessResult makeBuild = buildWithMake(shadowDir); if (makeBuild.statusCode != 0) { log.error("Building project with make failed: {}", makeBuild.errorOutput); return filledFailure(makeBuild.errorOutput); } } catch (IOException | InterruptedException e) { log.error("Building project with make failed", e); throw new QmakeBuildException(e); } Path testResults = path.resolve(TMC_TEST_RESULTS); String target = "check"; String config = "TESTARGS=-o " + testResults.toString() + ",xml"; String[] makeCommand = {"make", target, config}; log.info("Testing project with command {}", Arrays.toString(makeCommand)); try { ProcessResult testRun = run(makeCommand, shadowDir); if (!Files.exists(testResults)) { log.error("Failed to get test output at {}", testResults); return filledFailure(testRun.output); } } catch (IOException | InterruptedException e) { log.error("Testing with make check failed", e); throw new QmakeBuildException(e); } QTestResultParser parser = new QTestResultParser(); parser.loadTests(testResults); return parser.result(); }
Source:
public boolean addVertex(final V v) { if (!adjacent.containsKey(v)) { adjacent.put(v, new HashSet<>()); inDegrees.put(v, 0); rootVertices.add(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} already exists", new Object[]{v}); return false; } }

Target:
public boolean addVertex(final V v) { if (!adjacent.containsKey(v)) { adjacent.put(v, new HashSet<>()); inDegrees.put(v, 0); rootVertices.add(v); return true; } else { LOG.log(Level.WARNING, "The vertex {0} already exists", v); return false; } }
Source:
public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { final String index = "tools"; Response response = searchIndex(query, queryParameters, index); return response; }

Target:
public Response toolsIndexSearch(String query, MultivaluedMap<String, String> queryParameters, SecurityContext securityContext) { if (!config.getEsConfiguration().getHostname().isEmpty()) { try (RestClient restClient = RestClient .builder(new HttpHost(config.getEsConfiguration().getHostname(), config.getEsConfiguration().getPort(), "http")) .build()) { HttpEntity entity = query == null ? null : new NStringEntity(query, ContentType.APPLICATION_JSON); Map<String, String> parameters = new HashMap<>(); if (queryParameters != null) { queryParameters.forEach((key, value) -> parameters.put(key, value.get(0))); } org.elasticsearch.client.Response get = restClient.performRequest("GET", "/" + ALL_INDICES + "/_search", parameters, entity); if (get.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new CustomWebApplicationException("Could not search " + ALL_INDICES + "index", HttpStatus.SC_INTERNAL_SERVER_ERROR); } return Response.ok().entity(get.getEntity().getContent()).build(); } catch (ResponseException e) { int[] codesToResurface = {HttpStatus.SC_BAD_REQUEST}; int statusCode = e.getResponse().getStatusLine().getStatusCode(); LOG.error("Could not use Elasticsearch search", e); if (ArrayUtils.contains(codesToResurface, statusCode)) { throw new CustomWebApplicationException(e.getMessage(), statusCode); } else { throw new CustomWebApplicationException(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (IOException e2) { LOG.error("Could not use Elasticsearch search", e2); throw new CustomWebApplicationException(e2.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR); } } return Response.ok().entity(0).build(); }
Source:
public Builder initialData(Realm.Transaction transaction) { if (readOnly) { throw new IllegalStateException("initialData(Transaction) cannot be combined with read-only Realms."); } initialDataTransaction = transaction; return this; }

Target:
public Builder initialData(Realm.Transaction transaction) { initialDataTransaction = transaction; return this; }
Source:
@Override public ByteBuffer marshal(Object obj, int off) throws IOException { try(GridByteArrayOutputStream bOut = new GridByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bOut)) { out.writeObject(obj); out.flush(); ByteBuffer buf = ByteBuffer.allocate(off + bOut.size()); buf.position(off); buf.put(bOut.internalArray(), 0, bOut.size()); buf.flip(); return buf; } }

Target:
@Override public ByteBuffer marshal(Object obj, int off) throws IOException { GridByteArrayOutputStream bOut = new GridByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bOut); out.writeObject(obj); out.flush(); ByteBuffer buf = ByteBuffer.allocate(off + bOut.size()); buf.position(off); buf.put(bOut.internalArray(), 0, bOut.size()); buf.flip(); return buf; }
Source:
void run(Handler<AsyncResult<Void>> completionHandler) { if (closeHooksRun) { throw new IllegalStateException("Close hooks already run"); } closeHooksRun = true; if (closeHooks != null && !closeHooks.isEmpty()) { Set<Closeable> copy = new HashSet<>(closeHooks); int num = copy.size(); if (num != 0) { AtomicInteger count = new AtomicInteger(); AtomicBoolean failed = new AtomicBoolean(); for (Closeable hook : copy) { Future<Void> a = Future.future(); a.setHandler(ar -> { if (ar.failed()) { if (failed.compareAndSet(false, true)) { completionHandler.handle(Future.failedFuture(ar.cause())); } } else { if (count.incrementAndGet() == num) { completionHandler.handle(Future.succeededFuture()); } } }); try { hook.close(a.completer()); } catch (Throwable t) { log.warn("Failed to run close hooks", t); if (!a.isComplete()) { a.fail(t); } } } } else { completionHandler.handle(Future.succeededFuture()); } } else { completionHandler.handle(Future.succeededFuture()); } }

Target:
void run(Handler<AsyncResult<Void>> completionHandler) { Set<Closeable> copy = null; synchronized (this) { if (closeHooksRun) { throw new IllegalStateException("Close hooks already run"); } closeHooksRun = true; if (closeHooks != null && !closeHooks.isEmpty()) { copy = new HashSet<>(closeHooks); } } if (copy != null && !copy.isEmpty()) { int num = copy.size(); if (num != 0) { AtomicInteger count = new AtomicInteger(); AtomicBoolean failed = new AtomicBoolean(); for (Closeable hook : copy) { Future<Void> a = Future.future(); a.setHandler(ar -> { if (ar.failed()) { if (failed.compareAndSet(false, true)) { completionHandler.handle(Future.failedFuture(ar.cause())); } } else { if (count.incrementAndGet() == num) { completionHandler.handle(Future.succeededFuture()); } } }); try { hook.close(a.completer()); } catch (Throwable t) { log.warn("Failed to run close hooks", t); if (!a.isComplete()) { a.fail(t); } } } } else { completionHandler.handle(Future.succeededFuture()); } } else { completionHandler.handle(Future.succeededFuture()); } }
Source:
private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) { checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() .stream() .filter( partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId) .equals(this.ownerId)) .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) .collect(Collectors.toList())) .subscribe(ignored -> { }, ex -> { logger.error("Error renewing partition ownership", ex); isLoadBalancerRunning.set(false); }, () -> isLoadBalancerRunning.set(false)); }

Target:
private void renewOwnership(Map<String, PartitionOwnership> partitionOwnershipMap) { checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() .stream() .filter( partitionId -> partitionOwnershipMap.containsKey(partitionId) && partitionOwnershipMap.get(partitionId) .getOwnerId().equals(this.ownerId)) .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) .collect(Collectors.toList())) .subscribe(ignored -> { }, ex -> { logger.error("Error renewing partition ownership", ex); isLoadBalancerRunning.set(false); }, () -> isLoadBalancerRunning.set(false)); }
Source:
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException, MalformedURLException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } URL url = new URL(certificateId); String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } return new KeyVaultCertificateIdentifier(certificateId, url.getProtocol() + "://" + url.getHost(), pathSegments[2], pathSegments.length == 4 ? pathSegments[3] : null); }

Target:
public static KeyVaultCertificateIdentifier parse(String certificateId) throws IllegalArgumentException { if (certificateId == null) { throw new IllegalArgumentException("certificateId cannot be null"); } try { final URL url = new URL(certificateId); final String[] pathSegments = url.getPath().split("/"); if ((pathSegments.length != 3 && pathSegments.length != 4) || !"https".equals(url.getProtocol()) || (!"certificates".equals(pathSegments[1]) && !"deletedcertificates".equals(pathSegments[1])) || ("deletedcertificates".equals(pathSegments[1]) && pathSegments.length == 4)) { throw new IllegalArgumentException("certificateId is not a valid Key Vault Certificate identifier"); } final String vaultUrl = String.format("%s://%s", url.getProtocol(), url.getHost()); final String certificateName = pathSegments[2]; final String certificateVersion = pathSegments.length == 4 ? pathSegments[3] : null; return new KeyVaultCertificateIdentifier(certificateId, vaultUrl, certificateName, certificateVersion); } catch (MalformedURLException e) { throw new IllegalArgumentException("Could not parse certificateId", e); } }
Source:
public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if ( ViewPagerDownloadManager.instance.inInitialPhase(unit) ) return; if (isVisibleToUser) { checkVideoStatus(unit); try { if (playerFragment != null) { playerFragment.setCallback(this); playerFragment.handleOnResume(); } } catch (Exception ex) { logger.error(ex); } }else{ if (getActivity() != null) { ((BaseFragmentActivity) getActivity()).hideInfoMessage(true); } try { if (playerFragment != null) { playerFragment.setCallback(null); playerFragment.handleOnPause(); } } catch (Exception ex) { logger.error(ex); } } }

Target:
public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if ( ViewPagerDownloadManager.instance.inInitialPhase(unit) ) return; if (isVisibleToUser) { checkVideoStatus(unit); try { if (playerFragment != null) { playerFragment.setCallback(this); playerFragment.handleOnResume(); } } catch (Exception ex) { logger.error(ex); } }else{ if (getActivity() != null) { ((BaseFragmentActivity) getActivity()).hideInfoMessage(); } try { if (playerFragment != null) { playerFragment.setCallback(null); playerFragment.handleOnPause(); } } catch (Exception ex) { logger.error(ex); } } }
Source:
public void stop() { logger.info("stopping SparkDriver"); try { if (javaStreamingContext != null) { javaStreamingContext.ssc().sc().cancelAllJobs(); javaStreamingContext.close(); } if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }

Target:
public void stop() { logger.info("stopping SparkDriver"); try { if (streamingContext != null) { streamingContext.sc().cancelAllJobs(); streamingContext.stop(true, false); } super.stop(); } catch (Exception e) { logger.warn("Exception when stopping the spark module " + e); } }
Source:
public Connection getConnection() throws SQLException { Connection connection = null; int retryAttempt = 1; while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) { try { connection = createDataSource().getConnection(); if (connection == null || isReadOnly(connection)) { throw new SQLException("Failed to find DB connection Or connection is read only. "); } else { return connection; } } catch (final SQLException ex) { try { invalidateConnection(connection); } catch (final Exception e) { logger.error( "can not invalidate connection.", e); } logger.error( "Failed to find write-enabled DB connection. Wait 1 minutes and retry." + " No.Attempt = " + retryAttempt, ex); sleep(1000L * 15); retryAttempt++; } } return connection; }

Target:
public Connection getConnection() throws SQLException { Connection connection = null; int retryAttempt = 1; while (retryAttempt < AzDBUtil.MAX_DB_RETRY_COUNT) { try { connection = createDataSource().getConnection(); if (connection == null || isReadOnly(connection)) { throw new SQLException("Failed to find DB connection Or connection is read only. "); } else { return connection; } } catch (final SQLException ex) { try { invalidateConnection(connection); } catch (final Exception e) { logger.error( "can not invalidate connection.", e); } logger.error( "Failed to find write-enabled DB connection. Wait 15 seconds and retry." + " No.Attempt = " + retryAttempt, ex); sleep(1000L * 15); retryAttempt++; } } return connection; }
Source:
public static Calendar convertToCalendar(String value) { Calendar result = null; if (value != null && !value.isEmpty() && !value.equalsIgnoreCase("N/A") && !value.equalsIgnoreCase("NA")) { try { result = Calendar.getInstance(); result.setTimeInMillis(Long.valueOf(value) * 1000); } catch (NumberFormatException e) { logger.debug("Cannot convert to Calendar", value); result = null; } } return result; }

Target:
public static Calendar convertToCalendar(String value) { Calendar result = null; if (isValid(value)) { try { result = Calendar.getInstance(); result.setTimeInMillis(Long.valueOf(value) * 1000); } catch (NumberFormatException e) { LoggerFactory.getLogger(WeatherUndergroundJsonUtils.class).debug("Cannot convert to Calendar", value); result = null; } } return result; }
Source:
public Node getContextNode() { return getLibraryNode() != null || getParent() == null ? this : org.raml.yagi.framework.util.NodeUtils.getContextNode(getParent()); }

Target:
public Node getContextNode() { return getLibraryNode() != null || getParent() == null ? this : NodeUtils.getContextNode(getParent()); }
Source:
public void graphReleased(Object v, MouseEvent me) { final PickedState<Object> pickedVertexState = _graphContext.getVisualizationViewer().getPickedVertexState(); final Object[] selectedObjects = pickedVertexState.getSelectedObjects(); final AbstractLayout<Object, JobGraphLink> graphLayout = _graphContext.getGraphLayout(); for (final Object vertex : selectedObjects) { final Double x = graphLayout.getX(vertex); final Double y = graphLayout.getY(vertex); if (vertex instanceof HasMetadataProperties) { final Map<String, String> metadataProperties = ((HasMetadataProperties) vertex).getMetadataProperties(); metadataProperties.put(JobGraphMetadata.METADATA_PROPERTY_COORDINATES_X, "" + x.intValue()); metadataProperties.put(JobGraphMetadata.METADATA_PROPERTY_COORDINATES_Y, "" + y.intValue()); } else if (vertex instanceof Table) { JobGraphMetadata.setPointForTable(_graphContext.getAnalysisJobBuilder(), (Table) vertex, x, y); } } if (selectedObjects.length > 0) { _graphContext.getJobGraph().refresh(); } }

Target:
public void graphReleased(Object v, MouseEvent me) { if (_pressedPoint != null && _pressedPoint.equals(me.getPoint())) { return; } final PickedState<Object> pickedVertexState = _graphContext.getVisualizationViewer().getPickedVertexState(); final Object[] selectedObjects = pickedVertexState.getSelectedObjects(); final AbstractLayout<Object, JobGraphLink> graphLayout = _graphContext.getGraphLayout(); for (final Object vertex : selectedObjects) { final Double x = graphLayout.getX(vertex); final Double y = graphLayout.getY(vertex); if (vertex instanceof HasMetadataProperties) { final Map<String, String> metadataProperties = ((HasMetadataProperties) vertex).getMetadataProperties(); metadataProperties.put(JobGraphMetadata.METADATA_PROPERTY_COORDINATES_X, "" + x.intValue()); metadataProperties.put(JobGraphMetadata.METADATA_PROPERTY_COORDINATES_Y, "" + y.intValue()); } else if (vertex instanceof Table) { JobGraphMetadata.setPointForTable(_graphContext.getAnalysisJobBuilder(), (Table) vertex, x, y); } } if (selectedObjects.length > 0) { _graphContext.getJobGraph().refresh(); } }
Source:
S3FileSystemBase( Provider<AbstractBackupPath> pathProvider, ICompression compress, final IConfiguration config, BackupMetrics backupMetrics, BackupNotificationMgr backupNotificationMgr) { super(config, backupMetrics, backupNotificationMgr, pathProvider); this.compress = compress; this.config = config; int threads = config.getBackupThreads(); LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(threads); this.executor = new BlockingSubmitThreadPoolExecutor(threads, queue, config.getUploadTimeout()); double throttleLimit = config.getUploadThrottle(); this.rateLimiter = RateLimiter.create(throttleLimit < 1 ? Double.MAX_VALUE : throttleLimit); int objectExistLimit = config.getRemoteFileSystemObjectThrottle(); this.objectExistLimiter = RateLimiter.create(objectExistLimit < 1 ? Double.MAX_VALUE : objectExistLimit); }

Target:
S3FileSystemBase( Provider<AbstractBackupPath> pathProvider, ICompression compress, final IConfiguration config, BackupMetrics backupMetrics, BackupNotificationMgr backupNotificationMgr) { super(config, backupMetrics, backupNotificationMgr, pathProvider); this.compress = compress; this.config = config; int threads = config.getBackupThreads(); LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(threads); this.executor = new BlockingSubmitThreadPoolExecutor(threads, queue, config.getUploadTimeout()); this.rateLimiter = RateLimiter.create(1); this.objectExistLimiter = RateLimiter.create(1); configChangeListener(); }
Source:
public void shouldFailedIfToTypeNotMatch() throws Exception { operation.value = Boolean.FALSE; try { operation.xpath = "lists:integer"; operation.run(doc); fail(); } catch (OperationException | UnsupportedOperationException e) { assertEquals("Given type \"false\" value is not a long type", e.getMessage()); } catch (Exception e) { fail(); } }

Target:
public void shouldFailedIfToTypeNotMatch() throws Exception { operation.value = Boolean.FALSE; try { operation.xpath = "lists:integer"; operation.run(doc); fail(); } catch (Exception e) { assertEquals("Given type \"false\" value is not a long type", e.getMessage()); } }
Source:
private static Map parse(Response res) { return GSON.fromJson( res.getBody().asString(), new TypeToken<Map<String, Object>>() {}.getType()); }

Target:
private static Map parse(Response res) { return GSON.fromJson(res.getBody().asString(), MAP_STRING_TO_OBJECT_TYPE); }
Source:
public List<Path> compact(ThroughputController throughputController, User user) throws IOException { if (request instanceof DateTieredCompactionRequest) { return compactor.compact(request, ((DateTieredCompactionRequest) request).getBoundaries(), ((DateTieredCompactionRequest) request).getBoundariesPolicies(), throughputController, user); } else { throw new IllegalArgumentException("DateTieredCompactionRequest is expected. Actual: " + request.getClass().getCanonicalName()); } }

Target:
public List<Path> compact(ThroughputController throughputController, User user) throws IOException { if (request instanceof DateTieredCompactionRequest) { DateTieredCompactionRequest compactionRequest = (DateTieredCompactionRequest) request; return compactor.compact(request, compactionRequest.getBoundaries(), compactionRequest.getBoundariesPolicies(), throughputController, user); } else { throw new IllegalArgumentException("DateTieredCompactionRequest is expected. Actual: " + request.getClass().getCanonicalName()); } }
Source:
public String render() { String swiftGeneratedHeader = String.format("%s-Swift.h", targetName); return headerNames.stream() .filter(x -> !x.equals(swiftGeneratedHeader)) .map(x -> String.format("#import <%s/%s>\n", targetName, x)) .reduce("", String::concat); }

Target:
public String render() { return headerNames.stream() .filter(x -> !headersToExclude.contains(x)) .map(x -> String.format("#import <%s/%s>\n", targetName, x)) .reduce("", String::concat); }
Source:
public void before() { LoggerFactory.getLogger( BlacklistTranslatorTest.class ).info( "Executing test " + testName.getMethodName() ); Map<String, String> headers = new LinkedHashMap<>( 1 ); headers.put( "Foo", "bar" ); this.blacklistTranslator = new DefaultTranslator( mockServer.getUrl(), 0, Translator.CHUNK_SPLIT_COUNT, "", "", headers ); }

Target:
public void before() { LoggerFactory.getLogger( BlacklistTranslatorTest.class ).info( "Executing test " + testName.getMethodName() ); this.blacklistTranslator = new DefaultTranslator( mockServer.getUrl(), 0, Translator.CHUNK_SPLIT_COUNT, "", "" ); }
Source:
public ContentElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { ContentElement.Builder builder = ContentElement.builder(); boolean inContentElement = true; while (inContentElement) { XmlPullParser.Event tag = parser.next(); if (tag == XmlPullParser.Event.START_ELEMENT) { String name = parser.getName(); switch (name) { case ToAffixElement.ELEMENT: parseToAffix(parser, builder); break; case FromAffixElement.ELEMENT: parseFromAffix(parser, builder); break; case TimestampAffixElement.ELEMENT: parseTimestampAffix(parser, builder); break; case RandomPaddingAffixElement.ELEMENT: parseRPadAffix(parser, builder); break; case PayloadElement.ELEMENT: parsePayload(parser, builder); break; default: parseCustomAffix(parser, builder); break; } } else if (tag == XmlPullParser.Event.END_ELEMENT) { String name = parser.getName(); if (name.equals(ContentElement.ELEMENT) && ContentElement.NAMESPACE.equals(parser.getNamespace())) { inContentElement = false; } } } return builder.build(); }

Target:
public ContentElement parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException { ContentElement.Builder builder = ContentElement.builder(); while (true) { XmlPullParser.Event tag = parser.next(); if (tag == XmlPullParser.Event.START_ELEMENT) { String name = parser.getName(); switch (name) { case ToAffixElement.ELEMENT: parseToAffix(parser, builder); break; case FromAffixElement.ELEMENT: parseFromAffix(parser, builder); break; case TimestampAffixElement.ELEMENT: parseTimestampAffix(parser, builder); break; case RandomPaddingAffixElement.ELEMENT: parseRPadAffix(parser, builder); break; case PayloadElement.ELEMENT: parsePayload(parser, xmlEnvironment, builder); break; default: parseCustomAffix(parser, xmlEnvironment, builder); break; } } else if (tag == XmlPullParser.Event.END_ELEMENT) { if (parser.getDepth() == initialDepth) { break; } } } return builder.build(); }
Source:
public <T> Collection<T> services(String name) { if (!enterBusy()) return null; try { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs = Optional.ofNullable(lookupDeployedServiceId(name)) .map(locServices::get).orElse(null); if (F.isEmpty(ctxs)) return null; Collection<T> res = new ArrayList<>(ctxs.size()); for (ServiceContextImpl ctx : ctxs) { Service svc = ctx.service(); if (svc != null) res.add((T)svc); } return res; } finally { leaveBusy(); } }

Target:
@Override public <T> Collection<T> services(String name) { ctx.security().authorize(name, SecurityPermission.SERVICE_INVOKE, null); Collection<ServiceContextImpl> ctxs; synchronized (locSvcs) { ctxs = locSvcs.get(name); } if (ctxs == null) return null; synchronized (ctxs) { Collection<T> res = new ArrayList<>(ctxs.size()); for (ServiceContextImpl ctx : ctxs) { Service svc = ctx.service(); if (svc != null) res.add((T)svc); } return res; } }
Source:
protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map, final StorageDomainStatus status) { executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() { @SuppressWarnings("synthetic-access") @Override public StoragePoolIsoMap runInTransaction() { CompensationContext context = getCompensationContext(); context.snapshotEntityStatus(map, map.getstatus()); map.setstatus(status); getStoragePoolIsoMapDao().updateStatus(map.getId(), map.getstatus()); getCompensationContext().stateChanged(); return null; } }); }

Target:
protected void changeStorageDomainStatusInTransaction(final StoragePoolIsoMap map, final StorageDomainStatus status) { executeInNewTransaction(new TransactionMethod<StoragePoolIsoMap>() { @Override public StoragePoolIsoMap runInTransaction() { CompensationContext context = getCompensationContext(); context.snapshotEntityStatus(map, map.getstatus()); updateStatus(map, status); getCompensationContext().stateChanged(); return null; } }); }
Source:
private void assertValidState(EventAdmin eventAdmin) throws IllegalStateException { if (eventAdmin == null) { throw new IllegalArgumentException("The event bus module is not available!"); } }

Target:
private void assertValidState(EventAdmin eventAdmin) throws IllegalStateException { if (eventAdmin == null) { throw new IllegalStateException("The event bus module is not available!"); } }
Source:
private void assertBigDecimalLiteral(RexBuilder builder, String val) { final RexNode literal = builder.makeExactLiteral(new BigDecimal(val)); assertThat("Generated wrong BigDecimal RexLiteral", ((RexLiteral) literal).getValueAs(BigDecimal.class).toString(), is(val)); }

Target:
private void assertBigDecimalLiteral(RexBuilder builder, String val) { final RexNode literal = builder.makeExactLiteral(new BigDecimal(val)); assertThat("builder.makeExactLiteral(new BigDecimal(" + val + ")).getValueAs(BigDecimal.class).toString()", ((RexLiteral) literal).getValueAs(BigDecimal.class).toString(), is(val)); }
Source:
public final void removeSession(String sessionId) { Iterator<Entry<String, SessionInfo>> iterator = sessionInfoMap.entrySet().iterator(); while (iterator.hasNext()) { if (iterator.next().getKey().equals(sessionId)) { iterator.remove(); break; } } }

Target:
public final void removeSession(String sessionId) { sessionInfoMap.remove(sessionId); }
Source:
void refreshConnection() { if (networkRequest != null) { networkRequest.resetTask(); } if (refreshTokenNetworkRequest != null) { refreshTokenNetworkRequest.resetTask(); } }

Target:
synchronized void refreshConnection() { if (networkRequest != null) { networkRequest.resetTask(); } if (refreshTokenNetworkRequest != null) { refreshTokenNetworkRequest.resetTask(); } }
Source:
protected BookieServer startBookie(ServerConfiguration conf, final Bookie b) throws Exception { BookieServer server = new BookieServer(conf) { @Override protected Bookie newBookie(ServerConfiguration conf) { return b; } }; BookieSocketAddress address = Bookie.getBookieAddress(conf); if (bkc == null) { bkc = new BookKeeperTestClient(baseClientConf); } Future<?> waitForBookie = bkc.waitForBookie(address); server.start(); waitForBookie.get(30, TimeUnit.SECONDS); LOG.info("New bookie, {}, has been created.", address); try { startAutoRecovery(server, conf); } catch (CompatibilityException ce) { LOG.error("Exception while starting AutoRecovery!", ce); } catch (UnavailableException ue) { LOG.error("Exception while starting AutoRecovery!", ue); } return server; }

Target:
protected BookieServer startBookie(ServerConfiguration conf, final Bookie b) throws Exception { BookieServer server = new BookieServer(conf) { @Override protected Bookie newBookie(ServerConfiguration conf) { return b; } }; BookieSocketAddress address = Bookie.getBookieAddress(conf); if (bkc == null) { bkc = new BookKeeperTestClient(baseClientConf); } Future<?> waitForBookie = conf.isForceReadOnlyBookie() ? bkc.waitForReadOnlyBookie(address) : bkc.waitForWritableBookie(address); server.start(); waitForBookie.get(30, TimeUnit.SECONDS); LOG.info("New bookie '{}' has been created.", address); try { startAutoRecovery(server, conf); } catch (CompatibilityException ce) { LOG.error("Exception while starting AutoRecovery!", ce); } catch (UnavailableException ue) { LOG.error("Exception while starting AutoRecovery!", ue); } return server; }
Source:
public List<Thing> parseGeneric(String jsonText, String listingName) throws ParseException, RedditError { List<Thing> things = new LinkedList<Thing>(); Object response = jsonParser.parse(jsonText); validate(response); JSONObject object = (JSONObject) response; System.out.println(object.toJSONString()); JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get(listingName); for (Object element : array) { JSONObject data = (JSONObject) element; String kind = safeJsonToString(data.get("kind")); if (kind == null) { LOGGER.warn("Could not detect kind in a reddit listing element, skipping it."); } else if (kind.equals(Kind.COMMENT.value())) { things.add(new Comment(((JSONObject) data.get("data")))); } else if (kind.equals(Kind.LINK.value())) { things.add(new Submission(((JSONObject) data.get("data")))); } else if (kind.equals(Kind.SUBREDDIT.value())) { things.add(new Subreddit(((JSONObject) data.get("data")))); } } return things; }

Target:
public List<Thing> parseGeneric(String jsonText, String listingName) throws RedditParseException { try { List<Thing> things = new LinkedList<Thing>(); Object response = JSON_PARSER.parse(jsonText); validate(response); JSONObject object = (JSONObject) response; JSONArray array = (JSONArray) ((JSONObject) object.get("data")).get(listingName); for (Object element : array) { JSONObject data = (JSONObject) element; String kindData = safeJsonToString(data.get("kind")); Object objData = data.get("data"); if (kindData == null) { LOGGER.warn("Kind data missing, skipping it."); } else if (objData == null || !(objData instanceof JSONObject)) { LOGGER.warn("Object data missing, skipping it."); } else { Kind kind = Kind.match(kindData); Thing thing = parseThing(kind, ((JSONObject) data.get("data"))); if (thing == null) { LOGGER.warn("Encountered invalid kind for a listing (" + kindData + "), skipping it."); } else { things.add(thing); } } } return things; } catch (ParseException pe) { throw new RedditParseException(pe); } }
Source:
private static void findAtomic(Queue<PostfixNotationSymbol> queue, Deque<Set<Long>> stack, AtomicOperation atomic) { Preconditions.checkArgument(stack.isEmpty()); for (PostfixNotationSymbol symbol : queue) { if(symbol == ConjunctionSymbol.AND) { stack.push(TSets.intersection(stack.pop(), stack.pop())); } else if(symbol == ConjunctionSymbol.OR) { stack.push(TSets.union(stack.pop(), stack.pop())); } else if(symbol instanceof Expression) { Expression exp = (Expression) symbol; if(exp.getKeyRaw().equals( Constants.JSON_RESERVED_IDENTIFIER_NAME)) { Set<Long> idSet; if(exp.getOperatorRaw() == (Operator.EQUALS)) { idSet = Sets.newTreeSet(); for (TObject tObj : exp.getValuesRaw()) { idSet.add(((Number) Convert.thriftToJava(tObj)) .longValue()); } stack.push(idSet); } else if(exp.getOperatorRaw() == (Operator.NOT_EQUALS)) { idSet = atomic.getAllRecords(); for (TObject tObj : exp.getValuesRaw()) { idSet.remove(((Number) Convert.thriftToJava(tObj)) .longValue()); } stack.push(idSet); } else { throw new IllegalArgumentException(); } } else { stack.push(exp.getTimestampRaw() == 0 ? atomic.find( exp.getKeyRaw(), exp.getOperatorRaw(), exp.getValuesRaw()) : atomic.find( exp.getTimestampRaw(), exp.getKeyRaw(), exp.getOperatorRaw(), exp.getValuesRaw())); } } else { throw new IllegalStateException(); } } }

Target:
private static void findAtomic(Queue<PostfixNotationSymbol> queue, Deque<Set<Long>> stack, AtomicOperation atomic) { Preconditions.checkArgument(stack.isEmpty()); for (PostfixNotationSymbol symbol : queue) { if(symbol == ConjunctionSymbol.AND) { stack.push(TSets.intersection(stack.pop(), stack.pop())); } else if(symbol == ConjunctionSymbol.OR) { stack.push(TSets.union(stack.pop(), stack.pop())); } else if(symbol instanceof Expression) { Expression exp = (Expression) symbol; if(exp.getKeyRaw().equals( Constants.JSON_RESERVED_IDENTIFIER_NAME)) { Set<Long> idSet; if(exp.getOperatorRaw() == (Operator.EQUALS)) { idSet = Sets.newTreeSet(); for (TObject tObj : exp.getValuesRaw()) { idSet.add(((Number) Convert.thriftToJava(tObj)) .longValue()); } stack.push(idSet); } else if(exp.getOperatorRaw() == (Operator.NOT_EQUALS)) { idSet = atomic.getAllRecords(); for (TObject tObj : exp.getValuesRaw()) { idSet.remove(((Number) Convert.thriftToJava(tObj)) .longValue()); } stack.push(idSet); } else { System.out.println("Cannot query on record id using "+exp.getOperatorRaw()); throw new IllegalArgumentException(); } } else { stack.push(exp.getTimestampRaw() == 0 ? atomic.find( exp.getKeyRaw(), exp.getOperatorRaw(), exp.getValuesRaw()) : atomic.find( exp.getTimestampRaw(), exp.getKeyRaw(), exp.getOperatorRaw(), exp.getValuesRaw())); } } else { throw new IllegalStateException(); } } }