List of usage examples for java.util.concurrent TimeUnit NANOSECONDS
TimeUnit NANOSECONDS
To view the source code for java.util.concurrent TimeUnit NANOSECONDS.
Click Source Link
From source file:com.cosmosource.app.personnel.service.UnitAdminManager.java
/** * @Description?//from w w w . j a va2 s.c o m * @Authorhj * @Date2013-7-5 * @return boolean **/ public boolean confirmPubCard(String cardId, String nodeId, String opt) { boolean isSuccess = true; Map<String, Object> condtion = new HashMap<String, Object>(); condtion.put("cardId", cardId); condtion.put("nodeId", Integer.parseInt(nodeId)); if ("add".equals(opt)) { Long startTime = System.nanoTime(); while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (System.nanoTime() - startTime > TimeUnit.NANOSECONDS.convert(5000, TimeUnit.MILLISECONDS)) { isSuccess = false; break; } List<Map> listMap = this.sqlDao.findList("PersonnelUnitSQL.getAuthDoorStatus", condtion); if (null == listMap || listMap.size() == 0) { isSuccess = false; break; } else { if (null == listMap.get(0).get("EXP1") || StringUtil.isBlank(String.valueOf(listMap.get(0).get("EXP1")))) { break; } else if ("2".equals(String.valueOf(listMap.get(0).get("EXP1")))) { isSuccess = false; break; } } } } else if ("del".equals(opt)) { Long startTime = System.nanoTime(); while (true) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } if (System.nanoTime() - startTime > TimeUnit.NANOSECONDS.convert(5000, TimeUnit.MILLISECONDS)) { isSuccess = false; break; } List<Map> listMap = this.sqlDao.findList("PersonnelUnitSQL.getAuthDoorStatus", condtion); if (null == listMap || listMap.size() == 0) { break; } else { if (null != listMap.get(0).get("EXP1") && "3".equals(String.valueOf(listMap.get(0).get("EXP1")))) { isSuccess = false; break; } } } } return isSuccess; }
From source file:org.apache.hadoop.hbase.client.AsyncHBaseAdmin.java
private void getProcedureResult(final long procId, CompletableFuture<Void> future) { this.<GetProcedureResultResponse>newMasterCaller() .action((controller, stub) -> this .<GetProcedureResultRequest, GetProcedureResultResponse, GetProcedureResultResponse>call( controller, stub, GetProcedureResultRequest.newBuilder().setProcId(procId).build(), (s, c, req, done) -> s.getProcedureResult(c, req, done), (resp) -> resp)) .call().whenComplete((response, error) -> { if (error != null) { LOG.warn("failed to get the procedure result procId=" + procId, ConnectionUtils.translateException(error)); connection.RETRY_TIMER.newTimeout(t -> getProcedureResult(procId, future), pauseNs, TimeUnit.NANOSECONDS); return; }// w w w . ja v a 2 s . c om if (response.getState() == GetProcedureResultResponse.State.RUNNING) { connection.RETRY_TIMER.newTimeout(t -> getProcedureResult(procId, future), pauseNs, TimeUnit.NANOSECONDS); return; } if (response.hasException()) { IOException ioe = ForeignExceptionUtil.toIOException(response.getException()); future.completeExceptionally(ioe); } else { future.complete(null); } }); }
From source file:com.sonicle.webtop.core.app.ServiceManager.java
public BaseService instantiatePrivateService(String serviceId, PrivateEnvironment environment) { ServiceDescriptor descr = getDescriptor(serviceId); if (!descr.hasPrivateService()) throw new RuntimeException("Service has no default class"); // Creates service instance BaseService instance = null;//from w ww . j a v a 2 s . c o m try { instance = (BaseService) descr.getPrivateServiceClass().newInstance(); } catch (Throwable t) { logger.error("PrivateService: instantiation failure [{}]", t, descr.getManifest().getPrivateServiceClassName()); return null; } instance.configure(environment); // Calls initialization method long start = 0, end = 0; logger.trace("PrivateService: calling initialize() [{}]", serviceId); try { LoggerUtils.setContextDC(serviceId); start = System.nanoTime(); instance.initialize(); end = System.nanoTime(); } catch (Throwable t) { logger.error("PrivateService: initialize() throws errors [{}]", t, instance.getClass().getCanonicalName()); } finally { LoggerUtils.clearContextServiceDC(); } if (logger.isTraceEnabled() && (end != 0)) logger.trace("PrivateService: initialize() took {} ms [{}]", TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS), serviceId); return instance; }
From source file:gobblin.compaction.mapreduce.MRCompactor.java
@Override public void cancel() throws IOException { try {//from w w w . ja va2 s . c o m for (Map.Entry<Dataset, Job> entry : MRCompactor.RUNNING_MR_JOBS.entrySet()) { Job hadoopJob = entry.getValue(); if (!hadoopJob.isComplete()) { LOG.info(String.format("Killing hadoop job %s for dataset %s", hadoopJob.getJobID(), entry.getKey())); hadoopJob.killJob(); } } } finally { try { ExecutorsUtils.shutdownExecutorService(this.jobExecutor, Optional.of(LOG), 0, TimeUnit.NANOSECONDS); } finally { this.verifier.get().closeNow(); } } }
From source file:org.apache.solr.client.solrj.impl.CloudSolrClient.java
private NamedList<Object> directUpdate(AbstractUpdateRequest request, String collection, ClusterState clusterState) throws SolrServerException { UpdateRequest updateRequest = (UpdateRequest) request; ModifiableSolrParams params = (ModifiableSolrParams) request.getParams(); ModifiableSolrParams routableParams = new ModifiableSolrParams(); ModifiableSolrParams nonRoutableParams = new ModifiableSolrParams(); if (params != null) { nonRoutableParams.add(params);//w ww . j a va 2s. c o m routableParams.add(params); for (String param : NON_ROUTABLE_PARAMS) { routableParams.remove(param); } } if (collection == null) { throw new SolrServerException( "No collection param specified on request and no default collection has been set."); } //Check to see if the collection is an alias. Aliases aliases = zkStateReader.getAliases(); if (aliases != null) { Map<String, String> collectionAliases = aliases.getCollectionAliasMap(); if (collectionAliases != null && collectionAliases.containsKey(collection)) { collection = collectionAliases.get(collection); } } DocCollection col = getDocCollection(clusterState, collection, null); DocRouter router = col.getRouter(); if (router instanceof ImplicitDocRouter) { // short circuit as optimization return null; } //Create the URL map, which is keyed on slice name. //The value is a list of URLs for each replica in the slice. //The first value in the list is the leader for the slice. final Map<String, List<String>> urlMap = buildUrlMap(col); final Map<String, LBHttpSolrClient.Req> routes = (urlMap == null ? null : updateRequest.getRoutes(router, col, urlMap, routableParams, this.idField)); if (routes == null) { if (directUpdatesToLeadersOnly && hasInfoToFindLeaders(updateRequest, idField)) { // we have info (documents with ids and/or ids to delete) with // which to find the leaders but we could not find (all of) them throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "directUpdatesToLeadersOnly==true but could not find leader(s)"); } else { // we could not find a leader or routes yet - use unoptimized general path return null; } } final NamedList<Throwable> exceptions = new NamedList<>(); final NamedList<NamedList> shardResponses = new NamedList<>(routes.size() + 1); // +1 for deleteQuery long start = System.nanoTime(); if (parallelUpdates) { final Map<String, Future<NamedList<?>>> responseFutures = new HashMap<>(routes.size()); for (final Map.Entry<String, LBHttpSolrClient.Req> entry : routes.entrySet()) { final String url = entry.getKey(); final LBHttpSolrClient.Req lbRequest = entry.getValue(); try { MDC.put("CloudSolrClient.url", url); responseFutures.put(url, threadPool.submit(() -> lbClient.request(lbRequest).getResponse())); } finally { MDC.remove("CloudSolrClient.url"); } } for (final Map.Entry<String, Future<NamedList<?>>> entry : responseFutures.entrySet()) { final String url = entry.getKey(); final Future<NamedList<?>> responseFuture = entry.getValue(); try { shardResponses.add(url, responseFuture.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } catch (ExecutionException e) { exceptions.add(url, e.getCause()); } } if (exceptions.size() > 0) { Throwable firstException = exceptions.getVal(0); if (firstException instanceof SolrException) { SolrException e = (SolrException) firstException; throw new RouteException(ErrorCode.getErrorCode(e.code()), exceptions, routes); } else { throw new RouteException(ErrorCode.SERVER_ERROR, exceptions, routes); } } } else { for (Map.Entry<String, LBHttpSolrClient.Req> entry : routes.entrySet()) { String url = entry.getKey(); LBHttpSolrClient.Req lbRequest = entry.getValue(); try { NamedList<Object> rsp = lbClient.request(lbRequest).getResponse(); shardResponses.add(url, rsp); } catch (Exception e) { if (e instanceof SolrException) { throw (SolrException) e; } else { throw new SolrServerException(e); } } } } UpdateRequest nonRoutableRequest = null; List<String> deleteQuery = updateRequest.getDeleteQuery(); if (deleteQuery != null && deleteQuery.size() > 0) { UpdateRequest deleteQueryRequest = new UpdateRequest(); deleteQueryRequest.setDeleteQuery(deleteQuery); nonRoutableRequest = deleteQueryRequest; } Set<String> paramNames = nonRoutableParams.getParameterNames(); Set<String> intersection = new HashSet<>(paramNames); intersection.retainAll(NON_ROUTABLE_PARAMS); if (nonRoutableRequest != null || intersection.size() > 0) { if (nonRoutableRequest == null) { nonRoutableRequest = new UpdateRequest(); } nonRoutableRequest.setParams(nonRoutableParams); List<String> urlList = new ArrayList<>(); urlList.addAll(routes.keySet()); Collections.shuffle(urlList, rand); LBHttpSolrClient.Req req = new LBHttpSolrClient.Req(nonRoutableRequest, urlList); try { LBHttpSolrClient.Rsp rsp = lbClient.request(req); shardResponses.add(urlList.get(0), rsp.getResponse()); } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, urlList.get(0), e); } } long end = System.nanoTime(); RouteResponse rr = condenseResponse(shardResponses, (int) TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS)); rr.setRouteResponses(shardResponses); rr.setRoutes(routes); return rr; }
From source file:com.sonicle.webtop.core.app.ServiceManager.java
public void cleanupPrivateService(BaseService instance) { long start = 0, end = 0; logger.trace("PrivateService: calling cleanup() [{}]", instance.SERVICE_ID); try {/* w w w. ja v a2s .c o m*/ LoggerUtils.setContextDC(instance.SERVICE_ID); start = System.nanoTime(); instance.cleanup(); end = System.nanoTime(); } catch (Throwable t) { logger.error("PrivateService: cleanup() throws errors [{}]", t, instance.getClass().getCanonicalName()); } finally { LoggerUtils.clearContextServiceDC(); } if (logger.isTraceEnabled() && (end != 0)) logger.trace("PrivateService: cleanup() took {} ms [{}]", TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS), instance.SERVICE_ID); }
From source file:MSUmpire.DIA.DIAPack.java
public void GenerateRawMGF() throws IOException, Exception { if (RawMGFExist()) { return;/* w ww .j a v a2 s . c om*/ } Logger.getRootLogger().info("Extracting pseudo MS/MS spectra with raw intensity"); HashMap<Integer, ArrayList<PseudoMSMSProcessing>> ScanList = new HashMap<>(); HashMap<String, PseudoMSMSProcessing> UnfragScanList = new HashMap<>(); parameter.BoostComplementaryIon = false; ExecutorService executorPool = Executors.newFixedThreadPool(NoCPUs); for (LCMSPeakDIAMS2 DIAwindow : DIAWindows) { DIAwindow.ReadPeakCluster(); DIAwindow.ReadPrecursorFragmentClu2Cur(); DIAwindow.BuildFragmentMS1ranking(); DIAwindow.FilterByCriteria(); DIAwindow.BuildFragmentUnfragranking(); DIAwindow.FilterByCriteriaUnfrag(); for (PeakCluster ms1cluster : MS1FeatureMap.PeakClusters) { if (DIAwindow.DIA_MZ_Range.getX() <= ms1cluster.GetMaxMz() && DIAwindow.DIA_MZ_Range.getY() >= ms1cluster.TargetMz() && DIAwindow.FragmentsClu2Cur.containsKey(ms1cluster.Index)) { DIAwindow.ExtractFragmentForPeakCluser(ms1cluster); if (DIAwindow.Last_MZ_Range == null || DIAwindow.Last_MZ_Range.getY() < ms1cluster.TargetMz()) { PseudoMSMSProcessing mSMSProcessing = new PseudoMSMSProcessing(ms1cluster, parameter); executorPool.execute(mSMSProcessing); if (!ScanList.containsKey(ms1cluster.Index)) { ScanList.put(ms1cluster.Index, new ArrayList<PseudoMSMSProcessing>()); } ScanList.get(ms1cluster.Index).add(mSMSProcessing); } } } for (PeakCluster ms2cluster : DIAwindow.PeakClusters) { if (DIAwindow.DIA_MZ_Range.getX() <= ms2cluster.TargetMz() && DIAwindow.DIA_MZ_Range.getY() >= ms2cluster.TargetMz() && DIAwindow.UnFragIonClu2Cur.containsKey(ms2cluster.Index)) { DIAwindow.ExtractFragmentForUnfragPeakCluser(ms2cluster); PseudoMSMSProcessing mSMSProcessing = new PseudoMSMSProcessing(ms2cluster, parameter); executorPool.execute(mSMSProcessing); UnfragScanList.put(DIAwindow.WindowID + ";" + ms2cluster.Index, mSMSProcessing); } } DIAwindow.ClearAllPeaks(); System.gc(); Logger.getRootLogger() .info("(Memory usage:" + Math.round( (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576) + "MB)"); } executorPool.shutdown(); try { executorPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { Logger.getRootLogger().info("interrupted.."); } ReadScanNoMapping(); String mgffile = GetSkylineFolder() + GetForLibQ1Name() + ".mgf"; FileWriter mgfWriter = new FileWriter(mgffile, false); for (final int ScanNo : new java.util.TreeSet<>(ScanClusterMap_Q1.keySet())) { int ClusterIndex = ScanClusterMap_Q1.get(ScanNo); XYPointCollection Scan = new XYPointCollection(); PseudoMSMSProcessing mSMSProcessing = null; for (PseudoMSMSProcessing MS2Processing : ScanList.get(ClusterIndex)) { mSMSProcessing = MS2Processing; for (PrecursorFragmentPairEdge fragmentClusterUnit : MS2Processing.fragments) { Scan.AddPointKeepMaxIfValueExisted(fragmentClusterUnit.FragmentMz, fragmentClusterUnit.Intensity); } } StringBuilder mgfString = new StringBuilder(); mgfString.append("BEGIN IONS\n"); mgfString.append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n"); mgfString.append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n"); mgfString.append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n"); mgfString.append("TITLE=ClusterIndex:" + mSMSProcessing.Precursorcluster.Index + "\n"); for (int i = 0; i < Scan.PointCount(); i++) { mgfString.append(Scan.Data.get(i).getX()).append(" ").append(Scan.Data.get(i).getY()).append("\n"); } mgfString.append("END IONS\n\n"); mgfWriter.write(mgfString.toString()); } mgfWriter.close(); //////////////////////////////////////////////////////////////////////////////// String mgffile2 = GetSkylineFolder() + GetForLibQ2Name() + ".mgf"; FileWriter mgfWriter2 = new FileWriter(mgffile2, false); for (final int ScanNo : new java.util.TreeSet<>(ScanClusterMap_Q2.keySet())) { int ClusterIndex = ScanClusterMap_Q2.get(ScanNo); XYPointCollection Scan = new XYPointCollection(); PseudoMSMSProcessing mSMSProcessing = null; for (PseudoMSMSProcessing MS2Processing : ScanList.get(ClusterIndex)) { mSMSProcessing = MS2Processing; for (PrecursorFragmentPairEdge fragmentClusterUnit : MS2Processing.fragments) { Scan.AddPointKeepMaxIfValueExisted(fragmentClusterUnit.FragmentMz, fragmentClusterUnit.Intensity); } } StringBuilder mgfString = new StringBuilder(); mgfString.append("BEGIN IONS\n"); mgfString.append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n"); mgfString.append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n"); mgfString.append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n"); mgfString.append("TITLE=ClusterIndex:" + mSMSProcessing.Precursorcluster.Index + "\n"); for (int i = 0; i < Scan.PointCount(); i++) { mgfString.append(Scan.Data.get(i).getX()).append(" ").append(Scan.Data.get(i).getY()).append("\n"); } mgfString.append("END IONS\n\n"); mgfWriter2.write(mgfString.toString()); } mgfWriter2.close(); //////////////////////////////// String mgffile3 = GetSkylineFolder() + GetForLibQ3Name() + ".mgf"; FileWriter mgfWriter3 = new FileWriter(mgffile3, false); mzXMLParser Q3mzxml = new mzXMLParser(FilenameUtils.getFullPath(Filename) + GetQ3Name() + ".mzXML", parameter, SpectralDataType.DataType.DDA, null, NoCPUs); Q3mzxml.GetAllScanCollectionByMSLabel(false, true, false, false); for (final int ScanNo : new java.util.TreeSet<>(ScanClusterMap_Q3.keySet())) { String key = ScanClusterMap_Q3.get(ScanNo); XYPointCollection Scan = new XYPointCollection(); PseudoMSMSProcessing mSMSProcessing = UnfragScanList.get(key); for (PrecursorFragmentPairEdge fragmentClusterUnit : mSMSProcessing.fragments) { Scan.AddPointKeepMaxIfValueExisted(fragmentClusterUnit.FragmentMz, fragmentClusterUnit.Intensity); } StringBuilder mgfString = new StringBuilder(); mgfString.append("BEGIN IONS\n"); mgfString.append("PEPMASS=" + mSMSProcessing.Precursorcluster.TargetMz() + "\n"); mgfString.append("CHARGE=" + mSMSProcessing.Precursorcluster.Charge + "+\n"); mgfString.append("RTINSECONDS=" + mSMSProcessing.Precursorcluster.PeakHeightRT[0] * 60f + "\n"); mgfString.append("TITLE=ClusterIndex:" + mSMSProcessing.Precursorcluster.Index + "\n"); for (int i = 0; i < Scan.PointCount(); i++) { mgfString.append(Scan.Data.get(i).getX()).append(" ").append(Scan.Data.get(i).getY()).append("\n"); } mgfString.append("END IONS\n\n"); mgfWriter3.write(mgfString.toString()); } mgfWriter3.close(); }
From source file:com.sonicle.webtop.core.app.ServiceManager.java
public BasePublicService instantiatePublicService(String serviceId, PublicEnvironment environment) { ServiceDescriptor descr = getDescriptor(serviceId); if (!descr.hasPublicService()) throw new WTRuntimeException("Service [{}] has no public class", serviceId); BasePublicService instance = null;//from w w w .j a v a2 s.c o m try { instance = (BasePublicService) descr.getPublicServiceClass().newInstance(); } catch (Throwable t) { logger.error("PublicService: instantiation failure [{}]", t, descr.getManifest().getPublicServiceClassName()); return null; } instance.configure(environment); // Calls initialization method long start = 0, end = 0; logger.trace("PublicService: calling initialize() [{}]", serviceId); try { LoggerUtils.setContextDC(instance.SERVICE_ID); start = System.nanoTime(); instance.initialize(); end = System.nanoTime(); } catch (Throwable t) { logger.error("PublicService: initialize() throws errors [{}]", t, instance.getClass().getCanonicalName()); } finally { LoggerUtils.clearContextServiceDC(); } if (logger.isTraceEnabled() && (end != 0)) logger.trace("PublicService: initialize() took {} ms [{}]", TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS), serviceId); return instance; }
From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java
/** * Creates signature part of assertion. Uses digest method algorithm * corresponding to the signature algorithm used. * * @param assertion//from w w w .j a v a2 s . c om * @param signatureAlgorithm * @return */ private Element createSignatureAndSignAssertion(Assertion assertion, SignatureAlgorithm signatureAlgorithm, SignInfo signInfo) { assert assertion != null; assert signatureAlgorithm != null; XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); Element assertionElement = marshallAssertion(assertion); List<Transform> transforms = createTransforms(); Reference ref = createReference(transforms, assertionElement.getAttribute(Assertion.ID_ATTRIB_NAME), // here we use the digest method which is corresponding to the // signature algorithm used signatureAlgorithm.getDigestMethod().toString()); SignedInfo signedInfo = createSignedInfo(Collections.singletonList(ref), signatureAlgorithm); DOMSignContext signingContext = new DOMSignContext(signInfo.getPrivateKey(), assertionElement); signingContext.putNamespacePrefix(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, "ec"); signingContext.putNamespacePrefix(XMLSignature.XMLNS, "ds"); // signature should be the second section in the assertion - after issuer // here we are sure that the structure of assertion is as follows: // 1) issuer 2) subject // we get subject node and enter signature before it and the result is: // 1) issuer 2) signature 3) subject Node subjectNode = assertionElement.getChildNodes().item(1); signingContext.setNextSibling(subjectNode); log.debug("Set SigningContext into assertion (after Issuer or as a first child in the assertion DOM)."); final KeyInfo keyInfo = createKeyInfo(signInfo); XMLSignature xmlSignature = factory.newXMLSignature(signedInfo, keyInfo); try { final long start = System.nanoTime(); xmlSignature.sign(signingContext); perfLog.trace("'signature.sign' took {} ms.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)); } catch (MarshalException e) { throw new IllegalStateException(e); } catch (XMLSignatureException e) { throw new IllegalStateException(e); } log.debug("Created Signature and sign it."); return assertionElement; }
From source file:com.sonicle.webtop.core.app.ServiceManager.java
public void cleanupPublicService(BasePublicService instance) { long start = 0, end = 0; logger.trace("PublicService: calling cleanup() [{}]", instance.SERVICE_ID); try {//from w w w. j a v a 2 s.com LoggerUtils.setContextDC(instance.SERVICE_ID); start = System.nanoTime(); instance.cleanup(); end = System.nanoTime(); } catch (Throwable t) { logger.error("PublicService: cleanup() throws errors [{}]", t, instance.getClass().getCanonicalName()); } finally { LoggerUtils.clearContextServiceDC(); } if (logger.isTraceEnabled() && (end != 0)) logger.trace("PublicService: cleanup() took {} ms [{}]", TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS), instance.SERVICE_ID); }