auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void sanitizeForSaving() { this.courseId = Sanitizer.sanitizeTitle(courseId); this.feedbackQuestionId = Sanitizer.sanitizeTitle(feedbackQuestionId); this.giverEmail = Sanitizer.sanitizeEmail(giverEmail); this.giverSection = Sanitizer.sanitizeTitle(giverSection); this.recipientEmail = Sanitizer.sanitizeEmail(recipientEmail); this.recipientSection = Sanitizer.sanitizeTitle(recipientSection); }

Target:
public void sanitizeForSaving() { }
Source:
ImmutableMap<TypeName, FieldSpec> createFields(List<Property> properties) { ImmutableMap.Builder<TypeName, FieldSpec> fields = ImmutableMap.builder(); ClassName jsonAdapter = ClassName.get(TypeAdapter.class); Set<TypeName> seenTypes = Sets.newHashSet(); NameAllocator nameAllocator = new NameAllocator(); for (Property property : properties) { if (property.shouldNotDeserialize() && !property.shouldNotSerialize()) { continue; } TypeName type = property.type.isPrimitive() ? property.type.box() : property.type; ParameterizedTypeName adp = ParameterizedTypeName.get(jsonAdapter, type); if (!seenTypes.contains(property.type)) { fields.put(property.type, FieldSpec.builder(adp, nameAllocator.newName(simpleName(property.type)) + "_adapter", PRIVATE, VOLATILE) .build()); seenTypes.add(property.type); } } return fields.build(); }

Target:
ImmutableMap<TypeName, FieldSpec> createFields(List<Property> properties) { ImmutableMap.Builder<TypeName, FieldSpec> fields = ImmutableMap.builder(); ClassName jsonAdapter = ClassName.get(TypeAdapter.class); Set<TypeName> seenTypes = Sets.newHashSet(); NameAllocator nameAllocator = new NameAllocator(); for (Property property : properties) { if (property.shouldNotDeserialize() && property.shouldNotSerialize()) { continue; } TypeName type = property.type.isPrimitive() ? property.type.box() : property.type; ParameterizedTypeName adp = ParameterizedTypeName.get(jsonAdapter, type); if (!seenTypes.contains(property.type)) { fields.put(property.type, FieldSpec.builder(adp, nameAllocator.newName(simpleName(property.type)) + "_adapter", PRIVATE, VOLATILE) .build()); seenTypes.add(property.type); } } return fields.build(); }
Source:
public boolean equals(Object obj) { if (this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } try { StringLiteral other = (StringLiteral) obj; return this.equals(other); } catch(ClassCastException e) { return false; } }

Target:
public boolean equals(Object obj) { if (this == obj) { return true; } if(obj == null) { return false; } if(this.getClass() != obj.getClass()) { return false; } try { StringLiteral other = (StringLiteral) obj; return this.getValue().equals(other.getValue()); } catch(ClassCastException e) { return false; } }
Source:
private void collectConfigurationParameters(boolean isUse) { addContextParams(EHadoopParamName.DataBricksEndpoint, isUse); addContextParams(EHadoopParamName.DataBricksCloudProvider, isUse); addContextParams(EHadoopParamName.DataBricksClusterId, isUse); addContextParams(EHadoopParamName.DataBricksToken, isUse); addContextParams(EHadoopParamName.DataBricksDBFSDepFolder, isUse); }

Target:
private void collectConfigurationParameters(boolean isUse) { addContextParams(EHadoopParamName.DataBricksEndpoint, isUse); addContextParams(EHadoopParamName.DataBricksClusterId, isUse); addContextParams(EHadoopParamName.DataBricksToken, isUse); addContextParams(EHadoopParamName.DataBricksDBFSDepFolder, isUse); }
Source:
private void postEvents(List<Event> events) { CloseableHttpResponse response = null; Gson gson = new Gson(); String json = gson.toJson(events); HttpPost request = config.postRequest("/api/events/bulk"); StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); request.setEntity(entity); try { response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { if (status == HttpStatus.SC_UNAUTHORIZED) { logger.info("Invalid API key"); } else { logger.error("Unexpected status code: " + status); } } } catch (IOException e) { logger.error("Unhandled exception in LaunchDarkly client", e); } finally { try { if (response != null) response.close(); } catch (IOException e) { logger.error("Unhandled exception in LaunchDarkly client", e); } } }

Target:
private void postEvents(List<Event> events) { CloseableHttpResponse response = null; Gson gson = new Gson(); String json = gson.toJson(events); HttpPost request = config.postRequest("/api/events/bulk"); StringEntity entity = new StringEntity(json, "UTF-8"); entity.setContentType("application/json"); request.setEntity(entity); try { response = client.execute(request); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { if (status == HttpStatus.SC_UNAUTHORIZED) { logger.error("Invalid API key"); } else { logger.error("Unexpected status code: " + status); } } } catch (IOException e) { logger.error("Unhandled exception in LaunchDarkly client", e); } finally { try { if (response != null) response.close(); } catch (IOException e) { logger.error("Unhandled exception in LaunchDarkly client", e); } } }
Source:
public TtlTimeProvider(Configuration conf) { this.authoritativeDirTtl = conf.getLong(METADATASTORE_METADATA_TTL, DEFAULT_METADATASTORE_METADATA_TTL); }

Target:
public TtlTimeProvider(Configuration conf) { this.authoritativeDirTtl = conf.getTimeDuration(METADATASTORE_METADATA_TTL, DEFAULT_METADATASTORE_METADATA_TTL, TimeUnit.SECONDS); }
Source:
private ProjectConfig getProject(String workspaceId, String projectName) throws Exception { return requestFactory .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) .useGetMethod() .setAuthorizationHeader(machineServiceClient.getMachineApiToken(workspaceId)) .request() .asDto(ProjectConfigDto.class); }

Target:
private ProjectConfig getProject(String workspaceId, String projectName) throws Exception { return requestFactory .fromUrl(workspaceAgentApiEndpointUrlProvider.get(workspaceId) + "project/" + projectName) .useGetMethod() .setAuthorizationHeader( BEARER_TOKEN_PREFIX + machineServiceClient.getMachineApiToken(workspaceId)) .request() .asDto(ProjectConfigDto.class); }
Source:
public void testGetOptionTypeWithoutResults() { prepareAndInitSession(); prepareAndInitSession(); List<String> checkedVariables = Arrays.asList("not-existing1", "not-existing2", "not-existing3", "and_so_on"); String type; for (int i = 0; i < checkedVariables.size(); i++) { type = searchService.getOptionType(checkedVariables.get(i)); assertNotEquals(mockedVariableTypes, type); } }

Target:
public void testGetOptionTypeWithoutResults() { prepareAndInitSession(); prepareAndInitSession(); List<String> checkedVariables = Arrays.asList("not-existing1", "not-existing2", "not-existing3", "and_so_on"); checkedVariables.forEach(checkedVariable -> { String type = searchService.getOptionType(checkedVariable); assertNotEquals(mockedVariableTypes, type); }); }
Source:
public void waitForAllLifespanCommitted() { ListenableFuture<?> future = whenAllSucceed(commitFutures).call(() -> null, directExecutor()); try { getFutureValue(future, PrestoException.class); } catch (RuntimeException e) { future.cancel(true); throw e; } }

Target:
public void waitForAllLifespanCommitted() { ListenableFuture<Void> future = whenAllSucceed(commitFutures).call(() -> null, directExecutor()); try { future.get(); } catch (InterruptedException e) { future.cancel(true); currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { future.cancel(true); propagateIfPossible(e.getCause(), PrestoException.class); throw new RuntimeException(e.getCause()); } }
Source:
private static <K, V, T> List<T> waitUntilFinalKeyValueRecordsReceived(final Properties consumerConfig, final String topic, final List<T> expectedRecords, final long waitTime, final boolean withTimestamp) throws InterruptedException { final List<T> accumData = new ArrayList<>(); try (final Consumer<K, V> consumer = createConsumer(consumerConfig)) { final TestCondition valuesRead = () -> { final List<T> readData; if (withTimestamp) { readData = (List<T>) readKeyValuesWithTimestamp(topic, consumer, waitTime, expectedRecords.size()); } else { readData = (List<T>) readKeyValues(topic, consumer, waitTime, expectedRecords.size()); } accumData.addAll(readData); final List<T> accumulatedActual = accumData.stream().filter(expectedRecords::contains).collect(Collectors.toList()); final Map<K, List<T>> finalAccumData = new HashMap<>(); for (final T kv : accumulatedActual) { finalAccumData.computeIfAbsent( (K) (withTimestamp ? ((KeyValueTimestamp) kv).key() : ((KeyValue) kv).key), key -> new ArrayList<>()).add(kv); } final Map<K, List<T>> finalExpected = new HashMap<>(); for (final T kv : expectedRecords) { finalExpected.computeIfAbsent( (K) (withTimestamp ? ((KeyValueTimestamp) kv).key() : ((KeyValue) kv).key), key -> new ArrayList<>()).add(kv); } System.err.println(finalAccumData); System.err.println(finalExpected); return finalAccumData.equals(finalExpected); }; final String conditionDetails = "Did not receive all " + expectedRecords + " records from topic " + topic; TestUtils.waitForCondition(valuesRead, waitTime, conditionDetails); } return accumData; }

Target:
private static <K, V, T> List<T> waitUntilFinalKeyValueRecordsReceived(final Properties consumerConfig, final String topic, final List<T> expectedRecords, final long waitTime, final boolean withTimestamp) throws InterruptedException { final List<T> accumData = new ArrayList<>(); try (final Consumer<K, V> consumer = createConsumer(consumerConfig)) { final TestCondition valuesRead = () -> { final List<T> readData; if (withTimestamp) { readData = (List<T>) readKeyValuesWithTimestamp(topic, consumer, waitTime, expectedRecords.size()); } else { readData = (List<T>) readKeyValues(topic, consumer, waitTime, expectedRecords.size()); } accumData.addAll(readData); final List<T> accumulatedActual = accumData.stream().filter(expectedRecords::contains).collect(Collectors.toList()); final Map<K, List<T>> finalAccumData = new HashMap<>(); for (final T kv : accumulatedActual) { finalAccumData.computeIfAbsent( (K) (withTimestamp ? ((KeyValueTimestamp) kv).key() : ((KeyValue) kv).key), key -> new ArrayList<>()).add(kv); } final Map<K, List<T>> finalExpected = new HashMap<>(); for (final T kv : expectedRecords) { finalExpected.computeIfAbsent( (K) (withTimestamp ? ((KeyValueTimestamp) kv).key() : ((KeyValue) kv).key), key -> new ArrayList<>()).add(kv); } return finalAccumData.equals(finalExpected); }; final String conditionDetails = "Did not receive all " + expectedRecords + " records from topic " + topic; TestUtils.waitForCondition(valuesRead, waitTime, conditionDetails); } return accumData; }
Source:
public List<ByteString> parseNextBlock(boolean skipIfStartingOnBoundary) throws IOException { LOG.debug("BlockReader: none left to read, skipping to sync point"); long skipped = skipToNextSyncPoint(); if (skipped <= -1) { LOG.debug("BlockReader: SYNC point eof"); return null; } int blockSize = readInt(); LOG.debug("BlockReader: found sync point, next block has size " + blockSize); if (blockSize < 0) { LOG.debug("ProtobufReader: reading size after sync point eof"); return null; } byte[] byteArray = new byte[blockSize]; IOUtils.readFully(in_, byteArray, 0, blockSize); if (skipIfStartingOnBoundary && skipped == Protobufs.KNOWN_GOOD_POSITION_MARKER.length) { return parseNextBlock(false); } SerializedBlock block = SerializedBlock.parseFrom(byteArray); curBlobs_ = block.getProtoBlobs(); numLeftToReadThisBlock_ = curBlobs_.size(); LOG.debug("ProtobufReader: number in next block is " + numLeftToReadThisBlock_); return curBlobs_; }

Target:
public List<ByteString> parseNextBlock(boolean skipIfStartingOnBoundary) throws IOException { LOG.debug("BlockReader: none left to read, skipping to sync point"); long skipped = skipToNextSyncPoint(); if (skipped <= -1) { LOG.debug("BlockReader: SYNC point eof"); return null; } int blockSize = readInt(); LOG.debug("BlockReader: found sync point, next block has size " + blockSize); if (blockSize < 0) { LOG.debug("ProtobufReader: reading size after sync point eof"); return null; } if (skipIfStartingOnBoundary && skipped == Protobufs.KNOWN_GOOD_POSITION_MARKER.length) { in_.skip(blockSize); return parseNextBlock(false); } SerializedBlock block = SerializedBlock.parseFrom( new BoundedInputStream(in_, blockSize), blockSize); curBlobs_ = block.getProtoBlobs(); numLeftToReadThisBlock_ = curBlobs_.size(); LOG.debug("ProtobufReader: number in next block is " + numLeftToReadThisBlock_); return curBlobs_; }
Source:
public void execute(final WorkflowExecutor executor, final Context context) { pullRequestWorkflowService.getSettings() .then((Map<String, String> settings) -> { if (!Boolean.parseBoolean(settings.getOrDefault(CHE_PULLREQUEST_GENERATE__REVIEW__FACTORY, "true"))) { executor.done(GenerateReviewFactoryStep.this, context); return; } generateReviewFactory(executor, context); }); }

Target:
public void execute(final WorkflowExecutor executor, final Context context) { pullRequestWorkflowService.shouldGenerateReviewUrl() .then((Boolean shouldGenerateReviewUrl) -> { if (!shouldGenerateReviewUrl) { executor.done(GenerateReviewFactoryStep.this, context); return; } generateReviewFactory(executor, context); }); }
Source:
protected final List<ResultDocument> getSearchResults(ExecutionContext ctx) { return null; }

Target:
protected final List<ResultDocument> getSearchResults(ExecutionContext ctx) { throw new IllegalStateException(); }
Source:
private long getHeaderIndex(Predicate<WebElement> headerPredicate) { return Streams.mapWithIndex( getHeadings(), (we, i) -> headerPredicate.test(we) ? i : null) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new NoSuchElementException( "No header matches " + headerPredicate)); }

Target:
private long getHeaderIndex(Predicate<WebElement> headerPredicate) { return Streams.mapWithIndex( getHeadings(), (webElement, i) -> headerPredicate.test(webElement) ? i : null) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new NoSuchElementException("No header found.")); }
Source:
private Schema applyTruncateRule(Schema inputSchema, TruncateRule rule) { Schema.Builder builder = Schema.builder(); for (Column column : inputSchema.getColumns()) { builder.add(column.getName().substring(0, rule.getMaxLength()), column.getType()); } return builder.build(); }

Target:
private Schema applyTruncateRule(Schema inputSchema, TruncateRule rule) { Schema.Builder builder = Schema.builder(); for (Column column : inputSchema.getColumns()) { if (column.getName().length() <= rule.getMaxLength()) { builder.add(column.getName(), column.getType()); } else { try { builder.add(column.getName().substring(0, rule.getMaxLength()), column.getType()); } catch (IndexOutOfBoundsException ex) { logger.error("FATAL unexpected error in \"truncate\" rule: substring failed."); throw new AssertionError("FATAL unexpected error in \"truncate\" rule: substring failed.", ex); } } } return builder.build(); }
Source:
public void setPanelInfo(List<PanelInfo> panelInfo) { this.openPanels = new ArrayList<PanelInfo>(panelInfo); }

Target:
public void setPanelInfo(List<PanelInfo> panelInfo) { this.lastSessionPanels = new ArrayList<>(panelInfo); }
Source:
public static String placeholderAPIFormat(final Player player, String input) { if (input == null) { return null; } input = input.replaceAll(" if (papiEnabled) { return PlaceholderAPI.setPlaceholders(player, input); } return input; }

Target:
public static String placeholderAPIFormat(final Player player, String input) { if (input == null) { return null; } input = input.replaceAll("\\{|\\}", "%"); if(papiEnabled == null){ papiEnabled = Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI"); } if (papiEnabled) { return PlaceholderAPI.setPlaceholders(player, input); } return input; }
Source:
@Test public void testPushDistinctAggregateIntoJoin() throws Exception { final HepProgram preProgram = new HepProgramBuilder() .addRuleInstance(AggregateProjectMergeRule.INSTANCE) .build(); final HepProgram program = new HepProgramBuilder() .addRuleInstance(AggregateJoinTransposeRule.EXTENDED) .build(); final String sql = "select count(distinct sal) from sales.emp join sales.dept on job = name"; checkPlanUnchanged(new HepPlanner(program), sql); }

Target:
@Test public void testPushDistinctAggregateIntoJoin() { final HepProgram program = new HepProgramBuilder() .addRuleInstance(AggregateJoinTransposeRule.EXTENDED) .build(); final String sql = "select count(distinct sal) from sales.emp join sales.dept on job = name"; checkPlanUnchanged(new HepPlanner(program), sql); }
Source:
public void addAccounts(Collection<Account> accounts, int batchSize) throws SQLException { try { long startTimeMs = System.currentTimeMillis(); PreparedStatement insertStatement = dataAccessor.getPreparedStatement(insertSql, true); int count = 0; for (Account account : accounts) { insertStatement.setString(1, AccountCollectionSerde.accountToJsonNoContainers(account).toString()); insertStatement.setInt(2, account.getSnapshotVersion()); insertStatement.addBatch(); if (++count % batchSize == 0) { insertStatement.executeBatch(); } } insertStatement.executeBatch(); dataAccessor.onSuccess(Write, System.currentTimeMillis() - startTimeMs); } catch (SQLException e) { dataAccessor.onException(e, Write); throw e; } }

Target:
public void addAccounts(Collection<Account> accounts, int batchSize) throws SQLException { try { long startTimeMs = System.currentTimeMillis(); PreparedStatement insertStatement = dataAccessor.getPreparedStatement(insertSql, true); int count = 0; for (Account account : accounts) { insertStatement.setString(1, AccountCollectionSerde.accountToJsonNoContainers(account).toString()); insertStatement.setInt(2, account.getSnapshotVersion()); insertStatement.addBatch(); if (++count % batchSize == 0) { insertStatement.executeBatch(); } } if (accounts.size() % batchSize != 0) { insertStatement.executeBatch(); } dataAccessor.onSuccess(Write, System.currentTimeMillis() - startTimeMs); } catch (SQLException e) { dataAccessor.onException(e, Write); throw e; } }
Source:
public void testMulticastTopicToAnycastQueueBothAddress() throws Exception { String address = "testBoth"; File file = createMessageFile(); int noMessages = 10; Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); connection.start(); createBothTypeAddress(address); Thread export = new Thread(() -> { try { exportMessages("topic://" + address, noMessages, file); } catch (Exception e) { e.printStackTrace(); } }); export.start(); List<Message> messages = new ArrayList<>(noMessages); for (int i = 0; i < noMessages; i++) { messages.add(session.createTextMessage(RandomUtil.randomString())); } TimeUnit.SECONDS.sleep(3); sendMessages(session, getTopicDestination(address), messages); export.join(); importMessages(address, file); List<Message> received = consumeMessages(session, address, noMessages, false); for (int i = 0; i < noMessages; i++) { assertEquals(((TextMessage) messages.get(i)).getText(), ((TextMessage) received.get(i)).getText()); } }

Target:
public void testMulticastTopicToAnycastQueueBothAddress() throws Exception { String address = "testBoth"; String clientId = "test-client-id"; File file = createMessageFile(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); createBothTypeAddress(address); exportMessages("topic://" + address, 0, true, clientId, file); connection.start(); List<Message> messages = generateTextMessages(session, getTopicDestination(address)); exportMessages("topic://" + address, TEST_MESSAGE_COUNT, true, clientId, file); importMessages(address, file); checkSentMessages(session, messages, address); }
Source:
public static Optional<SweepProgress> hydrateProgress(Map<SweepProgressTable.SweepProgressRow, byte[]> result) { if (result.isEmpty()) { log.info("No persisted SweepProgress information found. Sweep will choose a new table to sweep."); return Optional.empty(); } try { return Optional.of(OBJECT_MAPPER.readValue(result.get(ROW), ImmutableSweepProgress.class)); } catch (Exception e) { log.warn("Error deserializing SweepProgress object while attempting to load intermittent result."); return Optional.empty(); } }

Target:
public static Optional<SweepProgress> hydrateProgress(Map<SweepProgressTable.SweepProgressRow, byte[]> result) { if (result.isEmpty()) { log.info("No persisted SweepProgress information found. Sweep will choose a new table to sweep."); return Optional.empty(); } try { return Optional.of(OBJECT_MAPPER.readValue(result.get(ROW), ImmutableSweepProgress.class)); } catch (Exception e) { log.warn("Error deserializing SweepProgress object while attempting to load intermittent result. Sweep " + "will choose a new table to sweep."); return Optional.empty(); } }
Source:
public void testDensification() throws Exception { CoordinateReferenceSystem utm32n = CRS.decode("EPSG:32632", true); ReferencedEnvelope wgs84Envelope = new ReferencedEnvelope(-190, 60, -90, 45, WGS84); ProjectionHandler handler = ProjectionHandlerFinder.getHandler(wgs84Envelope, WGS84, true); Geometry line = gf.createLineString( new Coordinate[] {new Coordinate(40, 45), new Coordinate(40, 88)}); LineString notDensified = (LineString) handler.preProcess(line); assertTrue(notDensified.getCoordinates().length == 2); Map params = new HashMap(); params.put("advancedProjectionDensify", 1.0); handler = ProjectionHandlerFinder.getHandler(wgs84Envelope, WGS84, true, params); LineString densified = (LineString) handler.preProcess(line); assertFalse(densified.getCoordinates().length == 2); }

Target:
public void testDensification() throws Exception { CoordinateReferenceSystem utm32n = CRS.decode("EPSG:32632", true); ReferencedEnvelope wgs84Envelope = new ReferencedEnvelope(-190, 60, -90, 45, WGS84); ProjectionHandler handler = ProjectionHandlerFinder.getHandler(wgs84Envelope, WGS84, true); Geometry line = gf.createLineString( new Coordinate[] {new Coordinate(40, 45), new Coordinate(40, 88)}); LineString notDensified = (LineString) handler.preProcess(line); assertEquals(2, notDensified.getCoordinates().length); Map params = new HashMap(); params.put(ProjectionHandler.ADVANCED_PROJECTION_DENSIFY, 1.0); handler = ProjectionHandlerFinder.getHandler(wgs84Envelope, WGS84, true, params); LineString densified = (LineString) handler.preProcess(line); assertEquals(45, densified.getCoordinates().length); }
Source:
private void pauseBeforeRetry(int retries, HttpResponse httpResponse, long timeElapsed) throws RestException { long delay = -1; long timeElapsedLeft = maxElapsedMillis - timeElapsed; if (backoffStrategy != null) { delay = Math.min(this.backoffStrategy.getDelayMillis(retries), timeElapsedLeft); } else if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 429) { delay = get429DelayMillis(httpResponse); if (!shouldRetry(retries, timeElapsed + delay)) { throw new RestException("HTTP 429: Too Many Requests. Exceeded request rate limit in the allotted amount of time."); } log.debug("429 detected, will retry in {}ms, attempt number: {}", delay, retries); } if (delay < 0) { delay = Math.min(getDefaultDelayMillis(retries), timeElapsedLeft); } log.debug("Retryable condition detected, will retry in {}ms, attempt number: {}", delay, retries); try { Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RestException(e.getMessage(), e); } }

Target:
private void pauseBeforeRetry(int retries, HttpResponse httpResponse, long timeElapsed) throws RestException { long delay = -1; long timeElapsedLeft = maxElapsedMillis - timeElapsed; if (backoffStrategy != null) { delay = Math.min(this.backoffStrategy.getDelayMillis(retries), timeElapsedLeft); } else if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 429) { delay = get429DelayMillis(httpResponse); if (!shouldRetry(retries, timeElapsed + delay)) { throw new RestException("Cannot retry request, next request will exceed retry configuration."); } log.debug("429 detected, will retry in {}ms, attempt number: {}", delay, retries); } if (delay < 0) { delay = Math.min(getDefaultDelayMillis(retries), timeElapsedLeft); } log.debug("Retryable condition detected, will retry in {}ms, attempt number: {}", delay, retries); try { Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RestException(e.getMessage(), e); } }
Source:
protected void executeQueryCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), ((GlusterVolumeProfileParameters)getParameters()).isNfs())); getQueryReturnValue().setReturnValue((((GlusterVolumeProfileParameters)getParameters()).isNfs()) ? (GlusterVolumeProfileInfo) returnValue.getReturnValue() : populateBrickNames((GlusterVolumeProfileInfo) returnValue.getReturnValue())); }

Target:
protected void executeQueryCommand() { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.GetGlusterVolumeProfileInfo, new GlusterVolumeProfileInfoVDSParameters(getParameters().getClusterId(), getUpServerId(getParameters().getClusterId()), getGlusterVolumeName(getParameters().getVolumeId()), ((GlusterVolumeProfileParameters)getParameters()).isNfs())); GlusterVolumeProfileInfo profileInfo = (GlusterVolumeProfileInfo) returnValue.getReturnValue(); if (!((GlusterVolumeProfileParameters)getParameters()).isNfs()) { populateBrickNames(profileInfo); } getQueryReturnValue().setReturnValue(profileInfo); }
Source:
public void convertBase64Binary(XSBinaryPointable binaryp, DataOutput dOut) throws SystemException, IOException { baaos.reset(); @SuppressWarnings("resource") Base64OutputStream b64os = new Base64OutputStream(baaos, true); b64os.write(binaryp.getByteArray(), binaryp.getStartOffset() + 2, binaryp.getLength() - 2); dOut.write(returnTag); UTF8StringUtil.getNumBytesToStoreLength(baaos.size()); dOut.write((byte) ((baaos.size() >>> 8) & 0xFF)); dOut.write((byte) ((baaos.size() >>> 0) & 0xFF)); dOut.write(baaos.getByteArray(), 0, baaos.size()); }

Target:
public void convertBase64Binary(XSBinaryPointable binaryp, DataOutput dOut) throws SystemException, IOException { Base64OutputStream b64os = new Base64OutputStream(baaos, true); b64os.write(binaryp.getByteArray(), binaryp.getStartOffset() + 2, binaryp.getLength() - 2); startString(); sb.appendUtf8Bytes(baaos.getByteArray(), 0, baaos.size()); sendStringDataOutput(dOut); }
Source:
public static void removeExternalUserId() { if (shouldLogUserPrivacyConsentErrorMessageForMethodName("removeExternalUserId()")) return; setExternalUserId("", new ExternalUserIdUpdateHandler() { @Override public void onSuccess(String newExternalUserId) { } @Override public void onFailure(ExternalUserIdError error) { } }); }

Target:
public static void removeExternalUserId() { if (shouldLogUserPrivacyConsentErrorMessageForMethodName("removeExternalUserId()")) return; removeExternalUserId(null); }
Source:
public static String getTenantBasedDevPortalContext(String tenantDomain) throws APIManagementException { String context = null; try { Registry registry = ServiceReferenceHolder.getInstance().getRegistryService(). getGovernanceSystemRegistry(); String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace("<tenant-id>", tenantDomain); if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject mappings = (JSONObject) parser.parse(content); if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_STORE)) { JSONObject storeMapping = (JSONObject) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_STORE); if (storeMapping.containsKey(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT)) { context = (String) storeMapping.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); } else { context = ""; } } } } catch (RegistryException e) { String msg = "Error while retrieving gateway domain mappings from registry"; log.error(msg, e); throw new APIManagementException(msg, e); } catch (ClassCastException e) { String msg = "Invalid JSON found in the gateway tenant domain mappings"; log.error(msg, e); throw new APIManagementException(msg, e); } catch (ParseException e) { String msg = "Malformed JSON found in the gateway tenant domain mappings"; log.error(msg, e); throw new APIManagementException(msg, e); } return context; }

Target:
public static String getTenantBasedDevPortalContext(String tenantDomain) throws APIManagementException { String context = null; try { Registry registry = ServiceReferenceHolder.getInstance().getRegistryService(). getGovernanceSystemRegistry(); String resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace("<tenant-id>", tenantDomain); if (registry.resourceExists(resourcePath)) { Resource resource = registry.get(resourcePath); String content = new String((byte[]) resource.getContent(), Charset.defaultCharset()); JSONParser parser = new JSONParser(); JSONObject mappings = (JSONObject) parser.parse(content); if (mappings.containsKey(APIConstants.API_DOMAIN_MAPPINGS_STORE)) { JSONObject storeMapping = (JSONObject) mappings.get(APIConstants.API_DOMAIN_MAPPINGS_STORE); if (storeMapping.containsKey(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT)) { context = (String) storeMapping.get(APIConstants.API_DOMAIN_MAPPINGS_CONTEXT); } else { context = ""; } } } } catch (RegistryException e) { String msg = "Error while retrieving gateway domain mappings from registry"; throw new APIManagementException(msg, e); } catch (ClassCastException e) { String msg = "Invalid JSON found in the gateway tenant domain mappings"; throw new APIManagementException(msg, e); } catch (ParseException e) { String msg = "Malformed JSON found in the gateway tenant domain mappings"; throw new APIManagementException(msg, e); } return context; }
Source:
private CopyCmdAnswer performResignature(DataObject dataObj, HostVO hostVO, boolean keepGrantedAccess) { long storagePoolId = dataObj.getDataStore().getId(); DataStore dataStore = _dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); Map<String, String> details = getDetails(dataObj); ResignatureCommand command = new ResignatureCommand(details); ResignatureAnswer answer = null; try { _volumeService.grantAccess(dataObj, hostVO, dataStore); answer = (ResignatureAnswer)_agentMgr.send(hostVO.getId(), command); } catch (Exception ex) { keepGrantedAccess = false; throw new CloudRuntimeException(ex.getMessage()); } finally { if (keepGrantedAccess == false) { try { _volumeService.revokeAccess(dataObj, hostVO, dataStore); } catch (Exception ex) { s_logger.debug(ex.getMessage(), ex); } } } if (answer == null || !answer.getResult()) { final String errMsg; if (answer != null && answer.getDetails() != null && !answer.getDetails().isEmpty()) { errMsg = answer.getDetails(); } else { errMsg = "Unable to perform resignature operation"; } throw new CloudRuntimeException(errMsg); } VolumeObjectTO newVolume = new VolumeObjectTO(); newVolume.setSize(answer.getSize()); newVolume.setPath(answer.getPath()); newVolume.setFormat(answer.getFormat()); return new CopyCmdAnswer(newVolume); }

Target:
private CopyCmdAnswer performResignature(DataObject dataObj, HostVO hostVO, boolean keepGrantedAccess) { long storagePoolId = dataObj.getDataStore().getId(); DataStore dataStore = dataStoreMgr.getDataStore(storagePoolId, DataStoreRole.Primary); Map<String, String> details = getDetails(dataObj); ResignatureCommand command = new ResignatureCommand(details); ResignatureAnswer answer = null; try { _volumeService.grantAccess(dataObj, hostVO, dataStore); answer = (ResignatureAnswer)_agentMgr.send(hostVO.getId(), command); } catch (CloudRuntimeException | AgentUnavailableException | OperationTimedoutException ex) { keepGrantedAccess = false; String msg = "Failed to resign the DataObject with the following ID: " + dataObj.getId(); LOGGER.warn(msg, ex); throw new CloudRuntimeException(msg + ex.getMessage()); } finally { if (keepGrantedAccess == false) { _volumeService.revokeAccess(dataObj, hostVO, dataStore); } } if (answer == null || !answer.getResult()) { final String errMsg; if (answer != null && answer.getDetails() != null && !answer.getDetails().isEmpty()) { errMsg = answer.getDetails(); } else { errMsg = "Unable to perform resignature operation in 'StorageSystemDataMotionStrategy.performResignature'"; } throw new CloudRuntimeException(errMsg); } VolumeObjectTO newVolume = new VolumeObjectTO(); newVolume.setSize(answer.getSize()); newVolume.setPath(answer.getPath()); newVolume.setFormat(answer.getFormat()); return new CopyCmdAnswer(newVolume); }
Source:
private static <T> T staticRequest( ApiResource.RequestMethod method, String url, Map<String, Object> params, Class<T> clazz, ApiResource.RequestType type, RequestOptions options) throws StripeException { long requestStart = System.currentTimeMillis(); StripeResponse response = rawRequest(method, url, params, type, options); long requestDurationMS = System.currentTimeMillis() - requestStart; int responseCode = response.code(); String responseBody = response.body(); String requestId = response.requestId(); if (responseCode < 200 || responseCode >= 300) { handleApiError(responseBody, responseCode, requestId); } T resource = null; try { resource = ApiResource.GSON.fromJson(responseBody, clazz); } catch (JsonSyntaxException e) { raiseMalformedJsonError(responseBody, responseCode, requestId); } if (resource instanceof StripeObject) { StripeObject obj = (StripeObject)resource; obj.setLastResponse(response); } if (Stripe.enableTelemetry && prevRequestMetrics.size() < MAX_REQUEST_METRICS_BUFFER_SIZE) { prevRequestMetrics.add(new RequestMetrics(requestId, requestDurationMS)); } return resource; }

Target:
private static <T> T staticRequest( ApiResource.RequestMethod method, String url, Map<String, Object> params, Class<T> clazz, ApiResource.RequestType type, RequestOptions options) throws StripeException { long requestStartMs = System.currentTimeMillis(); StripeResponse response = rawRequest(method, url, params, type, options); long requestDurationMs = System.currentTimeMillis() - requestStartMs; int responseCode = response.code(); String responseBody = response.body(); String requestId = response.requestId(); if (responseCode < 200 || responseCode >= 300) { handleApiError(responseBody, responseCode, requestId); } T resource = null; try { resource = ApiResource.GSON.fromJson(responseBody, clazz); } catch (JsonSyntaxException e) { raiseMalformedJsonError(responseBody, responseCode, requestId); } if (resource instanceof StripeObject) { StripeObject obj = (StripeObject)resource; obj.setLastResponse(response); } if (Stripe.enableTelemetry && prevRequestMetrics.size() < MAX_REQUEST_METRICS_BUFFER_SIZE) { prevRequestMetrics.add(new RequestMetrics(requestId, requestDurationMs)); } return resource; }
Source:
private boolean isSinglePartitioned(RexProgram program, RexNode rexNode, List<Integer> partitionKeys) { if (rexNode instanceof RexCall) { RexCall rexCall = (RexCall) rexNode; SqlKind sqlKind = rexCall.getOperator().getKind(); switch (sqlKind) { case EQUALS: return isSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys) || isSinglePartitioned(program, rexCall.getOperands().get(1), partitionKeys); case AND: return isSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys) || isSinglePartitioned(program, rexCall.getOperands().get(1), partitionKeys); case OR: return isSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys) && isSinglePartitioned(program, rexCall.getOperands().get(1), partitionKeys); default: return false; } } if (rexNode instanceof RexInputRef) { return partitionKeys.contains(((RexInputRef) rexNode).getIndex()); } if (rexNode instanceof RexLocalRef) { return isSinglePartitioned(program, program.getExprList().get(((RexLocalRef) rexNode).getIndex()), partitionKeys); } return false; }

Target:
private static boolean isSinglePartitioned(RexProgram program, RexNode rexNode, List<Integer> partitionKeys) { if (rexNode instanceof RexCall) { RexCall rexCall = (RexCall) rexNode; SqlKind sqlKind = rexCall.getOperator().getKind(); switch (sqlKind) { case EQUALS: return (isSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys) && !hasTableColumn(program, rexCall.getOperands().get(1))) || (isSinglePartitioned(program, rexCall.getOperands().get(1), partitionKeys) && !hasTableColumn(program, rexCall.getOperands().get(0))); case AND: return isSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys) || isSinglePartitioned(program, rexCall.getOperands().get(1), partitionKeys); case OR: return false; case NOT: return isComplementSinglePartitioned(program, rexCall.getOperands().get(0), partitionKeys); default: return false; } } else if (rexNode instanceof RexInputRef) { return partitionKeys.contains(((RexInputRef) rexNode).getIndex()); } else if (rexNode instanceof RexLocalRef) { return isSinglePartitioned(program, program.getExprList().get(((RexLocalRef) rexNode).getIndex()), partitionKeys); } else { return false; } }
Source:
public void validate(ValidationContext validationContext) { if (isEnabled() && !validationContext.systemEnvironment().get(SystemEnvironment.INBUILT_LDAP_PASSWORD_AUTH_ENABLED)) { configErrors.add("base", "'passwordFile' tag has been deprecated in favour of bundled PasswordFile plugin. Use that instead."); } }

Target:
public void validate(ValidationContext validationContext) { if (isEnabled() && !validationContext.systemEnvironment().inbuiltLdapPasswordAuthEnabled()) { configErrors.add("base", "'passwordFile' tag has been deprecated in favour of bundled PasswordFile plugin. Use that instead."); } }
Source:
public static DeadLetterQueueReporter createAndSetup(Map<String, Object> adminProps, ConnectorTaskId id, SinkConnectorConfig sinkConfig, Map<String, Object> producerProps, ErrorHandlingMetrics errorHandlingMetrics) { KafkaProducer<byte[], byte[]> dlqProducer = setUpTopicAndProducer( adminProps, producerProps, sinkConfig, DLQ_NUM_DESIRED_PARTITIONS ); return new DeadLetterQueueReporter(dlqProducer, sinkConfig, id, errorHandlingMetrics); }

Target:
public static DeadLetterQueueReporter createAndSetup(Map<String, Object> adminProps, ConnectorTaskId id, SinkConnectorConfig sinkConfig, Map<String, Object> producerProps, ErrorHandlingMetrics errorHandlingMetrics) { String topic = sinkConfig.dlqTopicName(); try (Admin admin = Admin.create(adminProps)) { if (!admin.listTopics().names().get().contains(topic)) { log.error("Topic doesn't exist. Will attempt to create topic.", topic); NewTopic schemaTopicRequest = new NewTopic(topic, DLQ_NUM_DESIRED_PARTITIONS, sinkConfig.dlqTopicReplicationFactor()); admin.createTopics(singleton(schemaTopicRequest)).all().get(); } } catch (InterruptedException e) { throw new ConnectException("Could not initialize dead letter queue with topic=" + topic, e); } catch (ExecutionException e) { if (!(e.getCause() instanceof TopicExistsException)) { throw new ConnectException("Could not initialize dead letter queue with topic=" + topic, e); } } KafkaProducer<byte[], byte[]> dlqProducer = new KafkaProducer<>(producerProps); return new DeadLetterQueueReporter(dlqProducer, sinkConfig, id, errorHandlingMetrics); }
Source:
private void executeFirstChunkedQuery() throws SQLException { String firstQuery = _chunkedQueryManager.generateFirstQuery(_sourceQuery, new ArrayList<>(_chunkingKeys.keySet()), _chunkSize, _maxChunkIndex, _chunkIndex); _firstStmt = _connection.prepareStatement(firstQuery); _firstStmt.setFetchSize(_fetchSize); _firstStmt.setQueryTimeout(_queryTimeoutSecs); long timeStart = System.currentTimeMillis(); _queryResultSet = _firstStmt.executeQuery(); _metrics.updateQueryExecutionTime(System.currentTimeMillis() - timeStart); _metrics.updateQueryExecutionRate(); }

Target:
private void executeFirstChunkedQuery() throws SQLException { String firstQuery = _chunkedQueryManager.generateFirstQuery(_sourceQuery, new ArrayList<>(_chunkingKeys.keySet()), _rowCountLimit, _maxChunkIndex, _chunkIndex); _firstStmt = _connection.prepareStatement(firstQuery); _firstStmt.setFetchSize(_fetchSize); _firstStmt.setQueryTimeout(_queryTimeoutSecs); executeChunkedQuery(_firstStmt); }
Source:
protected static int getLoginPort(Container container) { if (container.getNetworkSettings() != null) { Map<String, List<Map<String, String>>> ports = container.getNetworkSettings().getPorts(); if (ports != null && ports.containsKey("22/tcp")) { return Integer.parseInt(getOnlyElement(ports.get("22/tcp")).get("HostPort")); } } else if (container.getPorts() != null) { for (Port port : container.getPorts()) { if (port.getPrivatePort() == 22) { return port.getPublicPort(); } } } return -1; }

Target:
protected static int getLoginPort(Container container) { if (container.getNetworkSettings() != null) { Map<String, List<Map<String, String>>> ports = container.getNetworkSettings().getPorts(); if (ports != null && ports.containsKey("22/tcp")) { return Integer.parseInt(getOnlyElement(ports.get("22/tcp")).get("HostPort")); } } else if (container.getPorts() != null) { for (Port port : container.getPorts()) { if (port.getPrivatePort() == 22) { return port.getPublicPort(); } } } return NO_LOGIN_PORT; }
Source:
private void processTestOnTransientLayerDecoration(DecorationDescription mbd, String layerName) throws InterruptedException { activateBasicLayer(dDiagram, layerName); final List<DDiagramElement> elements = Lists.newArrayList(dDiagram.getOwnedDiagramElements()); checkTransientDecoration(elements, mbd); Assert.assertEquals("The session should be still be in sync when appliying a transient layer", SessionStatus.SYNC, session.getStatus()); DialectUIManager.INSTANCE.closeEditor(editor, true); editor = DialectUIManager.INSTANCE.openEditor(session, dDiagram, new NullProgressMonitor()); checkTransientDecoration(elements, mbd); URI uri = session.getSessionResource().getURI(); closeSession(session); TestsUtil.waitUntil(new OpenedSessionsCondition(0)); createSession(uri); Job.getJobManager().join(ResourceSyncClientNotifier.FAMILY, new NullProgressMonitor()); session.open(new NullProgressMonitor()); TestsUtil.waitUntil(new OpenedSessionsCondition(1)); dDiagram = (DDiagram) ((DAnalysis) session.getSessionResource().getContents().get(0)).getOwnedViews().get(0).getOwnedRepresentationDescriptors().get(0) .getRepresentation(); editor = DialectUIManager.INSTANCE.openEditor(session, dDiagram, new NullProgressMonitor()); Assert.assertEquals("Only one layer should be active", 1, dDiagram.getActivatedLayers().size()); Assert.assertEquals("Only the default layer should be active", "Default", dDiagram.getActivatedLayers().get(0).getName()); checkNoTransientDecoration(dDiagram.getOwnedDiagramElements()); }

Target:
private void processTestOnTransientLayerDecoration(DecorationDescription mbd, String layerName) throws InterruptedException { activateBasicLayer(dDiagram, layerName); final List<DDiagramElement> elements = Lists.newArrayList(dDiagram.getOwnedDiagramElements()); checkTransientDecoration(elements, mbd); Assert.assertEquals("The session should be still be in sync when applying a transient layer", SessionStatus.SYNC, session.getStatus()); DialectUIManager.INSTANCE.closeEditor(editor, true); editor = DialectUIManager.INSTANCE.openEditor(session, dDiagram, new NullProgressMonitor()); checkTransientDecoration(elements, mbd); URI uri = session.getSessionResource().getURI(); closeSession(session); TestsUtil.waitUntil(new OpenedSessionsCondition(0)); createSession(uri); Job.getJobManager().join(ResourceSyncClientNotifier.FAMILY, new NullProgressMonitor()); session.open(new NullProgressMonitor()); TestsUtil.waitUntil(new OpenedSessionsCondition(1)); dDiagram = (DDiagram) ((DAnalysis) session.getSessionResource().getContents().get(0)).getOwnedViews().get(0).getOwnedRepresentationDescriptors().get(0) .getRepresentation(); editor = DialectUIManager.INSTANCE.openEditor(session, dDiagram, new NullProgressMonitor()); Assert.assertEquals("Only one layer should be active", 1, dDiagram.getActivatedLayers().size()); Assert.assertEquals("Only the default layer should be active", "Default", dDiagram.getActivatedLayers().get(0).getName()); Assert.assertEquals("No transient layer should be active", 0, dDiagram.getActivatedTransientLayers().size()); checkNoTransientDecoration(dDiagram.getOwnedDiagramElements()); }
Source:
public Aggregator factorize(final ColumnSelectorFactory columnFactory) { getCompiledScript(); return new JavaScriptAggregator( fieldNames.stream().map(columnFactory::makeColumnValueSelector).collect(Collectors.toList()), compiledScript ); }

Target:
public Aggregator factorize(final ColumnSelectorFactory columnFactory) { JavaScriptAggregator.ScriptAggregator compiledScript = getCompiledScript(); return new JavaScriptAggregator( fieldNames.stream().map(columnFactory::makeColumnValueSelector).collect(Collectors.toList()), compiledScript ); }
Source:
public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData .prepareClonedGitRepository(TestConfiguration.class); String branchToDelete = "branchToDelete"; testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call(); Environment environment = testData.getRepository().findOne("bar", "staging", "branchToDelete"); assertNotNull(environment); testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete).call(); testData.getRepository().findOne("bar", "staging", "branchToDelete"); assertNotNull(environment); }

Target:
public void testShouldReturnEnvironmentFromLocalBranchInCaseRemoteDeleted() throws Exception { JGitConfigServerTestData testData = JGitConfigServerTestData .prepareClonedGitRepository(TestConfiguration.class); String branchToDelete = "branchToDelete"; testData.getServerGit().getGit().branchCreate().setName(branchToDelete).call(); Environment environment = testData.getRepository().findOne("bar", "staging", "branchToDelete"); assertNotNull(environment); testData.getServerGit().getGit().branchDelete().setBranchNames(branchToDelete).call(); environment = testData.getRepository().findOne("bar", "staging", "branchToDelete"); assertNotNull(environment); }
Source:
private void hotPlugUnplugCpus() { if (canHotPlugUnplugCpu()) { VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.SetNumberOfCpus, new SetNumberOfCpusVDSCommand.Params( getVm().getRunOnVds(), getVm().getId(), getParameters().getVm().getNumOfCpus())); AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(getVmId()); logable.addCustomValue("numberOfCpus", String.valueOf(getParameters().getVm().getNumOfCpus())); logable.addCustomValue("ErrorMessage", vdsReturnValue.getVdsError().getMessage()); boolean hotPlugUnplugSucceeded = vdsReturnValue.getSucceeded() && vdsReturnValue.getVdsError().getCode() == VdcBllErrors.Done; AuditLogDirector.log(logable, hotPlugUnplugSucceeded ? AuditLogType.SET_NUMBER_OF_CPUS : AuditLogType.FAILED_SET_NUMBER_OF_CPUS); if (!hotPlugUnplugSucceeded) { newVmStatic.setNumOfSockets(oldVm.getNumOfSockets()); } } }

Target:
private void hotPlugUnplugCpus() { if (getVm().getNumOfCpus() != getParameters().getVm().getNumOfCpus()) { VDSReturnValue returnValue = runVdsCommand(VDSCommandType.SetNumberOfCpus, new SetNumberOfCpusVDSCommand.Params( getVm().getRunOnVds(), getVm().getId(), getParameters().getVm().getNumOfCpus())); AuditLogableBase logable = new AuditLogableBase(); logable.setVmId(getVmId()); logable.addCustomValue("numberOfCpus", String.valueOf(getParameters().getVm().getNumOfCpus())); logable.addCustomValue("ErrorMessage", returnValue.getExceptionString() + " " + returnValue.getVdsError().getMessage()); AuditLogDirector.log(logable, returnValue.getSucceeded() ? AuditLogType.SET_NUMBER_OF_CPUS : AuditLogType.FAILED_SET_NUMBER_OF_CPUS); if (!returnValue.getSucceeded()) { newVmStatic.setNumOfSockets(oldVm.getNumOfSockets()); } } }