auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Bitmap decodeStream(InputStream stream, Request data) throws IOException { if (stream == null) { return null; } MarkableInputStream markStream = new MarkableInputStream(stream); stream = markStream; long mark = markStream.savePosition(1024); byte[] fileHeaderBytes = new byte[WEBP_FILE_HEADER_SIZE]; boolean isWebPFile = false; if (stream.read(fileHeaderBytes, 0, WEBP_FILE_HEADER_SIZE) == WEBP_FILE_HEADER_SIZE) { isWebPFile = WEBP_FILE_HEADER_RIFF.equals(new String(fileHeaderBytes, 0, 4)) && WEBP_FILE_HEADER_WEBP.equals(new String(fileHeaderBytes, 8, 4)); } markStream.reset(mark); if (isWebPFile) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024 * 4]; int n = 0; while (-1 != (n = stream.read(buffer))) { byteArrayOutputStream.write(buffer, 0, n); } byte[] bytes = byteArrayOutputStream.toByteArray(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPurgeable = true; options.inInputShareable = true; if (data.hasSize()) { options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); calculateInSampleSize(data.targetWidth, data.targetHeight, options); } return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); } else { BitmapFactory.Options options = null; if (data.hasSize()) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(stream, null, options); calculateInSampleSize(data.targetWidth, data.targetHeight, options); markStream.reset(mark); } return BitmapFactory.decodeStream(stream, null, options); } }

Target:
private Bitmap decodeStream(InputStream stream, Request data) throws IOException { if (stream == null) { return null; } MarkableInputStream markStream = new MarkableInputStream(stream); stream = markStream; long mark = markStream.savePosition(MARKER); boolean isWebPFile = Utils.isWebPFile(stream); markStream.reset(mark); if (isWebPFile) { byte[] bytes = Utils.toByteArray(stream); BitmapFactory.Options options = null; if (data.hasSize()) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); calculateInSampleSize(data.targetWidth, data.targetHeight, options); } return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options); } else { BitmapFactory.Options options = null; if (data.hasSize()) { options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(stream, null, options); calculateInSampleSize(data.targetWidth, data.targetHeight, options); markStream.reset(mark); } return BitmapFactory.decodeStream(stream, null, options); } }
Source:
private static void printUsage() { System.out.println("Usage:"); System.out.println("StoreUtils -[enc|dec|pvk] -store=path/to/keystore-file -pass=keystore-pass -string='string to be enc/decrypted' [-alias='cert alias']"); System.out.println("StoreUtils -pubkey2ssh -store=path/to/keystore-file -pass=keystore-pass -alias='cert alias'"); }

Target:
private static void printUsage() { System.out.println("Usage:"); System.out.println("StoreUtils -[enc|dec] -store=path/to/keystore-file -pass=keystore-pass -string='string to be enc/decrypted' [-alias='cert alias']"); System.out.println("StoreUtils -pubkey2ssh -store=path/to/keystore-file -pass=keystore-pass -alias='cert alias'"); }
Source:
private float getPercenUsedCores(QueueMetrics metrics) { int totalCores = metrics.getAllocatedVirtualCores() + metrics.getAvailableVirtualCores(); int usedCores = metrics.getAllocatedVirtualCores() + metrics.getPendingVirtualCores(); return (float) usedCores / totalCores; }

Target:
private float getPercenUsedCores(QueueMetrics metrics) { int totalCores = metrics.getAllocatedVirtualCores() + metrics.getAvailableVirtualCores(); int usedCores = metrics.getAllocatedVirtualCores() + metrics.getPendingVirtualCores(); return totalCores == 0 ? 0 : (float) usedCores / totalCores; }
Source:
public SerialMessage executeRefresh(ZWaveNode node, ZWaveSwitchAllCommandClass commandClass, int endpointId, Map<String, String> arguments) { logger.debug("NODE {}: Generating poll message for {}, endpoint {}", new Object[]{node.getNodeId(), commandClass.getCommandClass().getLabel(), endpointId}); return node.encapsulate(commandClass.getValueMessage(), commandClass, endpointId); }

Target:
public SerialMessage executeRefresh(ZWaveNode node, ZWaveSwitchAllCommandClass commandClass, int endpointId, Map<String, String> arguments) { return null; }
Source:
public boolean minimized() { return "min".equals(m_matcher.group(4)); }

Target:
public boolean minimized() { return MINIMIZED_URL_KEYWORD.equals(m_matcher.group(4)); }
Source:
public List<CloudianUser> listUsers(final String groupId) { if (Strings.isNullOrEmpty(groupId)) { return new ArrayList<>(); } LOG.debug("Trying to list Cloudian users in group id=" + groupId); try { final HttpResponse response = get(String.format("/user/list?groupId=%s&userType=all&userStatus=active", groupId)); checkResponseOK(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NO_CONTENT || response.getEntity() == null || response.getEntity().getContent() == null) { return new ArrayList<>(); } final ObjectMapper mapper = new ObjectMapper(); return Arrays.asList(mapper.readValue(response.getEntity().getContent(), CloudianUser[].class)); } catch (final IOException e) { LOG.error("Failed to list Cloudian users due to:", e); checkResponseTimeOut(e); } return new ArrayList<>(); }

Target:
public List<CloudianUser> listUsers(final String groupId) { if (Strings.isNullOrEmpty(groupId)) { return new ArrayList<>(); } LOG.debug("Trying to list Cloudian users in group id=" + groupId); try { final HttpResponse response = get(String.format("/user/list?groupId=%s&userType=all&userStatus=active", groupId)); checkResponseOK(response); if (checkEmptyResponse(response)) { return new ArrayList<>(); } final ObjectMapper mapper = new ObjectMapper(); return Arrays.asList(mapper.readValue(response.getEntity().getContent(), CloudianUser[].class)); } catch (final IOException e) { LOG.error("Failed to list Cloudian users due to:", e); checkResponseTimeOut(e); } return new ArrayList<>(); }
Source:
public void validate(Schema inputSchema, List<String> groupByFields, List<GroupByConfig.FunctionInfo> aggregates, FailureCollector collector) { for (String groupByField : groupByFields) { Schema.Field field = inputSchema.getField(groupByField); if (field == null) { collector.addFailure(String.format("Cannot group by field '%s' because it does not exist in input schema.", groupByField), null) .withConfigElement("groupByFields", groupByField); } } for (GroupByConfig.FunctionInfo functionInfo : aggregates) { if (functionInfo.getField().equals("*")) { continue; } Schema.Field inputField = inputSchema.getField(functionInfo.getField()); String collectorFieldName = String.format("%s:%s(%s)", functionInfo.getName(), functionNameMap.get(functionInfo.getFunction().toString().toUpperCase()), functionInfo.getField()); if (inputField == null) { collector.addFailure( String.format("Invalid aggregate %s(%s): Field '%s' does not exist in input schema.", functionInfo.getFunction(), functionInfo.getField(), functionInfo.getField()), null) .withConfigElement("aggregates", collectorFieldName); } if (functionInfo.getField().equalsIgnoreCase(functionInfo.getName())) { collector.addFailure(String.format("Name '%s' should not be same as aggregate field '%s'", functionInfo.getName(), functionInfo.getField()), null) .withConfigElement("aggregates", collectorFieldName); } if (GroupByConfig.Function.COUNTDISTINCT == functionInfo.getFunction()) { if (!conf.containsMacro("aggregates")) { validateCountDistinct(inputField, collector, collectorFieldName); } } } }

Target:
public void validate(Schema inputSchema, List<String> groupByFields, List<GroupByConfig.FunctionInfo> aggregates, FailureCollector collector) { for (String groupByField : groupByFields) { Schema.Field field = inputSchema.getField(groupByField); if (field == null) { collector.addFailure(String.format("Cannot group by field '%s' because it does not exist in input schema.", groupByField), null) .withConfigElement("groupByFields", groupByField); } } for (GroupByConfig.FunctionInfo functionInfo : aggregates) { if (functionInfo.getField().equals("*")) { continue; } Schema.Field inputField = inputSchema.getField(functionInfo.getField()); String collectorFieldName = String.format("%s:%s(%s)", functionInfo.getName(), functionNameMap.get(functionInfo.getFunction().toString().toUpperCase()), functionInfo.getField()); if (inputField == null) { collector.addFailure( String.format("Invalid aggregate %s(%s): Field '%s' does not exist in input schema.", functionInfo.getFunction(), functionInfo.getField(), functionInfo.getField()), null) .withConfigElement("aggregates", collectorFieldName); } if (functionInfo.getField().equalsIgnoreCase(functionInfo.getName())) { collector.addFailure(String.format("Name '%s' should not be same as aggregate field '%s'", functionInfo.getName(), functionInfo.getField()), null) .withConfigElement("aggregates", collectorFieldName); } if (GroupByConfig.Function.COUNTDISTINCT == functionInfo.getFunction()) { validateCountDistinct(inputField, collector, collectorFieldName); } } }
Source:
public void offerProducerCredit(final SimpleString address, final int credits, final int threshold, final Receiver receiver) { try { PagingManager pagingManager = manager.getServer().getPagingManager(); Runnable creditRunnable = () -> { connection.lock(); try { if (receiver.getCredit() <= threshold) { receiver.flow(credits - receiver.getCredit()); } } finally { connection.unlock(); } connection.flush(); }; if (address == null) { pagingManager.checkMemory(creditRunnable); } else { final PagingStore store = manager.getServer().getPagingManager().getPageStore(address); store.checkMemory(creditRunnable); } } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public void offerProducerCredit(final SimpleString address, final int credits, final int threshold, final Receiver receiver) { try { PagingManager pagingManager = manager.getServer().getPagingManager(); Runnable creditRunnable = () -> { connection.lock(); try { if (receiver.getCredit() <= threshold) { int topUp = credits - receiver.getCredit(); if (topUp > 0) { receiver.flow(topUp); } } } finally { connection.unlock(); } connection.flush(); }; if (address == null) { pagingManager.checkMemory(creditRunnable); } else { final PagingStore store = manager.getServer().getPagingManager().getPageStore(address); store.checkMemory(creditRunnable); } } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private void createModel() throws ModelMapException, ArrangeException, UnexpectedDiagramTypeException, UnexpectedEndException { for (Pair<String, DiagramExportationReport> report : layout.getReportsWithDiagramNames()) { String name = report.getFirst(); DiagramExportationReport der = report.getSecond(); LayoutVisualizerManager lvm = new LayoutVisualizerManager(der.getNodes(), der.getLinks(), der.getStatements()); lvm.arrange(); ModelMapProvider map = new ModelMapProvider(URI.createFileURI(genFolder), der.getModelName()); List<Statement> statements = lvm.getStatementsSet(); double spacing = 0.8; Statement s = statements.stream().filter(statement -> statement.getType() == StatementType.corridorsize) .findFirst().orElse(null); if (s != null) { spacing = Double.parseDouble(s.getParameter(0)); } switch (der.getType()) { case Class: model.addClassDiagram(name, lvm.getObjects(), lvm.getAssociations(), map, spacing); break; case StateMachine: model.addStateMachine(name, lvm.getObjects(), lvm.getAssociations(), map, spacing); break; default: throw new UnexpectedDiagramTypeException(name, der.getType().name()); } } }

Target:
private void createModel() throws ModelMapException, ArrangeException, UnexpectedDiagramTypeException, UnexpectedEndException, UnexpectedException { for (Pair<String, DiagramExportationReport> report : layout.getReportsWithDiagramNames()) { String name = report.getFirst(); DiagramExportationReport der = report.getSecond(); ModelMapProvider map = new ModelMapProvider(URI.createFileURI(genFolder), der.getModelName()); model.createDiagram(name, report.getSecond(), map); } }
Source:
public void refresh() { asyncNewSession(); }

Target:
public void refresh() { sessionCredentials.set(null); blockingNewSession(); }
Source:
public static ReportDesign createJSONTemplateDesign(String reportDesignUuid, ReportDefinition reportDefinition, String resourcePath) { ReportDesign design = new ReportDesign(); design.setUuid(reportDesignUuid); design.setName("JSON"); design.setReportDefinition(reportDefinition); design.setRendererType(JSONTemplateRenderer.class); ReportDesignResource resource = new ReportDesignResource(); resource.setName("template"); resource.setExtension("json"); resource.setContentType("application/json"); resource.setContents(ReportUtil.readByteArrayFromResource(resourcePath)); resource.setReportDesign(design); design.addResource(resource); return design; }

Target:
public static ReportDesign createJSONTemplateDesign(String reportDesignUuid, ReportDefinition reportDefinition, String resourcePath) { ReportDesign design = createJSONReportDesign(reportDesignUuid,reportDefinition); design.setReportDefinition(reportDefinition); design.setRendererType(TextTemplateRenderer.class); ReportDesignResource resource = new ReportDesignResource(); resource.setName("template"); resource.setExtension("json"); resource.setContentType("application/json"); resource.setContents(ReportUtil.readByteArrayFromResource(resourcePath)); resource.setReportDesign(design); design.addResource(resource); return design; }
Source:
public void switchAgentState(String agentName) { loader.waitOnClosed(); new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfElementLocated( By.xpath(format(Locators.AGENT_STATE, agentName)))) .click(); }

Target:
public void switchAgentState(String agentName) { new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) .until( ExpectedConditions.visibilityOfElementLocated( By.xpath(format(Locators.AGENT_STATE, agentName)))) .click(); }
Source:
public int deletePendingSegments(String dataSource, Interval deleteInterval) { final Optional<DateTime> minCreatedDateOfActiveTasks = taskStorageQueryAdapter .getActiveTasks() .stream() .map(task -> taskStorageQueryAdapter.getCreatedTime(task.getId())) .min(Comparator.naturalOrder()); final Interval activeTaskInterval = new Interval( minCreatedDateOfActiveTasks.orElse(DateTimes.MAX), DateTimes.MAX ); Preconditions.checkArgument( !deleteInterval.overlaps(activeTaskInterval), "Cannot delete pendingSegments because there is at least one running task created at %s", activeTaskInterval.getStart() ); return indexerMetadataStorageCoordinator.deletePendingSegments(dataSource, deleteInterval); }

Target:
public int deletePendingSegments(String dataSource, Interval deleteInterval) { final Optional<DateTime> minCreatedDateOfActiveTasks = taskStorageQueryAdapter .getActiveTasks() .stream() .map(task -> Preconditions.checkNotNull( taskStorageQueryAdapter.getCreatedTime(task.getId()), "Can't find the createdTime for task[%s]", task.getId() )) .min(Comparator.naturalOrder()); final Interval activeTaskInterval = new Interval( minCreatedDateOfActiveTasks.orElse(DateTimes.MAX), DateTimes.MAX ); Preconditions.checkArgument( !deleteInterval.overlaps(activeTaskInterval), "Cannot delete pendingSegments because there is at least one active task created at %s", activeTaskInterval.getStart() ); return indexerMetadataStorageCoordinator.deletePendingSegments(dataSource, deleteInterval); }
Source:
protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) { final BeanDefinitionBuilder jpaPollingChannelAdapterBuilder = BeanDefinitionBuilder .genericBeanDefinition(JpaPollingChannelAdapter.class); final BeanDefinitionBuilder jpaExecutorBuilder = JpaParserUtils.getJpaExecutorBuilder(element, parserContext); if(element.hasAttribute("max-number-of-results")) { String maxNumberOfResultsValue = element.getAttribute("max-number-of-results"); jpaExecutorBuilder.addPropertyValue("maxNumberOfResultsExpression", new LiteralExpression(maxNumberOfResultsValue)); } IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "delete-after-poll"); IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "delete-in-batch"); IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "expect-single-result"); final BeanDefinition jpaExecutorBuilderBeanDefinition = jpaExecutorBuilder.getBeanDefinition(); final String channelAdapterId = this.resolveId(element, jpaPollingChannelAdapterBuilder.getRawBeanDefinition(), parserContext); final String jpaExecutorBeanName = channelAdapterId + ".jpaExecutor"; parserContext.registerBeanComponent(new BeanComponentDefinition(jpaExecutorBuilderBeanDefinition, jpaExecutorBeanName)); jpaPollingChannelAdapterBuilder.addConstructorArgReference(jpaExecutorBeanName); return jpaPollingChannelAdapterBuilder.getBeanDefinition(); }

Target:
protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) { final BeanDefinitionBuilder jpaPollingChannelAdapterBuilder = BeanDefinitionBuilder .genericBeanDefinition(JpaPollingChannelAdapter.class); final BeanDefinitionBuilder jpaExecutorBuilder = JpaParserUtils.getJpaExecutorBuilder(element, parserContext); RootBeanDefinition definition = IntegrationNamespaceUtils .createExpressionDefinitionFromValueOrExpression("max-number-of-results", "max-results-expression", parserContext, element, false); if(definition != null) { jpaExecutorBuilder.addPropertyValue("maxResultsExpression", definition); } IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "delete-after-poll"); IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "delete-in-batch"); IntegrationNamespaceUtils.setValueIfAttributeDefined(jpaExecutorBuilder, element, "expect-single-result"); final BeanDefinition jpaExecutorBuilderBeanDefinition = jpaExecutorBuilder.getBeanDefinition(); final String channelAdapterId = this.resolveId(element, jpaPollingChannelAdapterBuilder.getRawBeanDefinition(), parserContext); final String jpaExecutorBeanName = channelAdapterId + ".jpaExecutor"; parserContext.registerBeanComponent(new BeanComponentDefinition(jpaExecutorBuilderBeanDefinition, jpaExecutorBeanName)); jpaPollingChannelAdapterBuilder.addConstructorArgReference(jpaExecutorBeanName); return jpaPollingChannelAdapterBuilder.getBeanDefinition(); }
Source:
public void setDataExporters(Collection<IDataExporter<? extends Object>> dataExporters) { final Map<String, IDataExporter<Object>> dataExportersMap = new LinkedHashMap<String, IDataExporter<Object>>(); final Set<IPortalDataType> portalDataTypes = new LinkedHashSet<IPortalDataType>(); for (final IDataExporter<?> dataExporter : dataExporters) { try { final IPortalDataType portalDataType = dataExporter.getPortalDataType(); final String typeId = portalDataType.getTypeId(); this.logger.debug("Registering IDataExporter for '{}' - {}", new Object[]{typeId, dataExporter}); final IDataExporter<Object> existing = dataExportersMap.put(typeId, (IDataExporter<Object>) dataExporter); if (existing != null) { this.logger.warn("Duplicate IDataExporter typeId for Replacing with {}", new Object[]{typeId, existing, dataExporter}); } portalDataTypes.add(portalDataType); } catch (Exception exception) { logger.error("Something bad happened provisioning exporter into JaxbPortalDataHandlerService;" + " ignoring that exporter.", dataExporter, exception); } } this.portalDataExporters = Collections.unmodifiableMap(dataExportersMap); this.exportPortalDataTypes = Collections.unmodifiableSet(portalDataTypes); }

Target:
public void setDataExporters(Collection<IDataExporter<? extends Object>> dataExporters) { final Map<String, IDataExporter<Object>> dataExportersMap = new LinkedHashMap<String, IDataExporter<Object>>(); final Set<IPortalDataType> portalDataTypes = new LinkedHashSet<IPortalDataType>(); for (final IDataExporter<?> dataExporter : dataExporters) { try { final IPortalDataType portalDataType = dataExporter.getPortalDataType(); final String typeId = portalDataType.getTypeId(); this.logger.debug("Registering IDataExporter for '{}' - {}", new Object[]{typeId, dataExporter}); final IDataExporter<Object> existing = dataExportersMap.put(typeId, (IDataExporter<Object>) dataExporter); if (existing != null) { this.logger.warn("Duplicate IDataExporter typeId for Replacing with {}", new Object[]{typeId, existing, dataExporter}); } portalDataTypes.add(portalDataType); } catch (Exception exception) { logger.error("Failed to register data exporter {}.", dataExporter, exception); } } this.portalDataExporters = Collections.unmodifiableMap(dataExportersMap); this.exportPortalDataTypes = Collections.unmodifiableSet(portalDataTypes); }
Source:
public IgniteInternalFuture<Void> stop() { synchronized (this) { if (!enabled) return new GridFinishedFuture<>(); enabled = false; } log.info("Stopping performance statistics writer."); FileWriter fileWriter = this.fileWriter; if (fileWriter != null) return fileWriter.shutdown(); return new GridFinishedFuture<>(); }

Target:
public synchronized void stop() { assert started; ringByteBuf.close(); U.awaitForWorkersStop(Collections.singleton(fileWriter), true, log); ringByteBuf.poll(); ringByteBuf.free(); try { fileIo.force(); } catch (IOException e) { log.warning("Failed to fsync the performance statistics file.", e); } U.closeQuiet(fileIo); knownStrs.clear(); started = false; }
Source:
protected void executeCommand() { deviceSizeVisibilityError = false; changeStorageDomainStatusInTransaction(getStorageDomain().getStoragePoolIsoMapData(), StorageDomainStatus.Locked); List<String> lunsToRefresh = getParameters().getLunIds(); Map<String, List<Pair<VDS, Integer>>> lunToVds = getDeviceListAllVds(lunsToRefresh); Map<String, List<VDS>> lunToFailedVDS = getFailedLuns(lunToVds); if (!lunToFailedVDS.isEmpty()) { deviceSizeVisibilityError = true; List<String> failedVds = new ArrayList<>(); for (Map.Entry<String, List<VDS>> entry : lunToFailedVDS.entrySet()) { String lunId = entry.getKey(); List<VDS> vdsList = entry.getValue(); log.error("Failed to refresh device " + lunId + " Not all VDS are seeing the same size " + "VDS :" + vdsList); String vdsListString = StringUtils.join(Entities.objectNames(vdsList), ", "); failedVds.add("LUN : " + lunId + "VDS: " + vdsListString); } throw new VdcBLLException(VdcBllErrors.REFRESH_LUN_ERROR, "Failed to refresh LUNs. Not all VDS are seeing the same size: " + failedVds); } resizePVs(lunsToRefresh); updateStorageDomainData(); changeStorageDomainStatusInTransaction(getStorageDomain().getStoragePoolIsoMapData(), StorageDomainStatus.Active); setSucceeded(true); }

Target:
protected void executeCommand() { changeStorageDomainStatusInTransaction(getStorageDomain().getStoragePoolIsoMapData(), StorageDomainStatus.Locked); List<String> lunsToRefresh = getParameters().getLunIds(); Map<String, List<Pair<VDS, Integer>>> lunToVds = getDeviceListAllVds(lunsToRefresh); Map<String, List<VDS>> lunToFailedVDS = getFailedLuns(lunToVds); if (!lunToFailedVDS.isEmpty()) { deviceSizeVisibilityError = true; List<String> failedVds = new ArrayList<>(); for (Map.Entry<String, List<VDS>> entry : lunToFailedVDS.entrySet()) { String lunId = entry.getKey(); List<VDS> vdsList = entry.getValue(); log.error("Failed to refresh device " + lunId + " Not all VDS are seeing the same size " + "VDS :" + vdsList); String vdsListString = StringUtils.join(Entities.objectNames(vdsList), ", "); failedVds.add("LUN : " + lunId + "VDS: " + vdsListString); } throw new VdcBLLException(VdcBllErrors.REFRESH_LUN_ERROR, "Failed to refresh LUNs. Not all VDS are seeing the same size: " + failedVds); } resizePVs(lunsToRefresh); updateStorageDomainData(); changeStorageDomainStatusInTransaction(getStorageDomain().getStoragePoolIsoMapData(), StorageDomainStatus.Active); setSucceeded(true); }
Source:
protected void executeCommand() { List<String> errors = new ArrayList<String>(); entity = getGlusterHooksDao().getById(getParameters().getHookId()); List <VDS> servers = getAllUpServers(getParameters().getClusterId()); List<Callable<Pair<VDS, VDSReturnValue>>> taskList = new ArrayList<Callable<Pair<VDS, VDSReturnValue>>>(); for (final VDS upServer : servers) { taskList.add(new Callable<Pair<VDS, VDSReturnValue>>() { @Override public Pair<VDS, VDSReturnValue> call() throws Exception { VDSReturnValue returnValue = runVdsCommand( getStatusChangeVDSCommand(), new GlusterHookVDSParameters(upServer.getId(), entity.getGlusterCommand(), entity.getStage(), entity.getName())); return new Pair<VDS, VDSReturnValue>(upServer, returnValue); } }); } List<Pair<VDS, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(taskList); for (Pair<VDS, VDSReturnValue> pairResult : pairResults) { VDSReturnValue retValue = pairResult.getSecond(); if (retValue.getSucceeded()) { updateServerHookStatusInDb(entity.getId(), pairResult.getFirst().getId(), getNewStatus()); } else { errors.add(retValue.getVdsError().getMessage()); } } if (errors.size() > 0) { entity.addStatusConflict(); setSucceeded(false); } else { setSucceeded(true); } entity.setStatus(getNewStatus()); updateServerHookInDb(entity); }

Target:
protected void executeCommand() { List<String> errors = new ArrayList<String>(); entity = getGlusterHooksDao().getById(getParameters().getHookId(),true); List <VDS> servers = getAllUpServers(getParameters().getClusterId()); List<GlusterServerHook> serverHooks = entity.getServerHooks(); if (serverHooks.size() != servers.size()) { errors.add(VdcBllMessages.CLUSTER_ALL_SERVERS_NOT_UP.toString()); } List<Callable<Pair<VDS, VDSReturnValue>>> taskList = new ArrayList<Callable<Pair<VDS, VDSReturnValue>>>(); for (final VDS upServer : servers) { taskList.add(new Callable<Pair<VDS, VDSReturnValue>>() { @Override public Pair<VDS, VDSReturnValue> call() throws Exception { VDSReturnValue returnValue = runVdsCommand( getStatusChangeVDSCommand(), new GlusterHookVDSParameters(upServer.getId(), entity.getGlusterCommand(), entity.getStage(), entity.getName())); return new Pair<VDS, VDSReturnValue>(upServer, returnValue); } }); } List<Pair<VDS, VDSReturnValue>> pairResults = ThreadPoolUtil.invokeAll(taskList); for (Pair<VDS, VDSReturnValue> pairResult : pairResults) { VDSReturnValue retValue = pairResult.getSecond(); if (retValue.getSucceeded()) { updateServerHookStatusInDb(entity.getId(), pairResult.getFirst().getId(), getNewStatus()); } else { if (!VdcBllErrors.GlusterHookAlreadyEnabled.equals(retValue.getVdsError().getCode())) { errors.add(retValue.getVdsError().getMessage()); } } } if (errors.size() > 0) { entity.addStatusConflict(); setSucceeded(false); } else { setSucceeded(true); } entity.setStatus(getNewStatus()); updateHookInDb(entity); }
Source:
public boolean updateApplicationModule(String appModuleId, ApplicationModule applicationModule) throws RegistryServiceException, TException { try { new ApplicationInterfaceRepository().updateApplicationModule(appModuleId, applicationModule); logger.debug("Airavata updated application module with module id: " + appModuleId); return true; } catch (AppCatalogException e) { logger.error(appModuleId, "Error while updating application module...", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating application module. More info : " + e.getMessage()); throw exception; } }

Target:
public boolean updateApplicationModule(String appModuleId, ApplicationModule applicationModule) throws RegistryServiceException, TException { try { applicationInterfaceRepository.updateApplicationModule(appModuleId, applicationModule); logger.debug("Airavata updated application module with module id: " + appModuleId); return true; } catch (AppCatalogException e) { logger.error(appModuleId, "Error while updating application module...", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while updating application module. More info : " + e.getMessage()); throw exception; } }
Source:
public CompletableFuture<Void> stopAsync(Workspace workspace, Map<String, String> options) throws NotFoundException, ConflictException { TracingTags.WORKSPACE_ID.set(workspace.getId()); TracingTags.STOPPED_BY.set( () -> firstNonNull( sessionUserIdOr(workspace.getAttributes().get(WORKSPACE_STOPPED_BY)), "undefined")); TracingTags.STACK_ID.set(() -> workspace.getAttributes().getOrDefault("stackId", "no stack")); String workspaceId = workspace.getId(); WorkspaceStatus status = statuses.get(workspaceId); if (status == null) { throw new NotFoundException("Workspace with id '" + workspaceId + "' is not running."); } if (status != RUNNING && status != STARTING) { throw new ConflictException( format("Could not stop workspace '%s' because its state is '%s'", workspaceId, status)); } if (!statuses.replace(workspaceId, status, STOPPING)) { WorkspaceStatus newStatus = statuses.get(workspaceId); throw new ConflictException( format( "Could not stop workspace '%s' because its state is '%s'", workspaceId, newStatus == null ? STOPPED : newStatus)); } setRuntimesId(workspaceId); String stoppedBy = firstNonNull( sessionUserNameOr(workspace.getAttributes().get(WORKSPACE_STOPPED_BY)), "undefined"); LOG.info( "Workspace '{}/{}' with id '{}' is stopping by user '{}'", workspace.getNamespace(), workspace.getConfig().getName(), workspace.getId(), stoppedBy); publishWorkspaceStatusEvent(workspaceId, STOPPING, status, options.get(WORKSPACE_STOP_REASON)); return CompletableFuture.runAsync( ThreadLocalPropagateContext.wrap(new StopRuntimeTask(workspace, options, stoppedBy)), sharedPool.getExecutor()); }

Target:
public CompletableFuture<Void> stopAsync(Workspace workspace, Map<String, String> options) throws NotFoundException, ConflictException { TracingTags.WORKSPACE_ID.set(workspace.getId()); TracingTags.STOPPED_BY.set(getStoppedBy(workspace)); TracingTags.STACK_ID.set(() -> workspace.getAttributes().getOrDefault("stackId", "no stack")); String workspaceId = workspace.getId(); WorkspaceStatus status = statuses.get(workspaceId); if (status == null) { throw new NotFoundException("Workspace with id '" + workspaceId + "' is not running."); } if (status != RUNNING && status != STARTING) { throw new ConflictException( format("Could not stop workspace '%s' because its state is '%s'", workspaceId, status)); } if (!statuses.replace(workspaceId, status, STOPPING)) { WorkspaceStatus newStatus = statuses.get(workspaceId); throw new ConflictException( format( "Could not stop workspace '%s' because its state is '%s'", workspaceId, newStatus == null ? STOPPED : newStatus)); } setRuntimesId(workspaceId); String stoppedBy = firstNonNull( sessionUserNameOr(workspace.getAttributes().get(WORKSPACE_STOPPED_BY)), "undefined"); LOG.info( "Workspace '{}/{}' with id '{}' is stopping by user '{}'", workspace.getNamespace(), workspace.getConfig().getName(), workspace.getId(), stoppedBy); publishWorkspaceStatusEvent(workspaceId, STOPPING, status, options.get(WORKSPACE_STOP_REASON)); return CompletableFuture.runAsync( ThreadLocalPropagateContext.wrap(new StopRuntimeTask(workspace, options, stoppedBy)), sharedPool.getExecutor()); }
Source:
public int compareTo(ImmutablePassengerData o) { return ComparisonChain.start() .compare(o.vehicle().get().getType().getName(), this.vehicle.getType().getName()) .compare(o.baseVehicle().get().getType().getName(), this.vehicle.getType().getName()) .result(); }

Target:
public int compareTo(ImmutablePassengerData o) { return ComparisonChain.start().compare(o.vehicle().get().getType().getName(), this.vehicle.getType().getName()) .compare(o.baseVehicle().get().getType().getName(), this.baseVehicle.getType().getName()) .compare(o.vehicle().get().getUniqueId(), this.vehicle.getUniqueId()) .compare(o.baseVehicle().get().getUniqueId(), this.baseVehicle.getUniqueId()).result(); }
Source:
public void setGroupIdHelpBock(String groupIdHelpBock) { this.groupIdHelpBock.setText(groupIdHelpBock); if (!"".equals(groupIdHelpBock)) { this.rootTR.className = "kie-tablelist__row has-error"; } else { this.rootTR.className = "kie-tablelist__row"; } }

Target:
public void setGroupIdHelpBock(String groupIdHelpBock) { this.groupIdHelpBock.setText(groupIdHelpBock); if (!groupIdHelpBock.isEmpty()) { this.groupIdTD.classList.add("has-error"); } else { this.groupIdTD.classList.remove("has-error"); } }
Source:
public void start(BundleContext bundleContext) throws Exception { StacksCoreActivator.context = bundleContext; DEFAULT = this; new StacksManager().getStacks(new NullProgressMonitor()); }

Target:
public void start(BundleContext bundleContext) throws Exception { StacksCoreActivator.context = bundleContext; DEFAULT = this; }
Source:
public void testBadNumberOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); geocodedCountryUDF.close(); }

Target:
public void testBadNumberOfArguments() throws HiveException, IOException { ObjectInspector value1 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector value2 = PrimitiveObjectInspectorFactory.javaStringObjectInspector; ObjectInspector[] initArguments = new ObjectInspector[]{value1, value2}; GeocodedCountryUDF geocodedCountryUDF = new GeocodedCountryUDF(); geocodedCountryUDF.initialize(initArguments); }
Source:
public Column(final ColumnSize firstSize, final ColumnSize... otherSizes) { setSize(firstSize, otherSizes); setStyleName(firstSize.getCssName()); }

Target:
public Column(final ColumnSize firstSize, final ColumnSize... otherSizes) { setSize(firstSize, otherSizes); }
Source:
private Class<?> getRawType(final Type type) { if (!Class.class.isInstance(type) && !ParameterizedType.class.isInstance(type)) { throw new IllegalStateException("Unsupported generic type " + type.getClass().getName()); } else if (Class.class.isInstance(type)) { return Class.class.cast(type); } else { return getRawType(ParameterizedType.class.cast(type).getRawType()); } }

Target:
private Class<?> getRawType(final Type type) { if (!Class.class.isInstance(type) && !ParameterizedType.class.isInstance(type)) { throw new IllegalStateException("Unsupported generic type " + type.getClass().getName()); } else if (Class.class.isInstance(type)) { return Class.class.cast(type); } else { return Class.class.cast(ParameterizedType.class.cast(type).getRawType()); } }
Source:
public void disconnect(String message) { if (isOnline()) { visit(""); find(by.link("Disconnect")).click(); find(by.input("offlineMessage")).clear(); find(by.input("offlineMessage")).sendKeys(message); clickButton("Yes"); } }

Target:
public void disconnect(String message) { if (isOnline()) { open(); find(by.link("Disconnect")).click(); find(by.input("offlineMessage")).clear(); find(by.input("offlineMessage")).sendKeys(message); clickButton("Yes"); } }
Source:
public void showLinkPreview(PageTitle title, int entrySource) { final String linkPreviewFragmentTag = "link_preview_dialog"; if (getSupportFragmentManager().findFragmentByTag(linkPreviewFragmentTag) == null) { linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), linkPreviewFragmentTag); } }

Target:
public void showLinkPreview(PageTitle title, int entrySource) { final String linkPreviewFragmentTag = "link_preview_dialog"; if (getSupportFragmentManager().findFragmentByTag(linkPreviewFragmentTag) == null) { LinkPreviewDialog linkPreview = LinkPreviewDialog.newInstance(title, entrySource); linkPreview.show(getSupportFragmentManager(), linkPreviewFragmentTag); } }
Source:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, ""); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }

Target:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateMessageEventCatching emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertMessageEventExecutionSet(emptySubprocessEvent.getExecutionSet(), EMPTY_VALUE, CANCELLING, EMPTY_VALUE); assertDataIOSet(emptySubprocessEvent.getDataIOSet(), EMPTY_VALUE); }
Source:
public SignedUploadRequest uploadSingleFile(final FileToSign toSign, final InputStream stream) throws EvrythngException, IOException { final List<FileToSign> toSignList = Collections.singletonList(toSign); final List<SignedUploadRequest> signedUploadRequests = fileUploadRequestsSigner(toSignList).execute(); final SignedUploadRequest signedUploadRequest = signedUploadRequests.get(0); final URL url = new URL(signedUploadRequest.getSignedUploadUrl()); FileUtils.uploadPublicStream(url, toSign.getType(), stream); return signedUploadRequest; }

Target:
public SignedUploadRequest uploadSingleFile(final FileToSign toSign, final InputStream stream) throws EvrythngException, IOException { final List<FileToSign> toSignList = Collections.singletonList(toSign); final List<SignedUploadRequest> signedUploadRequests = fileUploadRequestsSigner(toSignList).execute(); final SignedUploadRequest signedUploadRequest = signedUploadRequests.get(0); final URL url = new URL(signedUploadRequest.getSignedUploadUrl()); FileUtils.uploadStream(url, toSign.getType(), stream); return signedUploadRequest; }
Source:
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { Log log = helper.getLog(); try { MavenProject project = (MavenProject) helper.evaluate( "${project}" ); if (!project.getPackaging().equals("pom")) { List<License> licenses = getLicenses(project); if (licenses.size() == 0) { throw new EnforcerRuleException("You must set a license for this project"); } } else { log.info("Ignoring " + this.getClass().getSimpleName() + " in this project"); } } catch (ExpressionEvaluationException eee) { throw new EnforcerRuleException( "Unable to get project.", eee); } }

Target:
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException { Log log = helper.getLog(); try { MavenProject project = (MavenProject) helper.evaluate( "${project}" ); if (!"pom".equals(project.getPackaging())) { List<License> licenses = getLicenses(project); if (licenses.size() == 0) { if (hasLicenseFile(project)) { log.warn("License file found in the root of your project"); } throw new EnforcerRuleException("You must set a license for this project. Please read: <LINK_0>"); } } else { log.info("Ignoring " + this.getClass().getSimpleName() + " in this project"); } } catch (ExpressionEvaluationException eee) { throw new EnforcerRuleException("Unable to get project.", eee); } }
Source:
private void cleanupLeftOverJobs(final long msid) { try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { _queueMgr.cleanupActiveQueueItems(msid, true); List<AsyncJobVO> jobs = _jobDao.getResetJobs(msid); for (AsyncJobVO job : jobs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over job-" + job.getId()); } job.setStatus(JobInfo.Status.FAILED); job.setResultCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode()); job.setResult("job cancelled because of management server restart or shutdown"); job.setCompleteMsid(msid); _jobDao.update(job.getId(), job); if (s_logger.isDebugEnabled()) { s_logger.debug("Purge queue item for cancelled job-" + job.getId()); } _queueMgr.purgeAsyncJobQueueItemId(job.getId()); if(job.getInstanceType().equals("Volume")) { try { VolumeDetailVO volumeDetailVO = _volumeDetailsDao.findDetail(job.getInstanceId(), "SNAPSHOT_ID"); if (volumeDetailVO != null) { _volumeDetailsDao.remove(volumeDetailVO.getId()); } } catch (Exception e) { s_logger.error("Unexpected exception while removing concurrent request meta data :" + e.getLocalizedMessage()); } } } } }); } catch (Throwable e) { s_logger.warn("Unexpected exception in cleaning up left over jobs for mamagement server node " + msid, e); } }

Target:
private void cleanupLeftOverJobs(final long msid) { try { Transaction.execute(new TransactionCallbackNoReturn() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { _queueMgr.cleanupActiveQueueItems(msid, true); List<AsyncJobVO> jobs = _jobDao.getResetJobs(msid); for (AsyncJobVO job : jobs) { if (s_logger.isDebugEnabled()) { s_logger.debug("Cancel left-over job-" + job.getId()); } job.setStatus(JobInfo.Status.FAILED); job.setResultCode(ApiErrorCode.INTERNAL_ERROR.getHttpCode()); job.setResult("job cancelled because of management server restart or shutdown"); job.setCompleteMsid(msid); _jobDao.update(job.getId(), job); if (s_logger.isDebugEnabled()) { s_logger.debug("Purge queue item for cancelled job-" + job.getId()); } _queueMgr.purgeAsyncJobQueueItemId(job.getId()); if (job.getInstanceType().equals(ApiCommandJobType.Volume.toString())) { try { _volumeDetailsDao.removeDetail(job.getInstanceId(), "SNAPSHOT_ID"); } catch (Exception e) { s_logger.error("Unexpected exception while removing concurrent request meta data :" + e.getLocalizedMessage()); } } } } }); } catch (Throwable e) { s_logger.warn("Unexpected exception in cleaning up left over jobs for mamagement server node " + msid, e); } }
Source:
protected Void createTemplateCallback(AsyncCallbackDispatcher<TemplateServiceImpl, CreateCmdResult> callback, TemplateOpContext<TemplateApiResult> context) { TemplateObject template = context.getTemplate(); AsyncCompletionCallback<TemplateApiResult> parentCallback = context.getParentCallback(); TemplateApiResult result = new TemplateApiResult(template); CreateCmdResult callbackResult = callback.getResult(); if (callbackResult.isFailed()) { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); result.setResult(callbackResult.getResult()); if (parentCallback != null) { parentCallback.complete(result); } return null; } if (template.getFormat().equals(ImageFormat.OVA)) { if (!createDataDiskTemplates(template)) { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); result.setResult(callbackResult.getResult()); if (parentCallback != null) { parentCallback.complete(result); } return null; } } try { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (Exception e) { result.setResult(e.toString()); if (parentCallback != null) { parentCallback.complete(result); } return null; } if (parentCallback != null) { parentCallback.complete(result); } return null; }

Target:
protected Void createTemplateCallback(AsyncCallbackDispatcher<TemplateServiceImpl, CreateCmdResult> callback, TemplateOpContext<TemplateApiResult> context) { TemplateObject template = context.getTemplate(); AsyncCompletionCallback<TemplateApiResult> parentCallback = context.getParentCallback(); TemplateApiResult result = new TemplateApiResult(template); CreateCmdResult callbackResult = callback.getResult(); if (callbackResult.isFailed()) { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); result.setResult(callbackResult.getResult()); if (parentCallback != null) { parentCallback.complete(result); } return null; } if (template.getFormat().equals(ImageFormat.OVA)) { if (!createOvaDataDiskTemplates(template)) { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationFailed); result.setResult(callbackResult.getResult()); if (parentCallback != null) { parentCallback.complete(result); } return null; } } try { template.processEvent(ObjectInDataStoreStateMachine.Event.OperationSuccessed); } catch (Exception e) { result.setResult(e.toString()); if (parentCallback != null) { parentCallback.complete(result); } return null; } if (parentCallback != null) { parentCallback.complete(result); } return null; }
Source:
private void log(final List<LogEntry> logEntries) { final long start = System.currentTimeMillis(); final boolean success = log(clientProvider.getClient(), logEntries); final long end = System.currentTimeMillis(); notificationsHandler.onSpansSent(end - start, logEntries.size(), !success); processedSpans += logEntries.size(); if (success && LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Submitting " + logEntries.size() + " spans to service took " + (end - start) + "ms."); } }

Target:
private void log(final List<LogEntry> logEntries) { final long start = System.currentTimeMillis(); final boolean success = log(clientProvider.getClient(), logEntries); processedSpans += logEntries.size(); if (success && LOGGER.isLoggable(Level.FINE)) { final long end = System.currentTimeMillis(); LOGGER.fine("Submitting " + logEntries.size() + " spans to service took " + (end - start) + "ms."); } }
Source:
public void testGetWithEntityId() { dao = dbFacade.getUnregisteredOVFDataDao(); OvfEntityData ovfEntityData = dao.getByEntityIdAndStorageDomain(FixturesTool.VM_RHEL5_POOL_50, FixturesTool.STORAGE_DOAMIN_NFS2_1); assertNotNull("VM should exists in the UnregisteredOVFData", ovfEntityData); }

Target:
public void testGetWithEntityId() { OvfEntityData ovfEntityData = dao.getByEntityIdAndStorageDomain(FixturesTool.VM_RHEL5_POOL_50, FixturesTool.STORAGE_DOAMIN_NFS2_1); assertNotNull("VM should exists in the UnregisteredOVFData", ovfEntityData); }
Source:
CacheMetrics(Cache cache) { super(cache); registry = SharedMetricRegistries.getOrCreate(MetricsService.class.getName()); read = registry.counter(READ_NAME); read_hit = registry.counter(READ_HIT_NAME); read_miss = registry.counter(READ_MISS_NAME); registry.register(READ_HITRATIO_NAME, read_hit_ratio = new RatioGauge() { @Override protected Ratio getRatio() { Ratio ratio = Ratio.of(read_hit.getCount(), read.getCount()); return ratio; } }); write = registry.counter(WRITE_NAME); invalidation = registry.counter(INVALIDATE_ALL_NAME); registry.register(SIZE_NAME, size = new Gauge<Long>() { @Override public Long getValue() { return Long.valueOf(cache.getSize()); } }); }

Target:
public CacheMetrics(Cache cache) { super(cache); registry = SharedMetricRegistries.getOrCreate(MetricsService.class.getName()); read = registry.counter(readName); read_hit = registry.counter(readHitName); read_miss = registry.counter(readMissName); registry.register(readHitRatio, read_hit_ratio = new RatioGauge() { @Override protected Ratio getRatio() { Ratio ratio = Ratio.of(read_hit.getCount(), read.getCount()); return ratio; } }); write = registry.counter(writeName); invalidation = registry.counter(invalidateAllName); registry.register(sizeName, size = new Gauge<Long>() { @Override public Long getValue() { return Long.valueOf(cache.getSize()); } }); }
Source:
public TimeTZ value(Object value) { if (value == null) { return null; } if (value instanceof TimeTZ) { return (TimeTZ) value; } if (value instanceof String) { try { return TimeTZParser.parse((String) value); } catch (IllegalArgumentException e0) { try { return timeTZOf( TimeTZType.class.getSimpleName(), Long.valueOf((String) value)); } catch (NumberFormatException e1) { throw exceptionForInvalidLiteral(value); } } } throw exceptionForInvalidLiteral(value); }

Target:
public TimeTZ value(Object value) { if (value == null) { return null; } return (TimeTZ) value; }