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.vmware.identity.idm.server.IdentityManager.java
/** * Authenticates a principal using the password specified * * The principal is expected to be managed by one of the Identity providers * configured in the tenant./*from w ww . ja v a 2 s . c o m*/ * * @param tenantName Name of tenant. non-null non-empty, required * @param principal User principal to be authenticated. non-null non-empty, required * @param password Password. non-null non-empty, required * @return Normalized principal if successfully authenticated. * @throws IDMLoginException when authentication failed. * @throws PasswordExpiredException when authentication failed due to * expired password. * @throws UserAccountLockedException when authentication failed due to * locked user account. * @throws Exception */ private PrincipalId authenticate(String tenantName, String principal, String password) throws Exception { long startTime = System.nanoTime(); boolean authFailed = false; PrincipalId userPrincipal = null; IIdentityProvider provider = null; try { ValidateUtil.validateNotEmpty(tenantName, "Tenant name"); ServerUtils.validateNotEmptyUsername(principal); ValidateUtil.validateNotNull(password, "Password"); TenantInformation tenantInfo = findTenant(tenantName); if (tenantInfo == null) { throw new IDMLoginException("Access denied"); } userPrincipal = getUserPrincipal(tenantName, principal); if (userPrincipal == null) { throw new IDMLoginException(String.format("Invalid user principal '%s'.", principal)); } provider = tenantInfo.findProviderADAsFallBack(userPrincipal.getDomain()); if (provider == null) { throw new IDMLoginException("Access denied"); } String identityProviderName = provider.getName(); validateProviderAllowedAuthnTypes(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_PASSWORD, identityProviderName, tenantInfo); return provider.authenticate(userPrincipal, password); } catch (InvalidPrincipalException e) { authFailed = true; logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, "Failed to authenticate principal [{}]. Invalid principal.", (principal != null ? principal : "null")); throw e; } catch (Exception ex) { authFailed = true; logger.error(String.format("Failed to authenticate principal [%s] for tenant [%s]", principal != null ? principal : "null", tenantName != null ? tenantName : "null"), ex); if (provider != null && userPrincipal != null) { try { provider.checkUserAccountFlags(userPrincipal); } catch (UserAccountLockedException ex1) { logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, "Failed to authenticate principal [{}]. User account locked.", (principal != null ? principal : "null")); throw ex1; } catch (PasswordExpiredException ex1) { logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, "Failed to authenticate principal [{}]. User password expired.", (principal != null ? principal : "null")); throw ex1; } catch (Exception ex2) { logger.error(String.format("Failed to checkUserAccountFlags principal [%s] for tenant [%s]", principal != null ? principal : "null", tenantName != null ? tenantName : "null")); // we are ignoring this exception here, because we want to propagate the original // authenticate failure, and not this failure } } if (ex instanceof LoginException) { //Kerberos exception needs to be handled here Throwable t = ex.getCause(); if (t instanceof KrbException) { // get the Kerberos return code only when the cause if KrbException int returnCode = ((KrbException) t).returnCode(); switch (returnCode) { case ServerKrbUtils.KDC_ERR_CLIENT_REVOKED: { logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, "Failed to authenticate principal [{}]. User account locked.", (principal != null ? principal : "null")); throw new UserAccountLockedException(ex.getMessage()); } case ServerKrbUtils.KDC_ERR_KEY_EXPIRED: { logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, "Failed to authenticate principal [{}]. User password expired.", (principal != null ? principal : "null")); throw new PasswordExpiredException(ex.getMessage()); } default://no op for others break; } } } logger.error(VmEvent.USER_NAME_PWD_AUTH_FAILED, String.format("Failed to authenticate principal [%s]. %s", principal != null ? principal : "null", ex.getMessage()), ex); if (ex instanceof AccountLockedOutException) { throw new UserAccountLockedException(ex.getMessage()); } else if (ex instanceof AccountPasswordExpiredException) { throw new PasswordExpiredException(ex.getMessage()); } throw new IDMLoginException(ex.getMessage()); } finally { long delta = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); if (logger.isInfoEnabled()) { if (provider == null) { logger.info(String.format( "Authentication %s for user [%s] in tenant [%s] in [%d] milliseconds because the provider is not registered", authFailed ? "failed" : "succeeded", principal, tenantName, delta)); } else { logger.info(String.format( "Authentication %s for user [%s] in tenant [%s] in [%d] milliseconds with provider [%s] of type [%s]", authFailed ? "failed" : "succeeded", principal, tenantName, delta, provider.getName(), provider.getClass().getName())); } } IdmServer.getPerfDataSinkInstance() .addMeasurement(new PerfBucketKey(PerfMeasurementPoint.IDMAuthenticate, principal), delta); } }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
@Override public CompletableFuture<Void> execProcedure(String signature, String instance, Map<String, String> props) { CompletableFuture<Void> future = new CompletableFuture<>(); ProcedureDescription procDesc = ProtobufUtil.buildProcedureDescription(signature, instance, props); addListener(this.<Long>newMasterCaller() .action((controller, stub) -> this.<ExecProcedureRequest, ExecProcedureResponse, Long>call( controller, stub, ExecProcedureRequest.newBuilder().setProcedure(procDesc).build(), (s, c, req, done) -> s.execProcedure(c, req, done), resp -> resp.getExpectedTimeout())) .call(), (expectedTimeout, err) -> { if (err != null) { future.completeExceptionally(err); return; }// w ww . j a v a2s . co m TimerTask pollingTask = new TimerTask() { int tries = 0; long startTime = EnvironmentEdgeManager.currentTime(); long endTime = startTime + expectedTimeout; long maxPauseTime = expectedTimeout / maxAttempts; @Override public void run(Timeout timeout) throws Exception { if (EnvironmentEdgeManager.currentTime() < endTime) { addListener(isProcedureFinished(signature, instance, props), (done, err2) -> { if (err2 != null) { future.completeExceptionally(err2); return; } if (done) { future.complete(null); } else { // retry again after pauseTime. long pauseTime = ConnectionUtils .getPauseTime(TimeUnit.NANOSECONDS.toMillis(pauseNs), ++tries); pauseTime = Math.min(pauseTime, maxPauseTime); AsyncConnectionImpl.RETRY_TIMER.newTimeout(this, pauseTime, TimeUnit.MICROSECONDS); } }); } else { future.completeExceptionally( new IOException("Procedure '" + signature + " : " + instance + "' wasn't completed in expectedTime:" + expectedTimeout + " ms")); } } }; // Queue the polling task into RETRY_TIMER to poll procedure state asynchronously. AsyncConnectionImpl.RETRY_TIMER.newTimeout(pollingTask, 1, TimeUnit.MILLISECONDS); }); return future; }
From source file:com.vmware.identity.idm.server.IdentityManager.java
/** * TLS Client Certificate (or smartcard) authentication. * * This function does the following Certificate path validation, revocation * check Subject validation OID filtering * * @param tenantName/*from ww w . j av a2s . c om*/ * @param tlsCertChain * certificate chain may or may not provide full client cert * chain. * @return principal matched * @throws IDMLoginException * certificate not provided or can not find a matching user in * directory * @throws IdmCertificateRevokedException * certificate revoked * @throws InvalidArgumentException * parameter was incorrectly set * @throws CertificateRevocationCheckException * revocation check fails to determine the certificate status * @throws IDMException * any other exceptions */ private PrincipalId authenticate(String tenantName, X509Certificate[] tlsCertChain) throws IDMLoginException, CertificateRevocationCheckException, InvalidArgumentException, IdmCertificateRevokedException, IDMException { TenantInformation info; try { info = findTenant(tenantName); } catch (Exception e) { throw new IDMLoginException("Error in retrieve tenantInfo"); } if (tlsCertChain == null || tlsCertChain.length < 1) { logger.error("Certificate chain is empty or null"); throw new IDMLoginException("Certificate chain is empty or null"); } if (logger.isDebugEnabled()) { for (int i = 0; i < tlsCertChain.length; i++) { logger.debug("Client Certificate [" + i + "] = " + tlsCertChain[i].toString()); } } String subjectDn = tlsCertChain[0].getSubjectDN() != null ? tlsCertChain[0].getSubjectDN().toString() : ""; IIdmAuthStatRecorder recorder = PerformanceMonitorFactory.createIdmAuthStatRecorderInstance(tenantName, "CertificateAuthentication", "IDM", 0, IIdmAuthStat.ActivityKind.AUTHENTICATE, IIdmAuthStat.EventLevel.INFO, subjectDn); recorder.start(); AuthnPolicy aPolicy = info.getAuthnPolicy(); Validate.notNull(aPolicy, "AuthnPolicy can not be null."); Validate.isTrue(aPolicy.IsTLSClientCertAuthnEnabled(), "TLSClient authn is not enabled."); ClientCertPolicy certPolicy = aPolicy.getClientCertPolicy(); Validate.notNull(certPolicy, "Client Certificate Policy can not be null."); ValidateUtil.validateNotEmpty(tenantName, "Tenant name"); IdmClientCertificateValidator certValidator = new IdmClientCertificateValidator(certPolicy, tenantName); Map<String, String> authStatsExtension = new HashMap<String, String>(); recorder.add(authStatsExtension); String clusterID; try { clusterID = this.getClusterId(); } catch (Exception e1) { throw new IDMException("Failed to retrieve PSC cluster ID."); } certValidator.validateCertificatePath(tlsCertChain[0], clusterID, authStatsExtension); long startTime = System.nanoTime(); String upn = certValidator.extractUPN(tlsCertChain[0]); //Validate allowed authentication type on provider IIdentityProvider provider = null; try { PrincipalId userPrincipal = getUserPrincipal(tenantName, upn); provider = info.findProviderADAsFallBack(userPrincipal.getDomain()); } catch (Exception e) { throw new IDMException("Failed to retrieve details of identity provider with domain :" + subjectDn); } if (provider != null) { validateProviderAllowedAuthnTypes(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_TLS_CERTIFICATE, provider.getName(), info); } String[] parts = upn.split("@"); PrincipalId principalID; if (parts.length == 2) { principalID = new PrincipalId(parts[0], parts[1]); try { if (!this.IsActive(tenantName, principalID)) { logger.error("The user is not found or inactive:" + principalID.getUPN()); throw new IDMLoginException( "The user owning this certificate is not found or inactive. User UPN: " + principalID.getUPN()); } logger.info("Successfully validated subject of the client certificate : " + principalID.getUPN()); } catch (Exception e) { logger.error( "Failed to determine the status of principal with candicate UPN:" + principalID.getUPN()); throw new IDMLoginException("Unable to find user with UPN: " + principalID.getUPN()); } } else { logger.error(upn + " is in illegal UPN format"); throw new IDMLoginException("Illegal UPN format: " + upn); } authStatsExtension.put("SearchUserByCertificateUpn", String.format("%d Ms", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime))); recorder.end(); // authentication is successful return principalID; }
From source file:com.vmware.identity.idm.server.IdentityManager.java
/** * authenticate with secure ID//from w w w . j a v a 2s. co m * * @param tenantName * @param principal * @param passcode * @return * @throw IDMLoginExceptin if credential is denied * @throw IDMRsaSecurIDNewPinException if user need to setup new pin. * @throws IDMException all other errors. */ private RSAAMResult authenticateRsaSecurId(String tenantName, String sessionId, String userName, String passcode) throws IDMException { long startTime = System.nanoTime(); boolean authFailed = false; RSAAMResult authResult = null; logger.debug("Authenticating with RSA securID .."); try { ValidateUtil.validateNotEmpty(tenantName, "Tenant name"); ValidateUtil.validateNotNull(userName, "User Principal"); TenantInformation info = findTenant(tenantName); AuthnPolicy aPolicy = info.getAuthnPolicy(); Validate.notNull(aPolicy, "AuthnPolicy can not be null."); Validate.isTrue(aPolicy.IsRsaSecureIDAuthnEnabled(), "SecureID authentication is not turned on for this tenant."); RSAAgentConfig rsaConfig = aPolicy.get_rsaAgentConfig(); Validate.notNull(rsaConfig, "RSAAgentConfig is not defined"); HashMap<String, String> userIDAttrMap = rsaConfig.get_idsUserIDAttributeMap(); // we should not need to create api all the time; but different tenant should have different api AuthenticationSessionFactory api = null; String[] userInfo = separateUserIDAndDomain(userName); IIdentityProvider provider = info.findProviderADAsFallBack(userInfo[1]); if (null == provider) { throw new IDMLoginException( String.format("Identity source was not defined for user: %s.", userName)); } validateProviderAllowedAuthnTypes(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_RSA_SECUREID, provider.getName(), info); api = this._rsaSessionFactoryCache.getAuthnFactory(info); String userID = extractRsaUserID(info, userName, userIDAttrMap); AuthenticationSession session = null; String cachedSessionId = sessionId; PrincipalId pId = getPrincipalIDFromUserName(info, userName, userIDAttrMap); try { // Retrieve session if this it is provided if (cachedSessionId != null) { session = IdentityManager._rsaSessionCache.getSession(tenantName, cachedSessionId); } // generate a rsa session if not found in rsa session cache if (session == null) { logger.debug("Using new AuthSession ..."); session = api.createSession(); String newSessionId = createSessionId(); int status = session.authenticate(userID, new AuthenticationSecret(passcode)).getStatusCode(); if (status == AuthenticationResult.NEXT_CODE_REQUIRED) { IdentityManager._rsaSessionCache.addSession(tenantName, newSessionId, session); } authResult = afterProcessRSAStatus(status, newSessionId, userName, pId); } else { logger.debug("Using cached AuthSession, in second leg of NEXT_CODE_REQUIRED mode ..."); //It must be in nextcode mode if the session is found int prevStatus = session.getAuthenticationStatus().getStatusCode(); if (prevStatus != AuthenticationResult.NEXT_CODE_REQUIRED) { throw new IDMLoginException( String.format("Unexpected status in a cached rsa session: %s.", prevStatus)); } int status = session.nextAuthenticationStep(new AuthenticationSecret(passcode)).getStatusCode(); authResult = afterProcessRSAStatus(status, cachedSessionId, userName, pId); if (status != AuthenticationResult.NEXT_CODE_REQUIRED) { IdentityManager._rsaSessionCache.removeSession(tenantName, cachedSessionId); } } } finally { if (session.getAuthenticationStatus().getStatusCode() != AuthenticationResult.NEXT_CODE_REQUIRED) { session.closeSession(); } } } catch (IDMLoginException ex) { authFailed = true; throw ex; } catch (IDMException ex) { // don't wrap it. authFailed = true; throw ex; } catch (Exception ex) { authFailed = true; logger.error(String.format("Failed to authenticate principal [%s] by passcode", userName != null ? userName : "null"), ex); throw new IDMException(ex.getMessage()); } finally { long delta = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); if (logger.isInfoEnabled()) { logger.info(String.format( "Authentication %s for user [%s] in tenant [%s] in [%d] milliseconds with rsa secureID", authFailed ? "failed" : "succeeded or entered \"NEXT_CODE_REQUIRED\" mode", userName, tenantName, delta)); } IdmServer.getPerfDataSinkInstance() .addMeasurement(new PerfBucketKey(PerfMeasurementPoint.IDMAuthenticate, userName), delta); } return authResult; }
From source file:com.vmware.identity.idm.server.IdentityManager.java
private Collection<AttributeValuePair> getAttributeValues(String tenantName, PrincipalId principal, Collection<Attribute> attributes) throws Exception { try {//from w ww .ja va 2 s. co m ValidateUtil.validateNotEmpty(tenantName, "Tenant name"); ValidateUtil.validateNotNull(principal, "User Principal"); ValidateUtil.validateNotNull(attributes, "Attributes"); ValidateUtil.validatePositiveNumber(attributes.size(), "Attribute count"); TenantInformation tenantInfo = findTenant(tenantName); ServerUtils.validateNotNullTenant(tenantInfo, tenantName); IIdentityProvider provider = tenantInfo.findProviderADAsFallBack(principal.getDomain()); ServerUtils.validateNotNullIdp(provider, tenantName, principal.getDomain()); Collection<AttributeValuePair> attributeValues = new HashSet<AttributeValuePair>(); long startTime = System.nanoTime(); String samlGroupAttrName = tenantInfo.findSystemProvider().getMappingSamlAttributeForGroupMembership(); ISystemDomainIdentityProvider systemProvider = tenantInfo.findSystemProvider(); Collection<AttributeValuePair> retAttrs = provider.getAttributes(principal, attributes); AttributeValuePair sids = null; AttributeValuePair groupNames = null; for (AttributeValuePair attr : retAttrs) { if (attr.getAttrDefinition().getName().equalsIgnoreCase(INTERNAL_ATTR_GROUP_OBJECTIDS)) { sids = attr; } else if (attr.getAttrDefinition().getName().equalsIgnoreCase(samlGroupAttrName)) { groupNames = attr; } else { attributeValues.add(attr); } } if (!(provider instanceof ISystemDomainIdentityProvider)) { List<String> groupsInSp = new ArrayList<String>(); if ((sids != null) && (sids.getValues() != null) && (!sids.getValues().isEmpty())) { try { groupsInSp = systemProvider.findGroupsForFsps(sids.getValues()); } catch (Exception e) { logger.trace(String.format( "Failed to determine FSP for principal [%s] or any of its groups in tenant [%s]", principal != null ? principal.getUPN() : "null", tenantName)); } if (groupNames != null && groupsInSp != null && groupsInSp.size() > 0) { for (String groupName : groupsInSp) { groupNames.getValues().add(groupName); } } } } if (groupNames != null) { attributeValues.add(groupNames); } addEveryoneGroupTo(attributeValues, samlGroupAttrName, systemProvider); //only measure time of successful results IdmServer.getPerfDataSinkInstance().addMeasurement( new PerfBucketKey(PerfMeasurementPoint.IDMGetAttributeValues, principal.getDomain()), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)); return attributeValues; } catch (Exception ex) { logger.error(String.format("Failed to get attributes for principal [%s@%s] in tenant [%s]", principal != null ? principal.getName() : "null", principal != null ? principal.getDomain() : "null", tenantName)); throw ex; } }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
private void getProcedureResult(long procId, CompletableFuture<Void> future, int retries) { addListener(/*from w ww . ja v a 2 s . c om*/ 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(), (response, error) -> { if (error != null) { LOG.warn("failed to get the procedure result procId={}", procId, ConnectionUtils.translateException(error)); retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1), ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS); return; } if (response.getState() == GetProcedureResultResponse.State.RUNNING) { retryTimer.newTimeout(t -> getProcedureResult(procId, future, retries + 1), ConnectionUtils.getPauseTime(pauseNs, retries), TimeUnit.NANOSECONDS); return; } if (response.hasException()) { IOException ioe = ForeignExceptionUtil.toIOException(response.getException()); future.completeExceptionally(ioe); } else { future.complete(null); } }); }
From source file:org.apache.hadoop.hbase.client.RawAsyncHBaseAdmin.java
private <T> ServerRequestCallerBuilder<T> newServerCaller() { return this.connection.callerFactory.<T>serverRequest().rpcTimeout(rpcTimeoutNs, TimeUnit.NANOSECONDS) .operationTimeout(operationTimeoutNs, TimeUnit.NANOSECONDS).pause(pauseNs, TimeUnit.NANOSECONDS) .pauseForCQTBE(pauseForCQTBENs, TimeUnit.NANOSECONDS).maxAttempts(maxAttempts) .startLogErrorsCnt(startLogErrorsCnt); }
From source file:com.vmware.identity.idm.server.IdentityManager.java
/** * Finds the set of groups that contain the specified security principal in * the tenant.//from ww w. jav a 2 s.com * * The principal whose immediate parents are desired, may be a user or group * * @param tenantName Name of tenant, required.non-null non-empty * @param principalId Security principal id, required, non-null. * @return Set of immediate parent groups found. * @throws IDMException * @throws NoSuchTenantException - if no such tenant exist * @throws NoSuchIdpException - system tenant is not set up. * @throws InvalidArgumentException -- if the tenant name is null or empty * @throws InValidPrincipleException - principal ID is invalid. * @throws IDMException - wrapping exception for any other exceptions * from down the stack. */ private Set<Group> findDirectParentGroups(String tenantName, PrincipalId principalId) throws Exception { try { ValidateUtil.validateNotEmpty(tenantName, "Tenant name"); ValidateUtil.validateNotNull(principalId, "User principal"); long startedTime = System.nanoTime(); TenantInformation tenantInfo = findTenant(tenantName); ServerUtils.validateNotNullTenant(tenantInfo, tenantName); // (1) Find from system domain ISystemDomainIdentityProvider systemProvider = tenantInfo.findSystemProvider(); ServerUtils.validateNotNullSystemIdp(systemProvider, tenantName); Set<Group> groups = new HashSet<Group>(); PrincipalGroupLookupInfo idpGroups = null; List<Group> sysGroups = null; String fspId = null; // direct parent groups is a union of: // - set of direct parent groups from specific identity source provider // - set of direct parent groups from system provider for specified principal's object id // [if prinicipal's identity source != system provider] IIdentityProvider provider = tenantInfo.findProviderADAsFallBack(principalId.getDomain()); // TODO: external registered Idp support needs to be re-considered for more straightforward handling... if (provider == null) // this could be external idp registered user { fspId = getRegisteredExternalIDPUserObjectId(tenantName, principalId); } else { try { idpGroups = provider.findDirectParentGroups(principalId); if ((idpGroups != null) && (provider.getName().equalsIgnoreCase(systemProvider.getName()) == false)) { fspId = idpGroups.getPrincipalObjectId(); } } catch (InvalidPrincipalException ex) { // this could be external idp registered user fspId = getRegisteredExternalIDPUserObjectId(tenantName, principalId); } } if (ServerUtils.isNullOrEmpty(fspId) == false) { try { sysGroups = systemProvider.findGroupObjectsForFsps(Collections.<String>singletonList(fspId)); } catch (InvalidPrincipalException ex) { logger.trace(String.format("Failed to find principal [%s@%s] as FSP principal in tenant [%s]", principalId != null ? principalId.getName() : "null", principalId != null ? principalId.getDomain() : "null", tenantName)); sysGroups = null; } } if ((idpGroups != null) && (idpGroups.getGroups() != null) && (idpGroups.getGroups().isEmpty() == false)) { groups.addAll(idpGroups.getGroups()); } if (sysGroups != null && !sysGroups.isEmpty()) { groups.addAll(sysGroups); } // TODO: ideally everyone group should be added within system domain provider groups.add(systemProvider.getEveryoneGroup()); IdmServer.getPerfDataSinkInstance().addMeasurement( new PerfBucketKey(PerfMeasurementPoint.IDMFindDirectParentGroups, principalId.getDomain()), TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedTime)); return groups; } catch (Exception ex) { logger.error(String.format("Failed to find direct parent groups of principal [%s@%s] in tenant [%s]", principalId != null ? principalId.getName() : "null", principalId != null ? principalId.getDomain() : "null", tenantName)); throw ex; } }
From source file:org.apache.hadoop.hive.conf.HiveConf.java
public static TimeUnit unitFor(String unit, TimeUnit defaultUnit) { unit = unit.trim().toLowerCase();//from w ww .j av a 2s . c om if (unit.isEmpty() || unit.equals("l")) { if (defaultUnit == null) { throw new IllegalArgumentException("Time unit is not specified"); } return defaultUnit; } else if (unit.equals("d") || unit.startsWith("day")) { return TimeUnit.DAYS; } else if (unit.equals("h") || unit.startsWith("hour")) { return TimeUnit.HOURS; } else if (unit.equals("m") || unit.startsWith("min")) { return TimeUnit.MINUTES; } else if (unit.equals("s") || unit.startsWith("sec")) { return TimeUnit.SECONDS; } else if (unit.equals("ms") || unit.startsWith("msec")) { return TimeUnit.MILLISECONDS; } else if (unit.equals("us") || unit.startsWith("usec")) { return TimeUnit.MICROSECONDS; } else if (unit.equals("ns") || unit.startsWith("nsec")) { return TimeUnit.NANOSECONDS; } throw new IllegalArgumentException("Invalid time unit " + unit); }