auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Object fromURL(java.net.URL url) throws JsonParseException, IOException { MappingJsonFactory jsonFactory = new MappingJsonFactory(); URLConnection conn = url.openConnection(); conn.addRequestProperty("Accept", "application/ld+json);"); conn.addRequestProperty("Accept", "application/json;q=0.9, " + "application/javascript;q=0.5, text/javascript;q=0.5, text/plain;q=0.2, " + "*/*;q=0.1"); InputStream in = conn.getInputStream(); try { JsonParser parser = jsonFactory.createParser(in); JsonToken token = parser.nextToken(); Class<?> type; if (token == JsonToken.START_OBJECT) { type = Map.class; } else if(token == JsonToken.START_ARRAY) { type = List.class; } else { type = String.class; } try { return parser.readValueAs(type); } finally { parser.close(); } } finally { in.close(); } }

Target:
public static Object fromURL(java.net.URL url) throws JsonParseException, IOException { MappingJsonFactory jsonFactory = new MappingJsonFactory(); InputStream in = openStreamFromURL(url); try { JsonParser parser = jsonFactory.createParser(in); JsonToken token = parser.nextToken(); Class<?> type; if (token == JsonToken.START_OBJECT) { type = Map.class; } else if(token == JsonToken.START_ARRAY) { type = List.class; } else { type = String.class; } try { return parser.readValueAs(type); } finally { parser.close(); } } finally { in.close(); } }
Source:
public void render(Screen screen) { Bitmap[][] sheet = Art.getLocalPlayerArt(); if(Options.getAsBoolean(Options.ALTERNATIVE)) { sheet = Art.duchessDonut; } if (team == Team.Team2) { sheet = Art.herrSpeck; } if (dead) { return; } int frame = (walkTime / 4 % 6 + 6) % 6; int facing = this.facing + (carrying != null ? 8 : 0); double xmuzzle = muzzleX + ((facing == 0) ? 4 : 0); double ymuzzle = muzzleY - ((facing == 0) ? 4 : 0); boolean behind = (facing >= 3 && facing <= 5); if (muzzleTicks > 0 && behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } if (hurtTime % 2 != 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ff0000); } else if (flashTime > 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ffff80); } else { screen.blit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8); } if (muzzleTicks > 0 && !behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } renderCarrying(screen, (frame == 0 || frame == 3) ? -1 : 0); }

Target:
public void render(Screen screen) { Bitmap[][] sheet = Art.getLocalPlayerArt(); if (dead) { return; } int frame = (walkTime / 4 % 6 + 6) % 6; int facing = this.facing + (carrying != null ? 8 : 0); double xmuzzle = muzzleX + ((facing == 0) ? 4 : 0); double ymuzzle = muzzleY - ((facing == 0) ? 4 : 0); boolean behind = (facing >= 3 && facing <= 5); if (muzzleTicks > 0 && behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } if (hurtTime % 2 != 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ff0000); } else if (flashTime > 0) { screen.colorBlit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8, 0x80ffff80); } else { screen.blit(sheet[frame][facing], pos.x - Tile.WIDTH / 2, pos.y - Tile.HEIGHT / 2 - 8); } if (muzzleTicks > 0 && !behind) { screen.blit(Art.muzzle[muzzleImage][0], xmuzzle, ymuzzle); } renderCarrying(screen, (frame == 0 || frame == 3) ? -1 : 0); }
Source:
public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, LedgerType.PD_JOURNAL) .initiateAdv((long)(-1)); } finally { closeLock.readLock().unlock(); } }

Target:
public void asyncCreateLedgerAdv(final int ensSize, final int writeQuorumSize, final int ackQuorumSize, final DigestType digestType, final byte[] passwd, final CreateCallback cb, final Object ctx, final Map<String, byte[]> customMetadata) { if (writeQuorumSize < ackQuorumSize) { throw new IllegalArgumentException("Write quorum must be larger than ack quorum"); } closeLock.readLock().lock(); try { if (closed) { cb.createComplete(BKException.Code.ClientClosedException, null, ctx); return; } new LedgerCreateOp(BookKeeper.this, ensSize, writeQuorumSize, ackQuorumSize, digestType, passwd, cb, ctx, customMetadata, LedgerType.PD_JOURNAL) .initiateAdv(BookieProtocol.INVALID_LEDGER_ID); } finally { closeLock.readLock().unlock(); } }
Source:
public boolean equalsWrappedBytes(WrappedBytes other) { return Arrays.equals(bytes, other.getBytes()); }

Target:
public boolean equalsWrappedBytes(WrappedBytes other) { int length = getLength(); if (other.getLength() != length) return false; if (other.hashCode() != hashCode()) return false; for (int i = 0; i < length; ++i) { if (getByte(i) != other.getByte(i)) return false; } return true; }
Source:
public void setItems(Collection value) { genVersionToBaseTemplate(value); final List<VmTemplate> sortedValues = sortTemplates(value); super.setItems(sortedValues); }

Target:
public void setItems(Collection value) { genVersionToBaseTemplate(value); super.setItems(value); }
Source:
@Override public boolean isAlwaysFalse() { switch (getKind()) { case IS_NOT_NULL: return operands.get(0).isAlwaysNull(); case IS_NULL: case IS_UNKNOWN: return !operands.get(0).getType().isNullable(); case IS_FALSE: case IS_NOT_TRUE: case NOT: return operands.get(0).isAlwaysTrue(); case IS_NOT_FALSE: case IS_TRUE: case CAST: case MAX: case MIN: return operands.get(0).isAlwaysFalse(); case OR: for (RexNode operand : operands) { if (!operand.isAlwaysFalse()) { return false; } } return true; case AND: for (RexNode operand : operands) { if (operand.isAlwaysFalse()) { return true; } } return false; case EQUALS: case NOT_EQUALS: { RexNode o0 = operands.get(0); RexNode o1 = operands.get(1); if (!getType().isNullable() && o0.equals(o1)) { return getKind() == SqlKind.NOT_EQUALS; } int k0 = o0.isAlwaysTrue() ? 1 : (o0.isAlwaysFalse() ? 2 : 0); if (k0 != 0) { int k1 = o1.isAlwaysTrue() ? 1 : (o1.isAlwaysFalse() ? 2 : 0); return k1 != 0 && k0 != k1 ^ (getKind() != SqlKind.EQUALS); } return false; } default: return false; } }

Target:
@Override public boolean isAlwaysFalse() { switch (getKind()) { case IS_NOT_NULL: return operands.get(0).isAlwaysNull(); case IS_NULL: case IS_UNKNOWN: return !operands.get(0).getType().isNullable(); case IS_FALSE: case IS_NOT_TRUE: case NOT: return operands.get(0).isAlwaysTrue(); case IS_NOT_FALSE: case IS_TRUE: case CAST: return operands.get(0).isAlwaysFalse(); default: return false; } }
Source:
public void setup() { StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder() .applySetting( PREFIX + "backends.elasticsearchBackend_1.type", ElasticsearchBackendFactory.class.getName() ) .applySetting( PREFIX + "indexes.default.backend", "elasticsearchBackend_1" ) .applySetting( PREFIX + "backends.elasticsearchBackend_1.log.json_pretty_printing", true ) .applySetting( PREFIX + "backends.elasticsearchBackend_1." + SearchBackendElasticsearchSettings.ANALYSIS_CONFIGURER, new LibraryAnalysisConfigurer() ) .applySetting( org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP ) .applySetting( SearchOrmSettings.INDEXING_STRATEGY, IndexingStrategyConfiguration.MANUAL ); ServiceRegistry serviceRegistry = registryBuilder.build(); MetadataSources ms = new MetadataSources( serviceRegistry ) .addAnnotatedClass( Document.class ) .addAnnotatedClass( Book.class ) .addAnnotatedClass( Video.class ) .addAnnotatedClass( Library.class ) .addAnnotatedClass( DocumentCopy.class ) .addAnnotatedClass( BookCopy.class ) .addAnnotatedClass( VideoCopy.class ) .addAnnotatedClass( Person.class ) .addAnnotatedClass( Account.class ) .addAnnotatedClass( Borrowal.class ); Metadata metadata = ms.buildMetadata(); final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder(); this.sessionFactory = sfb.build(); withinTransaction( sessionFactory, this::initData ); withinTransaction( sessionFactory, this::invokeMassIndexing ); }

Target:
public void setup() { StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder() .applySetting( PREFIX + "backends.elasticsearchBackend_1.type", ElasticsearchBackendFactory.class.getName() ) .applySetting( PREFIX + "indexes.default.backend", "elasticsearchBackend_1" ) .applySetting( PREFIX + "backends.elasticsearchBackend_1.log.json_pretty_printing", true ) .applySetting( PREFIX + "backends.elasticsearchBackend_1." + SearchBackendElasticsearchSettings.ANALYSIS_CONFIGURER, new LibraryAnalysisConfigurer() ) .applySetting( org.hibernate.cfg.AvailableSettings.HBM2DDL_AUTO, Action.CREATE_DROP ) .applySetting( SearchOrmSettings.INDEXING_STRATEGY, IndexingStrategyConfiguration.MANUAL ); ServiceRegistry serviceRegistry = registryBuilder.build(); MetadataSources ms = new MetadataSources( serviceRegistry ) .addAnnotatedClass( Document.class ) .addAnnotatedClass( Book.class ) .addAnnotatedClass( Video.class ) .addAnnotatedClass( Library.class ) .addAnnotatedClass( DocumentCopy.class ) .addAnnotatedClass( BookCopy.class ) .addAnnotatedClass( VideoCopy.class ) .addAnnotatedClass( Person.class ) .addAnnotatedClass( Account.class ) .addAnnotatedClass( Borrowal.class ); Metadata metadata = ms.buildMetadata(); final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder(); this.sessionFactory = sfb.build(); withinTransaction( sessionFactory, this::initData ); }
Source:
public boolean isStep() { if (content.size() > 0) { int type = getTokenType(0); if (type == Token.QNAME || type == Token.WILDCARD || type == Token.NSWILDCARD || type == Token.AT || type == Token.DOT || type == Token.DBL_DOT) { return true; } else if (content.get(0) instanceof ASTNodeFunctionCall) { String name = ((ASTNodeFunctionCall)content.get(0)).name.toString(); return (name.equals("node") || name.equals("text") || name.equals("comment") || name.equals("processing-instruction")); } else { return false; } } else { return false; } }

Target:
public boolean isStep() { if (size() > 0) { int type = getTokenType(0); if (type == Token.QNAME || type == Token.WILDCARD || type == Token.NSWILDCARD || type == Token.AT || type == Token.DOT || type == Token.DBL_DOT) { return true; } else if (content.get(0) instanceof ASTNodeFunctionCall) { String name = ((ASTNodeFunctionCall)content.get(0)).name.toString(); return (name.equals("node") || name.equals("text") || name.equals("comment") || name.equals("processing-instruction")); } else { return false; } } else { return false; } }
Source:
public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ListModel<?>) { ListModel<?> listmodel = (ListModel<?>) base; Integer idx = coerce(property); boolean itemIdx = true; if (idx == null) { itemIdx = false; if (property instanceof String) { try { property = Fields.get(base, (String) property); } catch (NoSuchMethodException e) { } idx = coerce(property); } if (idx == null) { return null; } } context.setPropertyResolved(true); if (idx >= 0 && idx < listmodel.getSize() && itemIdx == true) { return listmodel.getElementAt(idx); } else if (itemIdx == false) { return idx; } } return null; }

Target:
public Object getValue(ELContext context, Object base, Object property) throws NullPointerException, PropertyNotFoundException, ELException { if (context == null) { throw new NullPointerException(); } if (base instanceof ListModel<?>) { ListModel<?> listmodel = (ListModel<?>) base; Integer idx = coerce(property); if (idx == null) { return null; } context.setPropertyResolved(true); if (idx >= 0 && idx < listmodel.getSize()) { return listmodel.getElementAt(idx); } } return null; }
Source:
public Factory<PaxosAcceptorNetworkClient> acceptor() { return client -> { List<PaxosAcceptor> remoteAcceptors = TimelockPaxosAcceptorAdapter .wrap(useCase(), remoteClients()) .apply(client); PaxosAcceptor localAcceptor = components().acceptor(client); LocalAndRemotes<PaxosAcceptor> allAcceptors = LocalAndRemotes.of(localAcceptor, remoteAcceptors); return new SingleLeaderAcceptorNetworkClient( allAcceptors.all(), quorumSize(), allAcceptors.withSharedExecutor(sharedExecutor())); }; }

Target:
public Factory<PaxosAcceptorNetworkClient> acceptor() { return client -> { List<PaxosAcceptor> remoteAcceptors = TimelockPaxosAcceptorAdapter .wrap(useCase(), remoteClients()) .apply(client); PaxosAcceptor localAcceptor = components().acceptor(client); LocalAndRemotes<PaxosAcceptor> allAcceptors = LocalAndRemotes.of(localAcceptor, remoteAcceptors) .enhanceRemotes(remote -> metrics().instrument(PaxosAcceptor.class, remote, client)); SingleLeaderAcceptorNetworkClient uninstrumentedAcceptor = new SingleLeaderAcceptorNetworkClient( allAcceptors.all(), quorumSize(), allAcceptors.withSharedExecutor(sharedExecutor())); return metrics().instrument(PaxosAcceptorNetworkClient.class, uninstrumentedAcceptor); }; }
Source:
private void createPodPathControls(Composite parent, DataBindingContext dbc) { Label deployPathLabel = new Label(parent, SWT.NONE); deployPathLabel.setText("Pod Deployment Path: "); applyAlignData(SWT.BEGINNING, SWT.CENTER,deployPathLabel); deployPathText = new Text(parent, SWT.BORDER); applyGridData(2, 1, SWT.FILL, SWT.CENTER,true, false,deployPathText); deployPathModifyListener = new ModifyListener() { public void modifyText(ModifyEvent e) { execute(new ServerWorkingCopyPropertyTextCommand(input.getServer(), "Set Deploy Path", deployPathText, deployPathText.getText(), OpenShiftServerUtils.ATTR_POD_PATH, this)); } }; ModifyListener deployPathDecoration = new TextboxDecoratorSupport(deployPathText, new IValidator() { @Override public IStatus validate(Object value) { if (!(value instanceof String) || StringUtils.isEmpty(value)) { return ValidationStatus.cancel("Please provide a path to deploy to on the pod."); } if (!Path.isValidPosixPath((String)value)) { return ValidationStatus.error("Please provide a valid path to deploy to on the pod"); } return Status.OK_STATUS; } }); deployPathText.addModifyListener(deployPathDecoration); }

Target:
private void createPodPathControls(Composite parent, DataBindingContext dbc) { Label deployPathLabel = new Label(parent, SWT.NONE); deployPathLabel.setText("Pod Deployment Path: "); GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.CENTER).applyTo(deployPathLabel); deployPathText = new Text(parent, SWT.BORDER); GridDataFactory.fillDefaults().span(2,1).align(SWT.FILL, SWT.CENTER).grab(true, false).applyTo(deployPathText); deployPathModifyListener = new ModifyListener() { @Override public void modifyText(ModifyEvent e) { execute(new ServerWorkingCopyPropertyTextCommand(input.getServer(), "Set Deploy Path", deployPathText, deployPathText.getText(), OpenShiftServerUtils.ATTR_POD_PATH, (ModifyListener) this)); } }; ModifyListener deployPathDecoration = new TextboxDecoratorSupport(deployPathText, value -> { if (!(value instanceof String) || StringUtils.isEmpty(value)) { return ValidationStatus.cancel("Please provide a path to deploy to on the pod."); } if (!Path.isValidPosixPath((String)value)) { return ValidationStatus.error("Please provide a valid path to deploy to on the pod"); } return Status.OK_STATUS; }); deployPathText.addModifyListener(deployPathDecoration); }
Source:
private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); Instant now = Instant.now(); Files.setLastModifiedTime(probe, FileTime.from(now)); FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant tset = t1.toInstant(); while (t2.compareTo(t1) <= 0) { tset = tset.plusNanos(1); Files.setLastModifiedTime(probe, FileTime.from(tset)); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); saveFileTimeResolution(s, fsResolution.plus(clockResolution)); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }

Target:
private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); Instant now = Instant.now(); Files.setLastModifiedTime(probe, FileTime.from(now)); FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant t1i = t1.toInstant(); for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 200) { Files.setLastModifiedTime(probe, FileTime.from(t1i.plusNanos(i * 1000))); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); fsResolution = fsResolution.plus(clockResolution); saveFileTimeResolution(s, fsResolution); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }
Source:
public double getArmorRemainingPercent() { if(getPosition() == null) { return 100; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 100; } return (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition())) / (initialBuildingCF + initialBuildingArmor); }

Target:
public double getArmorRemainingPercent() { if(getPosition() == null) { return 1.0; } Building occupiedStructure = getGame().getBoard().getBuildingAt(getPosition()); if((occupiedStructure == null) || (initialBuildingCF + initialBuildingArmor == 0)) { return 1.0; } return (occupiedStructure.getCurrentCF(getPosition()) + occupiedStructure.getArmor(getPosition())) / (initialBuildingCF + initialBuildingArmor); }
Source:
private LoadingCache<String, TransportNetwork> createCache(int size) { RemovalListener<String, TransportNetwork> removalListener = removalNotification -> { String id = removalNotification.getKey(); if (sourceBucket != null) { String[] extensions = {".db", ".db.p", ".zip"}; for (String type : extensions) { File file = new File(cacheDir, id + type); file.delete(); } } }; return CacheBuilder.newBuilder() .maximumSize(size) .removalListener(removalListener) .build(new CacheLoader() { public TransportNetwork load(Object s) throws Exception { return getNetwork((String) s); } }); }

Target:
private LoadingCache createCache(int size) { RemovalListener<String, TransportNetwork> removalListener = removalNotification -> { String id = removalNotification.getKey(); if (sourceBucket != null) { String[] extensions = {".db", ".db.p", ".zip"}; for (String type : extensions) { File file = new File(cacheDir, id + type); file.delete(); } } }; return CacheBuilder.newBuilder() .maximumSize(size) .removalListener(removalListener) .build(new CacheLoader() { public TransportNetwork load(Object s) throws Exception { return loadNetwork((String) s); } }); }
Source:
private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { String engineSessionId = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)).getActionReturnValue(); if (StringUtils.isNotEmpty(engineSessionId)) { try { VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, new VdcQueryParametersBase(), new EngineContext().withSessionId(engineSessionId)); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } } return jsonVms; }

Target:
private List<Map<String, String>> availableConsoles(String userIdAsString) { List<Map<String, String>> jsonVms = new ArrayList<>(); Guid userGuid = null; try { if (StringUtils.isNotEmpty(userIdAsString)) { userGuid = Guid.createGuidFromString(userIdAsString); } } catch (IllegalArgumentException e) { log.debug("Could not read User GUID"); } if (userGuid != null) { VdcReturnValueBase loginResult = backend.runInternalAction(VdcActionType.LoginOnBehalf, new LoginOnBehalfParameters(userGuid)); if (!loginResult.getSucceeded()) { throw new RuntimeException("Unable to create session using LoginOnBehalf"); } String engineSessionId = loginResult.getActionReturnValue(); try { VdcQueryReturnValue retVms = backend.runInternalQuery(VdcQueryType.GetAllVms, new VdcQueryParametersBase(), new EngineContext().withSessionId(engineSessionId)); if (retVms != null) { List<VM> vmsList = retVms.getReturnValue(); for (VM vm : vmsList) { Map<String, String> jsonVm = new HashMap<String, String>(); if (vm.getRunOnVds() != null) { VdcQueryReturnValue retValue = backend.runInternalQuery(VdcQueryType.GetVdsByVdsId, new IdQueryParameters(vm.getRunOnVds())); if (retValue != null && retValue.getReturnValue() != null) { VDS vds = (VDS) retValue.getReturnValue(); jsonVm.put("vmid", vm.getId().toString()); jsonVm.put("vmname", vm.getName()); jsonVm.put("host", vds.getHostName()); jsonVm.put("console", "default"); jsonVms.add(jsonVm); } } } } } finally { backend.runInternalAction(VdcActionType.LogoutSession, new VdcActionParametersBase(engineSessionId)); } } return jsonVms; }
Source:
public long fetchLastModifiedDate(SyncManager syncManager, String objectType, String objectId) throws JSONException, IOException { boolean isNewer = false; long serverLastModified = -1L; final String query = SOQLBuilder.getInstanceWithFields(Constants.LAST_MODIFIED_DATE) .from(objectType) .where(Constants.ID + " = '" + objectId + "'") .build(); RestResponse lastModResponse = syncManager.sendSyncWithSmartSyncUserAgent(RestRequest.getRequestForQuery(syncManager.apiVersion, query)); if (lastModResponse != null && lastModResponse.isSuccess()) { final JSONObject responseJSON = lastModResponse.asJSONObject(); if (responseJSON != null) { final JSONArray records = responseJSON.optJSONArray(Constants.RECORDS); if (records != null && records.length() > 0) { final JSONObject obj = records.optJSONObject(0); if (obj != null) { final String lastModStr = obj.optString(Constants.LAST_MODIFIED_DATE); if (!TextUtils.isEmpty(lastModStr)) { try { serverLastModified = Constants.TIMESTAMP_FORMAT.parse(lastModStr).getTime(); } catch (ParseException e) { Log.e("SyncUpTarget:fetchLastModifiedDate", "Error during date parsing", e); } } } } } } return serverLastModified; }

Target:
public String fetchLastModifiedDate(SyncManager syncManager, String objectType, String objectId) throws JSONException, IOException { final String query = SOQLBuilder.getInstanceWithFields(Constants.LAST_MODIFIED_DATE) .from(objectType) .where(Constants.ID + " = '" + objectId + "'") .build(); RestResponse lastModResponse = syncManager.sendSyncWithSmartSyncUserAgent(RestRequest.getRequestForQuery(syncManager.apiVersion, query)); return lastModResponse.asJSONObject().optJSONArray(Constants.RECORDS).optJSONObject(0).optString(Constants.LAST_MODIFIED_DATE); }
Source:
public void testInvalidXpath() throws IOException { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final Path file = Files.createTempFile("", ""); Files.write(file, fileContent.getBytes(StandardCharsets.UTF_8)); try { XpathUtil.printXpathBranch("\\ file.toFile()); fail("Should end with exception"); } catch (CheckstyleException ex) { final String expectedMessage = "Error during xpath evaluation"; assertEquals("Exception message is different", expectedMessage, ex.getMessage()); } }

Target:
public void testInvalidXpath() throws IOException { final String fileContent = "class Test { public void method() {int a = 5; int b = 5;}}"; final File file = tempFolder.newFile(); Files.write(file.toPath(), fileContent.getBytes(StandardCharsets.UTF_8)); final String invalidXpath = "\\ try { XpathUtil.printXpathBranch(invalidXpath, file); fail("Should end with exception"); } catch (CheckstyleException ex) { final String expectedMessage = "Error during evaluation for xpath: " + invalidXpath + ", file: " + file.getCanonicalPath(); assertThat("Exception message is different", ex.getMessage(), is(expectedMessage)); } }
Source:
public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", "Teammates Institute", "American", GenderType.OTHER, new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); assertEquals(studentProfile.getGender(), profileAttributes.gender); assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }

Target:
public void testValueOf() { StudentProfile studentProfile = new StudentProfile("id", "Joe", "joe@gmail.com", "Teammates Institute", "American", GenderType.MALE, new Text("hello"), new BlobKey("key")); StudentProfileAttributes profileAttributes = StudentProfileAttributes.valueOf(studentProfile); assertEquals(studentProfile.getGoogleId(), profileAttributes.googleId); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getShortName(), profileAttributes.shortName); assertEquals(studentProfile.getEmail(), profileAttributes.email); assertEquals(studentProfile.getInstitute(), profileAttributes.institute); assertEquals(studentProfile.getNationality(), profileAttributes.nationality); assertEquals(studentProfile.getGender(), profileAttributes.gender); assertEquals(studentProfile.getMoreInfo().getValue(), profileAttributes.moreInfo); assertEquals(studentProfile.getPictureKey().getKeyString(), profileAttributes.pictureKey); }
Source:
private void createChannel() { NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); mChannel.setDescription(CHANNEL_DESCRIPTION); mChannel.setShowBadge(true); mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); mNotificationManager.createNotificationChannel(mChannel); }

Target:
private void createChannel() { NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE); if (mNotificationManager == null) { return; } NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT); mChannel.setDescription(CHANNEL_DESCRIPTION); mChannel.setShowBadge(true); mChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC); mNotificationManager.createNotificationChannel(mChannel); }
Source:
public static TraceLogLevel valueOfString(String name) { if (name == null) { throw new InvalidParameterException(); } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } return LEVEL_UNKNOWN; }

Target:
public static TraceLogLevel valueOfString(String name) { if (name == null) { throw new IllegalArgumentException(); } for (TraceLogLevel tllevel : TraceLogLevel.values()) { if (tllevel.getInName().equalsIgnoreCase(name)) { return tllevel; } } return LEVEL_UNKNOWN; }
Source:
private List<Device> findDevices(final List<DeviceModel> deviceModels) { LOGGER.info("Trying to find devices for device models for manufacturer..."); final List<Device> devices = new ArrayList<>(); for (final DeviceModel deviceModel : deviceModels) { final List<Device> devs = this.deviceRepository.findByDeviceModelAndInMaintenanceFalse(deviceModel); devices.addAll(devs); } if (devices.isEmpty()) { LOGGER.warn("No devices found for device models for manufacturer"); } else { LOGGER.info("{} devices found for device models for manufacturer", devices.size()); } return devices; }

Target:
private List<Device> findDevices(final List<DeviceModel> deviceModels) { LOGGER.info("Trying to find devices for device models for manufacturer..."); final List<Device> devices = new ArrayList<>(); for (final DeviceModel deviceModel : deviceModels) { final List<Device> devs = this.deviceRepository.findByDeviceModelAndDeviceTypeAndInMaintenance(deviceModel, Ssld.SSLD_TYPE, false); devices.addAll(devs); } if (devices.isEmpty()) { LOGGER.warn("No devices found for device models for manufacturer"); } else { LOGGER.info("{} devices found for device models for manufacturer", devices.size()); } return devices; }
Source:
private void addDefinedContracts() { Parameters contractEmulations = getMergedParameters(Constants.DEFINE_CONTRACT); contracts.collectContracts("emulated", contractEmulations); }

Target:
private void addDefinedContracts() { Parameters definedContracts = getMergedParameters(Constants.DEFINE_CONTRACT); contracts.collectContracts(Constants.DEFINE_CONTRACT, definedContracts); }
Source:
private static void sortStudentResultList(List<StudentAttributes> studentList) { studentList.sort(Comparator.comparing((StudentAttributes student) -> student.course) .thenComparing(student -> student.section) .thenComparing(student -> student.team) .thenComparing(student -> student.name) .thenComparing(student -> student.name)); }

Target:
private static void sortStudentResultList(List<StudentAttributes> studentList) { studentList.sort(Comparator.comparing((StudentAttributes student) -> student.course) .thenComparing(student -> student.section) .thenComparing(student -> student.team) .thenComparing(student -> student.name) .thenComparing(student -> student.email)); }
Source:
public ImmutableSet<E> getDirectParents(E element) { final ImmutableSet.Builder<E> builder = ImmutableSet.builder(); builder.addAll(graph.getDirectParents(element)); return builder.build(); }

Target:
public ImmutableSet<E> getDirectParents(E element) { return ImmutableSet.copyOf(graph.getDirectParents(element)); }
Source:
public boolean startup( IPentahoSession session ) { Response status; Map<String, JSONObject> jsonFiles = new HashMap<>(); try { if ( environmentVariablesFilepath != null ) { JSONObject environmentVariables = getJsonFromFile( new File( environmentVariablesFilepath ) ); jsonFiles.put( environmentVariablesFilepath, environmentVariables ); } else { jsonFiles = parseJsonFiles(); } for ( String filename : jsonFiles.keySet() ) { JSONObject json = jsonFiles.get( filename ); WorkItemRequestPayload payload = new WorkItemRequestPayload( json ); if ( !payload.isValid() ) { logger.error( "File: " + filename + " is missing required parameters, skipping" ); } else { status = issueRequest( payload ); if ( status == null ) { logger.error( "File: " + filename + " has parameters formatted in an unparsable way. Could not process work item." ); } } renameFile( filename ); } } catch ( ParseException | IOException | SecurityException e ) { logger.error( e.getMessage(), e ); } return true; }

Target:
public boolean startup( IPentahoSession session ) { Response status; Map<String, JSONObject> jsonFiles = new HashMap<>(); if ( environmentVariablesFilepath != null ) { JSONObject environmentVariables = getJsonFromFile( new File( environmentVariablesFilepath ) ); jsonFiles.put( environmentVariablesFilepath, environmentVariables ); } else { jsonFiles = parseJsonFiles(); } for ( String filename : jsonFiles.keySet() ) { JSONObject json = jsonFiles.get( filename ); WorkItemRequestPayload payload = new WorkItemRequestPayload( json ); if ( !payload.isValid() ) { logger.error( "File: " + filename + " is missing required parameters, skipping" ); renameFile( filename ); } else { try { status = issueRequest( payload ); if ( status == null ) { logger.error( "File: " + filename + " has parameters formatted in an unparsable way. Could not process work item." ); } } catch ( Exception e ) { logger.error( "Error processing " + filename + " skipping" ); } finally { renameFile( filename ); } } } return true; }
Source:
public String getValue(DynamicOptions dynamicOptions) { if (value != null) { return value; } else if (dynamicOptions.getVariableOptionIndex() != 1){ return variableValues.get(dynamicOptions.getVariableOptionIndex()); } else if (templateBuilder != null) { return templateBuilder.build(dynamicOptions.getEvent()); } else { return null; } }

Target:
public String getValue(DynamicOptions dynamicOptions) { if (dynamicOptions.getVariableOptionIndex() != -1 && !variableValues.isEmpty()) { return variableValues.get(dynamicOptions.getVariableOptionIndex()); } else if (value != null) { return value; } else if (templateBuilder != null) { return templateBuilder.build(dynamicOptions.getEvent()); } else { return null; } }
Source:
public Constraint copyOver(RelationalSymbolicValue.Kind kind) { if(kind == GREATER_THAN_OR_EQUAL || kind == LESS_THAN) { return null; } return Constraint.super.copyOver(kind); }

Target:
public Constraint copyOver(RelationalSymbolicValue.Kind kind) { switch (kind) { case LESS_THAN: case GREATER_THAN_OR_EQUAL: return null; case EQUAL: case METHOD_EQUALS: return this; default: return inverse(); } }
Source:
public void testGetConsumerInputPartioning() { int partitionBlockSize = 5; ConsumerCurator curator = Mockito.spy(consumerCurator); when(curator.getInBlockSize()).thenReturn(partitionBlockSize); Map<String, Consumer> consumers = new HashMap<>(); for (int i = 0; i < partitionBlockSize * 5; ++i) { Consumer consumer = new Consumer("consumer-" + i, "user-" + i, owner, ct); consumer.setUuid("uuid-" + i); curator.create(consumer); consumers.put(consumer.getUuid(), consumer); } curator.flush(); Set<String> input = new HashSet<>(); Set<Consumer> expected = new HashSet<>(); for (int i = 0; i < partitionBlockSize * 3 + 1; ++i) { Consumer consumer = consumers.get("uuid-" + i); input.add(consumer.getId()); expected.add(consumer); } Collection<Consumer> output = curator.getConsumers(input); assertEquals(output.size(), expected.size()); for (Consumer consumer : expected) { assertTrue(output.contains(consumer)); } }

Target:
public void testGetConsumerInputPartioning() { int partitionBlockSize = 5; ConsumerCurator curator = Mockito.spy(consumerCurator); when(curator.getInBlockSize()).thenReturn(partitionBlockSize); Map<String, Consumer> consumers = new HashMap<>(); for (int i = 0; i < partitionBlockSize * 5; ++i) { Consumer consumer = new Consumer("consumer-" + i, "user-" + i, owner, ct); consumer.setUuid("uuid-" + i); curator.create(consumer); consumers.put(consumer.getUuid(), consumer); } curator.flush(); Set<String> input = new HashSet<>(); Set<Consumer> expected = new HashSet<>(); for (int i = 0; i < partitionBlockSize * 10; ++i) { Consumer consumer = consumers.get("uuid-" + i); if (consumer != null) { expected.add(consumer); input.add(consumer.getId()); } else { input.add("id-" + i); } } Collection<Consumer> output = curator.getConsumers(input); assertEquals(output.size(), expected.size()); for (Consumer consumer : expected) { assertTrue(output.contains(consumer)); } }
Source:
private void checkForMissedServletContexts() { try { BundleContext context = getContext(); if (context == null) { return; } Collection<ServiceReference<ServletContext>> references = getContext().getServiceReferences(ServletContext.class, null); for (ServiceReference<ServletContext> reference : references) { Bundle refBundle = reference.getBundle(); BundleContext bundlectx = refBundle.getBundleContext(); ServletContext service = bundlectx.getService(reference); if (service.getFilterRegistration(DELEGATING_FILTER) == null) { LOGGER.error( "Platform filter delegate failed to start in time to inject itself into {}. This means the servlet will not properly attach the user subject to requests. Attempting to resolve the issue by restarting the bundle.", refBundle.getSymbolicName(), refBundle.getBundleId(), refBundle.getSymbolicName()); refBundle.stop(); refBundle.start(); } } } catch (InvalidSyntaxException | BundleException e) { LOGGER.error( "Problem checking ServletContexts for DelegateServletFilter injections. One of the servlets running might not have all of the needed filters injected. See debug logs for additional details."); LOGGER.debug("Additional Details:", e); } }

Target:
private void checkForMissedServletContexts() { try { BundleContext context = getContext(); if (context == null) { return; } Collection<ServiceReference<ServletContext>> references = context.getServiceReferences(ServletContext.class, null); for (ServiceReference<ServletContext> reference : references) { Bundle refBundle = reference.getBundle(); BundleContext bundlectx = refBundle.getBundleContext(); ServletContext service = bundlectx.getService(reference); if (service.getFilterRegistration(DELEGATING_FILTER) == null) { LOGGER.error( "Platform filter delegate failed to start in time to inject itself into {}. This means the servlet will not properly attach the user subject to requests. Attempting to resolve the issue by restarting the bundle.", refBundle.getSymbolicName(), refBundle.getBundleId(), refBundle.getSymbolicName()); refBundle.stop(); refBundle.start(); } } } catch (InvalidSyntaxException | BundleException e) { LOGGER.error( "Problem checking ServletContexts for DelegateServletFilter injections. One of the servlets running might not have all of the needed filters injected. A system restart is recommended. See debug logs for additional details."); LOGGER.debug("Additional Details:", e); } }
Source:
public void addNonEmptyError(String error, List<String> errors) { if (!error.isEmpty()) { errors.add(error); } }

Target:
public void addNonEmptyError(String error, List<String> errors) { if (error.isEmpty()) { return; } errors.add(error); }
Source:
public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, EhcacheEntityCreationException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { String message = "Unable to create entity for cluster id " + identifier + ": another client owns the maintenance lease"; LOGGER.error(message); throw new EhcacheEntityCreationException(message); } else { try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { while (true) { ref.create(UUID.randomUUID()); try { EhcacheClientEntity entity = ref.fetchEntity(); try { configure(entity, config); return; } finally { entity.close(); } } catch (EntityNotFoundException e) { } } } catch (EntityNotProvidedException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } catch (EntityVersionMismatchException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { localMaintenance.unlock(); } } } }

Target:
public void create(final String identifier, final ServerSideConfiguration config) throws EntityAlreadyExistsException, EhcacheEntityCreationException { Hold existingMaintenance = maintenanceHolds.get(identifier); Hold localMaintenance = null; if (existingMaintenance == null) { localMaintenance = createAccessLockFor(identifier).tryWriteLock(); } if (existingMaintenance == null && localMaintenance == null) { throw new EhcacheEntityCreationException("Unable to create entity for cluster id " + identifier + ": another client owns the maintenance lease"); } else { try { EntityRef<EhcacheClientEntity, UUID> ref = getEntityRef(identifier); try { while (true) { ref.create(UUID.randomUUID()); try { EhcacheClientEntity entity = ref.fetchEntity(); try { configure(entity, config); return; } finally { entity.close(); } } catch (EntityNotFoundException e) { } } } catch (EntityNotProvidedException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } catch (EntityVersionMismatchException e) { LOGGER.error("Unable to create entity for cluster id {}", identifier, e); throw new AssertionError(e); } } finally { if (localMaintenance != null) { localMaintenance.unlock(); } } } }
Source:
public PrologEnvironment newPrologEnvironment() throws CompileException { PrologEnvironment env; if (cLoader != null) { return envFactory.create(cLoader); } env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }

Target:
public PrologEnvironment newPrologEnvironment() throws CompileException { if (ruleLoader != null) { return envFactory.create(ruleLoader); } PrologEnvironment env = envFactory.create(getClass().getClassLoader()); String rules = getConfig().getPrologRules(); if (rules != null) { PushbackReader in = new PushbackReader(new StringReader(rules), Prolog.PUSHBACK_SIZE); JavaObjectTerm streamObject = new JavaObjectTerm(in); if (!env.execute(Prolog.BUILTIN, "consult_stream", SymbolTerm.intern("rules.pl"), streamObject)) { throw new CompileException("Cannot consult rules.pl " + getProject().getName() + " " + getConfig().getRevision()); } } return env; }
Source:
public void retrieveConfigurationObjects( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.RetrieveConfigurationObjectsRequest request, final String messageType) throws FunctionalException { LOGGER.debug("synchronizeTime for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final RetrieveConfigurationObjectsRequest requestDto = new RetrieveConfigurationObjectsRequest( request.getDeviceIdentification()); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevice.getIpAddress(), requestDto), messageType); }

Target:
public void retrieveConfigurationObjects( @Identification final String organisationIdentification, @Identification final String deviceIdentification, final String correlationUid, final com.alliander.osgp.domain.core.valueobjects.smartmetering.RetrieveConfigurationObjectsRequest request, final String messageType) throws FunctionalException { LOGGER.debug("retrieveConfigurationObjects for organisationIdentification: for deviceIdentification: {}", organisationIdentification, deviceIdentification); final SmartMeter smartMeteringDevice = this.domainHelperService.findSmartMeter(deviceIdentification); final RetrieveConfigurationObjectsRequest requestDto = new RetrieveConfigurationObjectsRequest( request.getDeviceIdentification()); this.osgpCoreRequestMessageSender.send(new RequestMessage(correlationUid, organisationIdentification, deviceIdentification, smartMeteringDevice.getIpAddress(), requestDto), messageType); }
Source:
@Override public FileIO create(File file, OpenOption... modes) throws IOException { if (file.getAbsolutePath().contains("node01-") && file.getAbsolutePath().contains("binary_meta")) throw new IOException("No space left on device"); return delegateFactory.create(file, modes); }

Target:
@Override public FileIO create(File file, OpenOption... modes) throws IOException { if (unluckyConsistentId.get() != null && file.getAbsolutePath().contains(unluckyConsistentId.get()) && file.getAbsolutePath().contains(StandaloneGridKernalContext.BINARY_META_FOLDER)) throw new IOException("No space left on device"); return delegateFactory.create(file, modes); }
Source:
public int serve(List<Path> resultsPaths, Path reportPath) throws IOException { if (notExists()) { throw new FileNotFoundException("Can't find allure installation"); } if (Files.exists(reportPath)) { FileUtils.deleteDirectory(reportPath.toFile()); } CommandLine commandLine = new CommandLine(getAllureExecutablePath().toAbsolutePath().toFile()); commandLine.addArgument("serve"); for (Path resultsPath : resultsPaths) { commandLine.addArgument(resultsPath.toAbsolutePath().toString(), true); } DefaultExecutor executor = new DefaultExecutor(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); executor.setWatchdog(watchdog); executor.setExitValue(0); return executor.execute(commandLine); }

Target:
public int serve(List<Path> resultsPaths, Path reportPath) throws IOException { this.checkAllureExists(); FileUtils.deleteQuietly(reportPath.toFile()); CommandLine commandLine = new CommandLine(getAllureExecutablePath().toAbsolutePath().toFile()); commandLine.addArgument("serve"); for (Path resultsPath : resultsPaths) { commandLine.addArgument(resultsPath.toAbsolutePath().toString(), true); } return execute(commandLine); }
Source:
public void testPassParamsToEndpoint() throws IOException { String requestString = "/context?queryParam=some%20value"; boolean isSpaceCharacterEscaped = false; logViewerClient.clearLogs(); try { HttpRequestUtil.sendGetRequest(getApiInvocationURL("test") + requestString, null); } catch (Exception timeout) { } LogEvent[] logs = logViewerClient.getAllSystemLogs(); for (LogEvent logEvent : logs) { String message = logEvent.getMessage(); if (message.contains("queryParam = some%20value")) { isSpaceCharacterEscaped = true; break; } } Assert.assertTrue(isSpaceCharacterEscaped, "Fail to send a message via REST when query parameter consist of space character"); }

Target:
public void testPassParamsToEndpoint() throws Exception { String requestString = "/context?queryParam=some%20value"; boolean isSpaceCharacterEscaped = false; logViewerClient.clearLogs(); try { HttpRequestUtil.sendGetRequest(getApiInvocationURL("test") + requestString, null); } catch (Exception timeout) { } LogEvent[] logs = logViewerClient.getAllRemoteSystemLogs(); for (LogEvent logEvent : logs) { String message = logEvent.getMessage(); if (message.contains("queryParam = some%20value")) { isSpaceCharacterEscaped = true; break; } } Assert.assertTrue(isSpaceCharacterEscaped, "Fail to send a message via REST when query parameter consist of space character"); }