auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void start() throws Exception { LOGGER.info("Starting Cardinality Manager"); if (cardinalityConfig.isActive()) { LOGGER.info("Scheduling cardinality calculation job"); LocalDateTime localNow = LocalDateTime.now(); ZoneId currentZone = ZoneId.of(TIME_ZONE); ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone); ZonedDateTime zonedNext5 = zonedNow.withHour(cardinalityConfig.getInitialDelay()).withMinute(0).withSecond(0); if (zonedNow.compareTo(zonedNext5) > 0) zonedNext5 = zonedNext5.plusDays(1); Duration duration = Duration.between(zonedNow, zonedNext5); long initialDelay = duration.getSeconds(); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { LockingTaskExecutor executor = new DefaultLockingTaskExecutor(new HazelcastLockProvider(hazelcastConnection.getHazelcast())); Instant lockAtMostUntil = Instant.now().plusSeconds(TimeUnit.HOURS.toSeconds(MAX_TIME_TO_RUN_TASK_IN_HOURS)); executor.executeWithLock(new CardinalityCalculationRunnable(tableMetadataManager), new LockConfiguration("cardinalityCalculation", lockAtMostUntil)); } }, initialDelay, cardinalityConfig.getInterval(), TimeUnit.SECONDS); LOGGER.info("Scheduled cardinality calculation job"); } else { LOGGER.info("Not scheduling cardinality calculation job"); } LOGGER.info("Started Cardinality Manager"); }

Target:
public void start() throws Exception { LOGGER.info("Starting Cardinality Manager"); if (cardinalityConfig.isActive()) { LOGGER.info("Scheduling cardinality calculation job"); LocalDateTime localNow = LocalDateTime.now(); Calendar now = Calendar.getInstance(); ZoneId currentZone = ZoneId.of(now.getTimeZone().getID()); ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone); ZonedDateTime zonedNext5 = zonedNow.withHour(cardinalityConfig.getInitialDelay()).withMinute(0).withSecond(0); if (zonedNow.compareTo(zonedNext5) > 0) zonedNext5 = zonedNext5.plusDays(1); Duration duration = Duration.between(zonedNow, zonedNext5); long initialDelay = duration.getSeconds(); scheduledExecutorService.scheduleAtFixedRate(new Runnable() { @Override public void run() { LockingTaskExecutor executor = new DefaultLockingTaskExecutor(new HazelcastLockProvider(hazelcastConnection.getHazelcast())); Instant lockAtMostUntil = Instant.now().plusSeconds(TimeUnit.HOURS.toSeconds(MAX_TIME_TO_RUN_TASK_IN_HOURS)); executor.executeWithLock(new CardinalityCalculationRunnable(tableMetadataManager), new LockConfiguration("cardinalityCalculation", lockAtMostUntil)); } }, initialDelay, cardinalityConfig.getInterval(), TimeUnit.SECONDS); LOGGER.info("Scheduled cardinality calculation job"); } else { LOGGER.info("Not scheduling cardinality calculation job"); } }
Source:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle || truncationHandle == Long.MIN_VALUE) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }

Target:
public void offerSp(InitiateResponseMessage msg, boolean isLeader, long handle) { long truncationHandle = m_lastSpTruncationHandle; if (isLeader) { truncationHandle = handle; } if (msg.getSpHandle() >= truncationHandle) { m_mailbox.send(msg.getInitiatorHSId(), msg); } else { m_shortCircuitReadSp.add(new Item(msg)); } releaseShortCircuitRead(truncationHandle, IS_SP); }
Source:
void requestMore(long n) { if (n > 0) { while (true) { final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, REQUESTED_NOT_COMPLETED)) { request(Long.MAX_VALUE); return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else return; } } }

Target:
void requestMore(long n) { if (n > 0) { while (true) { final int s = state.get(); if (s == NOT_REQUESTED_NOT_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_NOT_COMPLETED, REQUESTED_NOT_COMPLETED)) { return; } } else if (s == NOT_REQUESTED_COMPLETED) { if (state.compareAndSet(NOT_REQUESTED_COMPLETED, REQUESTED_COMPLETED)) { emit(); return; } } else return; } } }
Source:
public AuthConfig createAuthConfig(boolean isPush, boolean skipExtendedAuth, Map authConfig, Settings settings, String user, String registry) throws MojoExecutionException { AuthConfig ret = createAuthConfig(isPush, authConfig, settings, user, registry); if (ret != null) { if (registry == null ) { log.debug("default registry; no extended auth"); return ret; } if (skipExtendedAuth) { log.debug("skipping extended auth"); return ret; } try { return extendedAuthentication(registry, ret); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } ret = getAuthConfigFromDockerConfig(registry); if(ret != null) { log.debug("found credentials in ~.docker/config.json"); return ret; } log.debug("no credentials found"); return null; }

Target:
public AuthConfig createAuthConfig(boolean isPush, boolean skipExtendedAuth, Map authConfig, Settings settings, String user, String registry) throws MojoExecutionException { AuthConfig ret = createStandardAuthConfig(isPush, authConfig, settings, user, registry); if (ret != null) { if (registry == null ) { log.debug("default registry; no extended auth"); return ret; } if (skipExtendedAuth) { log.debug("skipping extended auth"); return ret; } try { return extendedAuthentication(registry, ret); } catch (IOException e) { throw new MojoExecutionException(e.getMessage(), e); } } ret = getAuthConfigFromDockerConfig(registry); if(ret != null) { log.debug("found credentials in ~.docker/config.json"); return ret; } log.debug("no credentials found"); return null; }
Source:
public MemcachedBackupSession createSession( String sessionId ) { if ( _log.isDebugEnabled() ) { _log.debug( "createSession invoked: " + sessionId ); } checkMaxActiveSessions(); final MemcachedBackupSession session = createEmptySession(); session.setNew( true ); session.setValid( true ); session.setCreationTime( System.currentTimeMillis() ); session.setMaxInactiveInterval( _manager.getMaxInactiveInterval() ); if ( sessionId == null || !_memcachedNodesManager.canHitMemcached( sessionId ) ) { sessionId = _manager.generateSessionId(); } session.setId( sessionId ); final Request request = _currentRequest.get(); if(request != null) { request.setNote(NEW_SESSION_ID, sessionId); } if(!_sticky) { synchronized (_manager.getSessionsInternal()) { session.registerReference(); } } if ( _log.isDebugEnabled() ) { _log.debug( "Created new session with id " + session.getId() ); } _manager.incrementSessionCounter(); if( _invalidSessionsCache.get(session.getId()) ){ if ( _log.isDebugEnabled() ) { _log.debug( "Remove session id " + session.getId() + " from _invalidSessionsCache, marking new session valid" ); } _invalidSessionsCache.remove(session.getId()); } return session; }

Target:
public MemcachedBackupSession createSession( String sessionId ) { if ( _log.isDebugEnabled() ) { _log.debug( "createSession invoked: " + sessionId ); } checkMaxActiveSessions(); final MemcachedBackupSession session = createEmptySession(); session.setNew( true ); session.setValid( true ); session.setCreationTime( System.currentTimeMillis() ); session.setMaxInactiveInterval( _manager.getMaxInactiveInterval() ); if ( sessionId == null || !_memcachedNodesManager.canHitMemcached( sessionId ) ) { sessionId = _manager.generateSessionId(); } session.setId( sessionId ); final Request request = _currentRequest.get(); if(request != null) { request.setNote(NEW_SESSION_ID, sessionId); } if(!_sticky) { synchronized (_manager.getSessionsInternal()) { session.registerReference(); } } if ( _log.isDebugEnabled() ) { _log.debug( "Created new session with id " + session.getId() ); } _manager.incrementSessionCounter(); if( _invalidSessionsCache.containsKey(session.getId()) ){ if ( _log.isDebugEnabled() ) { _log.debug( "Remove session id " + session.getId() + " from _invalidSessionsCache, marking new session valid" ); } _invalidSessionsCache.remove(session.getId()); } return session; }
Source:
void releaseAllResources() throws IOException { if (isReleased.compareAndSet(false, true)) { ArrayDeque<Buffer> releasedBuffers = new ArrayDeque<>(); synchronized (receivedBuffers) { releasedBuffers.addAll(receivedBuffers); receivedBuffers.clear(); } bufferManager.releaseAllBuffers(releasedBuffers); } }

Target:
void releaseAllResources() throws IOException { ArrayDeque<Buffer> releasedBuffers = new ArrayDeque<>(); boolean shouldRelease = false; synchronized (receivedBuffers) { if (!isReleased) { isReleased = true; shouldRelease = true; releasedBuffers.addAll(receivedBuffers); receivedBuffers.clear(); } } if (shouldRelease) { bufferManager.releaseAllBuffers(releasedBuffers); } }
Source:
static void filterProperties(Message message, Set<String> namesToClear, List<Object> out) { List<String> names; try { names = list(message.getPropertyNames()); } catch (Throwable t) { propagateIfFatal(t); log(t, "error getting property names from {0}", message, null); return; } if (disjoint(namesToClear, names) && message instanceof BytesMessage) { return; } for (String name: names) { Object value; try { value = message.getObjectProperty(name); } catch (Throwable t) { propagateIfFatal(t); log(t, "error getting property {0} from message {1}", name, message); return; } if (!namesToClear.contains(name) && value != null) { out.add(name); out.add(value); } } try { message.clearProperties(); } catch (Throwable t) { propagateIfFatal(t); log(t, "error clearing properties of {0}", message, null); return; } if (message instanceof BytesMessage) { resetBytesMessageProperties(message, out); } else { resetProperties(message, out); } }

Target:
static void filterProperties(Message message, Set<String> namesToClear, List<Object> out) { List<String> names; try { names = list(message.getPropertyNames()); } catch (Throwable t) { propagateIfFatal(t); log(t, "error getting property names from {0}", message, null); return; } for (String name: names) { if (!namesToClear.contains(name)) { Object value; try { value = message.getObjectProperty(name); } catch (Throwable t) { propagateIfFatal(t); log(t, "error getting property {0} from message {1}", name, message); return; } if (value != null) { out.add(name); out.add(value); } } } try { message.clearProperties(); } catch (Throwable t) { propagateIfFatal(t); log(t, "error clearing properties of {0}", message, null); return; } if (message instanceof BytesMessage) { resetBytesMessageProperties(message, out); } else { resetProperties(message, out); } }
Source:
public void setup() throws Exception { profileInstances = spy(new MockInstanceImpl<>(profile1, profile2)); tested = new BackendProfileManager(definitionUtils, profileInstances); }

Target:
public void setup() { profileInstances = spy(new MockInstanceImpl<>(profile1, profile2)); tested = new BackendProfileManager(definitionUtils, profileInstances); }
Source:
public Result apply(FilterNode filterNode, Captures captures, Context context) { TableScanNode tableScan = captures.get(TABLE_SCAN); TableLayoutRewriter tableLayoutRewriter = new TableLayoutRewriter(metadata, context.getSession(), context.getSymbolAllocator(), context.getIdAllocator()); PlanNode rewrittenTableScan = tableLayoutRewriter.planTableScan(captures.get(TABLE_SCAN), filterNode.getPredicate()); if (arePlansEquivalent(filterNode, tableScan, rewrittenTableScan, context)) { return Result.empty(); } return Result.ofPlanNode(rewrittenTableScan); }

Target:
public Result apply(FilterNode filterNode, Captures captures, Context context) { TableScanNode tableScan = captures.get(TABLE_SCAN); TableLayoutRewriter tableLayoutRewriter = new TableLayoutRewriter(metadata, context.getSession(), context.getSymbolAllocator(), context.getIdAllocator()); PlanNode rewritten = tableLayoutRewriter.planTableScan(captures.get(TABLE_SCAN), filterNode.getPredicate()); if (arePlansSame(filterNode, tableScan, rewritten)) { return Result.empty(); } return Result.ofPlanNode(rewritten); }
Source:
private boolean isDomainExistAndActive() { if (!validate(getStorageDomainValidator().isDomainExistAndActive())) { return false; } return true; }

Target:
private boolean isDomainExistAndActive() { return (validate(getStorageDomainValidator().isDomainExistAndActive())); }
Source:
public void testMapCountWithBackupReadEnabled() { HazelcastInstance hz = createHazelcastInstance(); Node node = getNode(hz); PhoneHome phoneHome = new PhoneHome(node); Map<String, String> parameters; parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "0"); Map<String, String> map1 = hz.getMap("hazelcast"); parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "0"); node.getConfig().getMapConfig("hazelcast").setReadBackupData(true); parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "1"); }

Target:
public void testMapCountWithBackupReadEnabled() { Map<String, String> parameters; parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "0"); Map<String, String> map1 = node.hazelcastInstance.getMap("hazelcast"); parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "0"); node.getConfig().getMapConfig("hazelcast").setReadBackupData(true); parameters = phoneHome.phoneHome(true); assertEquals(parameters.get("mpbrct"), "1"); }
Source:
public EditShortcutPanel(ObjectMapper objectMapper) { super(); this.objectMapper = objectMapper; final VBox vBox = new VBox(); this.description = new Label(); this.description.setWrapText(true); this.gridPane = new GridPane(); this.gridPane.getStyleClass().add("grid"); this.gridPane.getColumnConstraints().addAll(new ColumnConstraintsWithPercentage(30), new ColumnConstraintsWithPercentage(70)); Region spacer = new Region(); spacer.setPrefHeight(40); GridPane buttons = new GridPane(); buttons.setAlignment(Pos.CENTER); ColumnConstraints runColumn = new ColumnConstraints(); runColumn.setPercentWidth(30); ColumnConstraints stopColumn = new ColumnConstraints(); stopColumn.setPercentWidth(30); ColumnConstraints uninstallColumn = new ColumnConstraints(); uninstallColumn.setPercentWidth(30); buttons.getColumnConstraints().addAll(runColumn, stopColumn, uninstallColumn); this.saveButton = new Button(tr("Save")); vBox.getChildren().addAll(this.description, this.gridPane, spacer, this.saveButton); this.setCenter(vBox); }

Target:
public EditShortcutPanel(ObjectMapper objectMapper) { super(); this.objectMapper = objectMapper; final VBox vBox = new VBox(); this.description = new Label(); this.description.setWrapText(true); this.gridPane = new GridPane(); this.gridPane.getStyleClass().add("grid"); this.gridPane.getColumnConstraints().addAll(new ColumnConstraintsWithPercentage(30), new ColumnConstraintsWithPercentage(70)); Region spacer = new Region(); spacer.getStyleClass().add("detailsButtonSpacer"); this.saveButton = new Button(tr("Save")); vBox.getChildren().addAll(this.description, this.gridPane, spacer, this.saveButton); this.setCenter(vBox); }
Source:
public void addAll(Collection<? extends Contributor> contributors) { if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) { super.addAll(contributors); } else { for (Contributor c : contributors) { add(c); } } }

Target:
public void addAll(Collection<? extends Contributor> contributors) { setNotifyOnChange(false); for (Contributor c : contributors) { add(c); } notifyDataSetChanged(); }
Source:
public void shouldNotThrowExceptionIfSerdesCorrectlySetFromProcessorContext() { EasyMock.expect(innerStoreMock.name()).andStubReturn("mocked-store"); EasyMock.replay(innerStoreMock); final MeteredTimestampedWindowStore<String, Long> store = new MeteredTimestampedWindowStore<>( innerStoreMock, 10L, "scope", new MockTime(), null, null ); store.init(context, innerStoreMock); try { store.put("key", ValueAndTimestamp.make(42L, 60000)); } catch (final StreamsException exception) { if (exception.getCause() instanceof ClassCastException) { fail("Serdes are not correctly set from processor context."); } } }

Target:
public void shouldNotThrowExceptionIfSerdesCorrectlySetFromProcessorContext() { EasyMock.expect(innerStoreMock.name()).andStubReturn("mocked-store"); EasyMock.replay(innerStoreMock); final MeteredTimestampedWindowStore<String, Long> store = new MeteredTimestampedWindowStore<>( innerStoreMock, 10L, "scope", new MockTime(), null, null ); store.init(context, innerStoreMock); try { store.put("key", ValueAndTimestamp.make(42L, 60000)); } catch (final StreamsException exception) { if (exception.getCause() instanceof ClassCastException) { fail("Serdes are not correctly set from processor context."); } throw exception; } }
Source:
private void startRecording(Description des) { GraphicsConfiguration gc = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); File movieFolder = new File("target"); String mimeType = FormatKeys.MIME_QUICKTIME; String videoFormatName = VideoFormatKeys.ENCODING_QUICKTIME_ANIMATION; String compressorName = VideoFormatKeys.COMPRESSOR_NAME_QUICKTIME_ANIMATION; Dimension outputDimension = gc.getBounds().getSize(); int bitDepth = BIT_DEPTH; float quality = QUALITY_RATIO; int screenRate = FRAME_RATE_PER_SEC; long maxRecordingTime = MAX_RECORDING_TIME_SECS; Format outputFormatForScreenCapture = getOutputFormatForScreenCapture(videoFormatName, compressorName, outputDimension, bitDepth, quality, screenRate); try { this.screenRecorder = new JUnitScreenRecorder (gc, gc.getBounds(), getFileFormat(mimeType), outputFormatForScreenCapture, null, null, movieFolder, des); this.screenRecorder.start(); } catch (IOException e) { throw new IllegalArgumentException("Exception starting test recording.", e); } catch (AWTException e) { throw new IllegalArgumentException("Exception starting test recording.", e); } }

Target:
private void startRecording(Description des) { GraphicsConfiguration gc = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); File movieFolder = new File(TARGET); String mimeType = FormatKeys.MIME_QUICKTIME; String videoFormatName = VideoFormatKeys.ENCODING_QUICKTIME_ANIMATION; String compressorName = VideoFormatKeys.COMPRESSOR_NAME_QUICKTIME_ANIMATION; Dimension outputDimension = gc.getBounds().getSize(); int bitDepth = BIT_DEPTH; float quality = QUALITY_RATIO; int screenRate = FRAME_RATE_PER_SEC; long maxRecordingTime = MAX_RECORDING_TIME_SECS; Format outputFormatForScreenCapture = getOutputFormatForScreenCapture(videoFormatName, compressorName, outputDimension, bitDepth, quality, screenRate); try { this.screenRecorder = new JUnitScreenRecorder (gc, gc.getBounds(), getFileFormat(mimeType), outputFormatForScreenCapture, null, null, movieFolder, des); this.screenRecorder.start(); } catch (IOException e) { logger.warn("Exception starting test recording {}", e); } catch (AWTException e) { logger.warn("Exception starting test recording {}", e); } }
Source:
public void run() { shareFileClient.upload(createRandomInputStream(options.getSize()), options.getSize()); }

Target:
public void run() { inputStream.reset(); shareFileClient.upload(inputStream, options.getSize()); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView1 = (TextView)findViewById(R.id.textView1); mLoginProgressDialog = new ProgressDialog(this); mLoginProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mLoginProgressDialog.setMessage("Login in progress..."); try { Utils.setupKeyForSample(); mAuthContext = new AuthenticationContext(MainActivity.this, Constants.AUTHORITY_URL, false); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Encryption is failed", Toast.LENGTH_SHORT) .show(); } Toast.makeText(getApplicationContext(), TAG + "done", Toast.LENGTH_SHORT).show(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView1 = (TextView) findViewById(R.id.textView1); mLoginProgressDialog = new ProgressDialog(this); mLoginProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); mLoginProgressDialog.setMessage("Login in progress..."); try { Utils.setupKeyForSample(); mAuthContext = new AuthenticationContext(MainActivity.this, Constants.AUTHORITY_URL, false); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Encryption failed", Toast.LENGTH_SHORT).show(); } Toast.makeText(getApplicationContext(), TAG + "done", Toast.LENGTH_SHORT).show(); }
Source:
private void createX509KeyManager(Socket socket) { if (!(socket instanceof SSLSocket)) { logAndThrow("Expected a SSLSocket to extract the domain from SNI extension."); } SSLSocket sslSocket = (SSLSocket) socket; String hostname = extractHostname(sslSocket.getHandshakeSession()); if (hostname == null) { logger.info("No domain extracted from SSL/TLS handshake session."); } try { initKeyManagerFactoryWithCertForHostname(keyManagerFactory, hostname, listeningAddress); } catch (InvalidKeyException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | SignatureException | KeyStoreException | IOException e) { logAndThrow("Failed to generate the certificate for '" + hostname + "' caused by: " + e.getMessage(), e); } x509KeyManager = getX509KeyManager(keyManagerFactory.getKeyManagers()); if (x509KeyManager == null) { logAndThrow("No X509KeyManager found in: " + Arrays.toString(keyManagerFactory.getKeyManagers())); } }

Target:
private void createX509KeyManager(Socket socket) { if (!(socket instanceof SSLSocket)) { logAndThrow("Expected a SSLSocket to extract the domain from SNI extension."); } SSLSocket sslSocket = (SSLSocket) socket; String hostname = extractHostname(sslSocket.getHandshakeSession()); if (hostname == null) { logger.debug("No domain extracted from SSL/TLS handshake session."); } try { initKeyManagerFactoryWithCertForHostname(keyManagerFactory, hostname, listeningAddress); } catch (InvalidKeyException | UnrecoverableKeyException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | SignatureException | KeyStoreException | IOException e) { logAndThrow("Failed to generate the certificate for '" + hostname + "' caused by: " + e.getMessage(), e); } x509KeyManager = getX509KeyManager(keyManagerFactory.getKeyManagers()); if (x509KeyManager == null) { logAndThrow("No X509KeyManager found in: " + Arrays.toString(keyManagerFactory.getKeyManagers())); } }
Source:
public void run(@Nonnull JDefinedClassOrInterface type) throws Exception { if (type instanceof JDefinedClass) { JDefinedClass definedClass = (JDefinedClass) type; if (!DirectlyDerivedClassesMarker.hasDirectlyDerivedClasses(definedClass)) { if (!type.isAbstract()) { EffectivelyFinalMarker.markAsEffectivelyFinal(definedClass); if (!preserveReflections()) { definedClass.setFinal(); tracer.getStatistic(TYPES_FINALIZED).incValue(); } } } } }

Target:
public void run(@Nonnull JDefinedClassOrInterface type) throws Exception { if (type instanceof JDefinedClass) { JDefinedClass definedClass = (JDefinedClass) type; if (!DirectlyDerivedClassesMarker.hasDirectlyDerivedClasses(definedClass)) { if (!type.isAbstract() && !type.isFinal()) { EffectivelyFinalClassMarker.markAsEffectivelyFinal(definedClass); if (!preserveReflections()) { definedClass.setFinal(); tracer.getStatistic(TYPES_FINALIZED).incValue(); } } } } }
Source:
public String getBlogUuid() { return super.getUid(); }

Target:
public String getBlogUuid() { return getUid(); }
Source:
public Builder expiry(int duration, TimeUnit unit) { int expiry = (int) TimeUnit.SECONDS.convert(duration, unit); validateExpiry(expiry); operations.add(args -> args.expiry = expiry); return this; }

Target:
public Builder expiry(int duration, TimeUnit unit) { return expiry((int) unit.toSeconds(duration)); }
Source:
public static boolean copy(FileSystem srcFS, FileStatus srcStatus, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { Path src = srcStatus.getPath(); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (dst != null && src != null && src.toUri().equals(dst.toUri())) { throw new PathOperationException("Source (" + src + ") and destination " + "(" + dst + ") are equal in the copy command."); } if (srcStatus.isDirectory()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i], dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else { InputStream in=null; OutputStream out = null; try { in = srcFS.open(src); out = dstFS.create(dst, overwrite); IOUtils.copyBytes(in, out, conf, true); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }

Target:
public static boolean copy(FileSystem srcFS, FileStatus srcStatus, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException { Path src = srcStatus.getPath(); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.makeQualified(src).equals(dstFS.makeQualified(dst))) { throw new PathOperationException("Source (" + src + ") and destination " + "(" + dst + ") are equal in the copy command."); } if (srcStatus.isDirectory()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i], dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else { InputStream in=null; OutputStream out = null; try { in = srcFS.open(src); out = dstFS.create(dst, overwrite); IOUtils.copyBytes(in, out, conf, true); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } if (deleteSource) { return srcFS.delete(src, true); } else { return true; } }
Source:
private void _cleanUpCloseDNSMulticast(List<Throwable> errors) { if(dnsMultiCast!=null) { LOGGER.log(Level.FINE, "Closing DNS multi-cast service-discovery"); try { dnsMultiCast.close(); } catch (OutOfMemoryError e) { throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); errors.add(e); } } }

Target:
private void _cleanUpCloseDNSMulticast(List<Throwable> errors) { if(dnsMultiCast!=null) { LOGGER.log(Level.FINE, "Closing DNS Multicast service"); try { dnsMultiCast.close(); } catch (OutOfMemoryError e) { throw e; } catch (LinkageError e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); } catch (Throwable e) { LOGGER.log(SEVERE, "Failed to close DNS Multicast service", e); errors.add(e); } } }
Source:
public void testDnaStringHasInvalidNucleotides() { expectedException.expect(NullPointerException.class); NucleotideCounter nucleotideCounter = new NucleotideCounter("AGXXACT"); Map<Character, Integer> counts = nucleotideCounter.nucleotideCounts(); }

Target:
public void testDnaStringHasInvalidNucleotides() { expectedException.expect(IllegalArgumentException.class); NucleotideCounter nucleotideCounter = new NucleotideCounter("AGXXACT"); }
Source:
protected void finalize() throws Throwable { try { if (mState != State.CLOSED) { LOG.warn("Finalizing unclosed AsyncHBaseKijiBufferedWriter in state {}.", this, mState); close(); } } catch (Throwable thr) { LOG.warn("Throwable thrown by close() in finalize of AsyncHBaseKijiBufferedWriter: {}\n{}", thr.getMessage(), StringUtils.stringifyException(thr)); } finally { super.finalize(); } }

Target:
protected void finalize() throws Throwable { try { if (mState != State.CLOSED) { CLEANUP_LOG.warn( "Finalizing unclosed AsyncHBaseKijiBufferedWriter in state {}.", this, mState); close(); } } catch (Throwable thr) { LOG.warn("Throwable thrown by close() in finalize of AsyncHBaseKijiBufferedWriter: {}\n{}", thr.getMessage(), StringUtils.stringifyException(thr)); } finally { super.finalize(); } }
Source:
public SplunkServiceFactory(List<SplunkServer> splunkServers) { this.splunkServers = splunkServers; }

Target:
public SplunkServiceFactory(List<SplunkServer> splunkServers) { Assert.notEmpty(splunkServers); this.splunkServers = new ArrayList<SplunkServer>(splunkServers); }
Source:
public URI getAnonymousExecutionURI() { for (Link l : this.links) { if (l.getRelation() == Relation.UNRECOGNIZED) { return l.getHref(); } } return null; }

Target:
public Optional<URI> getAnonymousExecutionURI() { for (Link l : this.links) { if (l.getRelation() == Relation.UNRECOGNIZED) { return Optional.of(l.getHref()); } } return Optional.absent(); }
Source:
private void setCowVirtualSizeAndQcowCompat(DiskImage diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); if (qcow2Signature == QCOW2_SIGNATURE && QCOW2_VERSIONS.contains(qcow2Version)) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); diskImage.setQcowCompat(QcowCompat.forQcowHeaderVersion(qcow2Version)); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }

Target:
private void setCowVirtualSizeAndQcowCompat(DiskImage diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); QcowCompat qcowCompat = QcowCompat.forQcowHeaderVersion(qcow2Version); if (qcow2Signature == QCOW2_SIGNATURE && (qcowCompat != null || qcowCompat != QcowCompat.Undefined)) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); diskImage.setQcowCompat(qcowCompat); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }
Source:
public void setup() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); addInlinedPropertiesToEnvironment( context, AAD_PROPERTY_PREFIX + "user-group.allowed-groups = group1", AAD_PROPERTY_PREFIX + "tenant-id = fake-tenant-id", AAD_PROPERTY_PREFIX + "client-id = fake-client-id", AAD_PROPERTY_PREFIX + "client-secret = fake-client-secret", AAD_PROPERTY_PREFIX + "webApiClients.fake-graph.scopes = <LINK_0>" ); context.register(AADResourceServerOboConfiguration.class); context.refresh(); clientRegistrationsRepo = context.getBean(AADOboClientRegistrationRepository.class); }

Target:
public void setup() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); addInlinedPropertiesToEnvironment( context, AAD_PROPERTY_PREFIX + "tenant-id = fake-tenant-id", AAD_PROPERTY_PREFIX + "client-id = fake-client-id", AAD_PROPERTY_PREFIX + "client-secret = fake-client-secret", AAD_PROPERTY_PREFIX + "authorization.fake-graph.scopes = <LINK_0>" ); context.register(AADResourceServerOboConfiguration.class); context.refresh(); clientRegistrationsRepo = context.getBean(InMemoryClientRegistrationRepository.class); }
Source:
private LineString interpolateToLineString(Coordinate[] arcCoordinates, Coordinate center, double radius) { List<Coordinate> generatedCoordinates = new ArrayList<Coordinate>(); generatedCoordinates.add(pointToGrid(arcCoordinates[0])); double angle = getAngleBetweenTwoPoints(arcCoordinates[0], arcCoordinates[1], radius); generatedCoordinates.addAll(generateLineStringCoordinates(arcCoordinates[0], arcCoordinates[1], center, radius, angle, NEXT_COORDINATE_DISTANCE)); generatedCoordinates.add(pointToGrid(arcCoordinates[1])); angle = getAngleBetweenTwoPoints(arcCoordinates[1], arcCoordinates[2], radius); generatedCoordinates.addAll(generateLineStringCoordinates(arcCoordinates[1], arcCoordinates[2], center, radius, angle, NEXT_COORDINATE_DISTANCE)); generatedCoordinates.add(pointToGrid(arcCoordinates[2])); LineString lineString = null; try { lineString = new GeometryFactory() .createLineString(generatedCoordinates.toArray(new Coordinate[0])); } catch (Exception ex) { log.error("Error in interpolation of arc", ex); } return lineString; }

Target:
private LineString interpolateToLineString(Coordinate[] arcCoordinates, Coordinate center, double radius) { List<Coordinate> generatedCoordinates = new ArrayList<Coordinate>(); generatedCoordinates.add(pointToGrid(arcCoordinates[0])); double angle = getAngleBetweenTwoPoints(arcCoordinates[0], arcCoordinates[1], radius); generatedCoordinates.addAll(generateLineStringCoordinates(arcCoordinates[0], arcCoordinates[1], center, radius, angle, NEXT_COORDINATE_DISTANCE)); if (!isSameAsLastGridCoordinate(arcCoordinates[1])) generatedCoordinates.add(lastGridCoordinateOfArc); angle = getAngleBetweenTwoPoints(arcCoordinates[1], arcCoordinates[2], radius); generatedCoordinates.addAll(generateLineStringCoordinates(arcCoordinates[1], arcCoordinates[2], center, radius, angle, NEXT_COORDINATE_DISTANCE)); if (!isSameAsLastGridCoordinate(arcCoordinates[2])) generatedCoordinates.add(lastGridCoordinateOfArc); LineString lineString = null; try { lineString = new GeometryFactory() .createLineString(generatedCoordinates.toArray(new Coordinate[0])); } catch (Exception ex) { log.error("Error in interpolation of arc", ex); } return lineString; }
Source:
public Response activate(Action action) { VdsActionParameters params = new VdsActionParameters(guid); int timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksWaitTimeoutSeconds); params.setLockProperties(LockProperties.create(Execution).withWaitTimeout(SECONDS.toMillis(timeout))); return doAction(ActionType.ActivateVds, params, action); }

Target:
public Response activate(Action action) { return doAction(ActionType.ActivateVds, new VdsTimedWaitActionParameters(guid), action); }
Source:
protected TupleBatch fetchNextReady() throws DbException { while (!getChild().eos()) { TupleBatch tb = getChild().nextReady(); if (tb == null) { if (getChild().eos()) { break; } return null; } extractWorkerInfo(tb); } if (isPercentageSample) { sampleSize = Math.round(totalTupleCount * (samplePercentage / 100)); } Preconditions.checkState(sampleSize >= 0 && sampleSize <= totalTupleCount, "Cannot extract %s samples from a population of size %s", sampleSize, totalTupleCount); if (sampleType == SamplingType.WithReplacement) { withReplacementDistribution(workerInfo, totalTupleCount, sampleSize); } else if (sampleType == SamplingType.WithoutReplacement) { withoutReplacementDistribution(workerInfo, totalTupleCount, sampleSize); } else { throw new DbException("Invalid sampleType: " + sampleType); } IntColumnBuilder wIDs = new IntColumnBuilder(); IntColumnBuilder actualSizes = new IntColumnBuilder(); IntColumnBuilder sampSizes = new IntColumnBuilder(); StringColumnBuilder sampTypes = new StringColumnBuilder(); for (Map.Entry<Integer, WorkerInfo> iWorker : workerInfo.entrySet()) { wIDs.appendInt(iWorker.getKey()); actualSizes.appendInt(iWorker.getValue().actualTupleCount); sampSizes.appendInt(iWorker.getValue().sampleSize); sampTypes.appendString(sampleType.name()); } ImmutableList.Builder<Column<?>> columns = ImmutableList.builder(); columns.add(wIDs.build(), actualSizes.build(), sampSizes.build(), sampTypes.build()); setEOS(); return new TupleBatch(SCHEMA, columns.build()); }

Target:
protected TupleBatch fetchNextReady() throws DbException { while (!getChild().eos()) { TupleBatch tb = getChild().nextReady(); if (tb == null) { if (getChild().eos()) { break; } return null; } extractWorkerInfo(tb); } getChild().close(); if (isPercentageSample) { sampleSize = Math.round(totalTupleCount * (samplePercentage / 100)); } Preconditions.checkState(sampleSize >= 0 && sampleSize <= totalTupleCount, "Cannot extract %s samples from a population of size %s", sampleSize, totalTupleCount); if (sampleType == SamplingType.WithReplacement) { withReplacementDistribution(workerInfo, totalTupleCount, sampleSize); } else if (sampleType == SamplingType.WithoutReplacement) { withoutReplacementDistribution(workerInfo, totalTupleCount, sampleSize); } else { throw new DbException("Invalid sampleType: " + sampleType); } List<ColumnBuilder<?>> colBuilders = ColumnFactory.allocateColumns(SCHEMA); for (Map.Entry<Integer, WorkerInfo> iWorker : workerInfo.entrySet()) { colBuilders.get(0).appendInt(iWorker.getKey()); colBuilders.get(1).appendInt(iWorker.getValue().actualTupleCount); colBuilders.get(2).appendInt(iWorker.getValue().sampleSize); colBuilders.get(3).appendString(sampleType.name()); } ImmutableList.Builder<Column<?>> columns = ImmutableList.builder(); for (ColumnBuilder<?> cb : colBuilders) { columns.add(cb.build()); } setEOS(); return new TupleBatch(SCHEMA, columns.build()); }
Source:
public Object eval(String expression, Entity entity) { Stopwatch stopwatch = null; if (LOG.isTraceEnabled()) { stopwatch = Stopwatch.createStarted(); } Object scriptEngineValueMap = toScriptEngineValueMap(entity, 3); Object value; try { value = jsScriptEngine.invokeFunction("evalScript", expression, scriptEngineValueMap); } catch (Throwable t) { return new ScriptException(t); } if (stopwatch != null) { stopwatch.stop(); LOG.trace("Script evaluation took µs", stopwatch.elapsed(MICROSECONDS)); } return value; }

Target:
public Object eval(String expression, Entity entity) { Stopwatch stopwatch = null; if (LOG.isTraceEnabled()) { stopwatch = Stopwatch.createStarted(); } Object scriptEngineValueMap = toScriptEngineValueMap(entity, ENTITY_REFERENCE_FETCHING_DEPTH); Object value; try { value = jsScriptEngine.invokeFunction("evalScript", expression, scriptEngineValueMap); } catch (Throwable t) { return new ScriptException(t); } if (stopwatch != null) { stopwatch.stop(); LOG.trace("Script evaluation took µs", stopwatch.elapsed(MICROSECONDS)); } return value; }
Source:
public RegisteredObservers load(CuratorFramework curator) throws Exception { ImmutableMap<Column, ObserverSpecification> observers; ImmutableMap<Column, ObserverSpecification> weakObservers; ByteArrayInputStream bais; try { bais = new ByteArrayInputStream(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_OBSERVERS1)); } catch (NoNodeException nne) { return null; } DataInputStream dis = new DataInputStream(bais); observers = readObservers(dis); weakObservers = readObservers(dis); return new RegisteredObservers() { @Override public Observers getObservers(Environment env) { return new ObserversV1(env, observers, weakObservers); } @Override public ImmutableSet<Column> getObservedColumns(NotificationType nt) { switch (nt) { case STRONG: return observers.keySet(); case WEAK: return weakObservers.keySet(); default: throw new IllegalArgumentException("Unknown notification type " + nt); } } }; }

Target:
public RegisteredObservers load(CuratorFramework curator) throws Exception { Map<Column, ObserverSpecification> observers; Map<Column, ObserverSpecification> weakObservers; ByteArrayInputStream bais; try { bais = new ByteArrayInputStream(curator.getData().forPath(ZookeeperPath.CONFIG_FLUO_OBSERVERS1)); } catch (NoNodeException nne) { return null; } DataInputStream dis = new DataInputStream(bais); observers = readObservers(dis); weakObservers = readObservers(dis); return new RegisteredObservers() { @Override public Observers getObservers(Environment env) { return new ObserversV1(env, observers, weakObservers); } @Override public Set<Column> getObservedColumns(NotificationType nt) { switch (nt) { case STRONG: return observers.keySet(); case WEAK: return weakObservers.keySet(); default: throw new IllegalArgumentException("Unknown notification type " + nt); } } }; }
Source:
public CatalogContext( Catalog catalog, DbSettings settings, int version, long genId, CatalogInfo catalogInfo, DefaultProcedureManager defaultProcManager, PlannerTool plannerTool, HostMessenger messenger, boolean hasSchemaChange) { if (catalog == null) { throw new IllegalArgumentException("Can't create CatalogContext with null catalog."); } if (settings == null) { throw new IllegalArgumentException("Cant't create CatalogContent with null cluster settings"); } this.catalog = catalog; cluster = catalog.getClusters().get("cluster"); database = cluster.getDatabases().get("database"); procedures = database.getProcedures(); tables = database.getTables(); authSystem = new AuthSystem(database, cluster.getSecurityenabled()); m_dbSettings = settings; catalogVersion = version; m_genId = genId; m_catalogInfo = catalogInfo; if (hasSchemaChange) { m_defaultProcs = new DefaultProcedureManager(database); m_ptool = new PlannerTool(database, m_catalogInfo.m_catalogHash); } else { m_defaultProcs = defaultProcManager; m_ptool = plannerTool.updateWhenNoSchemaChange(database, m_catalogInfo.m_catalogHash);; } m_jdbc = new JdbcDatabaseMetaDataGenerator(catalog, m_defaultProcs, m_catalogInfo.m_jarfile); m_messenger = messenger; if (procedures != null) { for (Procedure proc : procedures) { if (proc.getSinglepartition()) { ProcedurePartitionInfo ppi = new ProcedurePartitionInfo(VoltType.get((byte)proc.getPartitioncolumn().getType()), proc.getPartitionparameter()); proc.setAttachment(ppi); } } } m_memoizedDeployment = null; }

Target:
public CatalogContext( Catalog catalog, DbSettings settings, int version, long genId, CatalogInfo catalogInfo, DefaultProcedureManager defaultProcManager, PlannerTool plannerTool, HostMessenger messenger, boolean hasSchemaChange) { if (catalog == null) { throw new IllegalArgumentException("Can't create CatalogContext with null catalog."); } if (settings == null) { throw new IllegalArgumentException("Cant't create CatalogContext with null cluster settings"); } this.catalog = catalog; cluster = catalog.getClusters().get("cluster"); database = cluster.getDatabases().get("database"); procedures = database.getProcedures(); tables = database.getTables(); authSystem = new AuthSystem(database, cluster.getSecurityenabled()); m_dbSettings = settings; catalogVersion = version; m_genId = genId; m_catalogInfo = catalogInfo; if (hasSchemaChange) { m_defaultProcs = new DefaultProcedureManager(database); m_ptool = new PlannerTool(database, m_catalogInfo.m_catalogHash); } else { m_defaultProcs = defaultProcManager; m_ptool = plannerTool.updateWhenNoSchemaChange(database, m_catalogInfo.m_catalogHash);; } m_jdbc = new JdbcDatabaseMetaDataGenerator(catalog, m_defaultProcs, m_catalogInfo.m_jarfile); m_messenger = messenger; if (procedures != null) { for (Procedure proc : procedures) { if (proc.getSinglepartition()) { ProcedurePartitionInfo ppi = new ProcedurePartitionInfo(VoltType.get((byte)proc.getPartitioncolumn().getType()), proc.getPartitionparameter()); proc.setAttachment(ppi); } } } m_memoizedDeployment = null; }
Source:
public static List<Object> mapDataRow(Entity entity) { List<Object> dataRow = newArrayList(); for (Attribute attribute : entity.getEntityType().getAttributes()) { if (attribute.getDataType() != AttributeType.COMPOUND) { if (isSingleReferenceType(attribute)) { Entity value = entity.getEntity(attribute.getName()); dataRow.add(value != null ? value.getIdValue() : null); } else if (isMultipleReferenceType(attribute)) { Iterable<Entity> values = entity.getEntities(attribute.getName()); List<Object> ids = StreamSupport.stream(values.spliterator(), false) .map(Entity::getIdValue) .collect(Collectors.toList()); dataRow.add(org.apache.logging.log4j.util.Strings.join(ids, ',')); } else { Object value = entity.get(attribute.getName()); dataRow.add(value); } } } return dataRow; }

Target:
public static List<Object> mapDataRow(Entity entity) { List<Object> dataRow = new ArrayList<>(); for (Attribute attribute : entity.getEntityType().getAttributes()) { if (attribute.getDataType() != AttributeType.COMPOUND) { if (isSingleReferenceType(attribute)) { Entity value = entity.getEntity(attribute.getName()); dataRow.add(value != null ? value.getIdValue() : null); } else if (isMultipleReferenceType(attribute)) { Iterable<Entity> values = entity.getEntities(attribute.getName()); String ids = Streams.stream(values) .map(Entity::getIdValue) .map(Object::toString) .collect(joining(",")); dataRow.add(ids); } else { Object value = entity.get(attribute.getName()); dataRow.add(value); } } } return dataRow; }
Source:
private void decodePosition(JsonObject object, Position position) { position.setProtocol(protocolName); position.setTime(new Date((long) object.getJsonNumber("timestamp").doubleValue() * 1000)); JsonNumber lat = object.getJsonNumber("position.latitude"); JsonNumber lon = object.getJsonNumber("position.longitude"); position.setLatitude(lat != null ? lat.doubleValue() : 0); position.setLongitude(lon != null ? lon.doubleValue() : 0); JsonNumber speed = object.getJsonNumber("position.speed"); position.setSpeed(speed != null ? speed.doubleValue() : 0); JsonNumber course = object.getJsonNumber("position.direction"); position.setCourse(course != null ? course.doubleValue() : 0); JsonNumber altitude = object.getJsonNumber("position.altitude"); position.setAltitude(altitude != null ? altitude.doubleValue() : 0); int satellites = object.getInt("position.satellites", 0); position.setValid(object.getBoolean("position.valid", true)); position.set(Position.KEY_SATELLITES, satellites); if (object.getBoolean("alarm.event.trigger", false)) { position.set(Position.KEY_ALARM, Position.ALARM_GENERAL); } }

Target:
private void decodePosition(JsonObject object, Position position) { position.setProtocol(getProtocolName()); Date deviceTime = new Date((long) object.getJsonNumber("timestamp").doubleValue() * 1000); position.setTime(deviceTime); JsonNumber lat = object.getJsonNumber("position.latitude"); JsonNumber lon = object.getJsonNumber("position.longitude"); if (lat != null && lon != null) { position.setLatitude(lat.doubleValue()); position.setLongitude(lon.doubleValue()); } else { getLastLocation(position, deviceTime); } JsonNumber speed = object.getJsonNumber("position.speed"); if (speed != null) { position.setSpeed(speed.doubleValue()); } JsonNumber course = object.getJsonNumber("position.direction"); if (course != null) { position.setCourse(course.doubleValue()); } JsonNumber altitude = object.getJsonNumber("position.altitude"); if (altitude != null) { position.setAltitude(altitude.doubleValue()); } position.setValid(object.getBoolean("position.valid", true)); position.set(Position.KEY_SATELLITES, object.getInt("position.satellites", 0)); if (object.getBoolean("alarm.event.trigger", false)) { position.set(Position.KEY_ALARM, Position.ALARM_GENERAL); } }