List of usage examples for java.util UUID nameUUIDFromBytes
public static UUID nameUUIDFromBytes(byte[] name)
From source file:tigase.xmpp.impl.JabberIqRegister.java
/**{@inheritDoc} * * <br><br>/* w w w. j av a2 s . c o m*/ * * TODO: Implement registration form configurable and loading * all the fields from the registration form TODO: rewrite the * plugin using the XMPPProcessorAbstract API */ @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (log.isLoggable(Level.FINEST)) { log.finest("Processing packet: " + packet.toString()); } if (session == null) { if (log.isLoggable(Level.FINEST)) { log.finest("Session is null, ignoring"); } return; } // end of if (session == null) BareJID id = session.getDomainAsJID().getBareJID(); if (packet.getStanzaTo() != null) { id = packet.getStanzaTo().getBareJID(); } try { // I think it does not make sense to check the 'to', just the // connection // ID // if ((id.equals(session.getDomain()) || // id.equals(session.getUserId().toString())) // && packet.getFrom().equals(session.getConnectionId())) { // Wrong thinking. The user may send an request from his own account // to register with a transport or any other service, then the // connection // ID matches the session id but this is still not a request to the // local // server. The TO address must be checked too..... // if (packet.getPacketFrom().equals(session.getConnectionId())) { if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId()) && (!session.isAuthorized() || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) { // We want to allow password change but not user registration if // registration is disabled. The only way to tell apart // registration // from password change is to check whether the user is // authenticated. // For authenticated user the request means password change, // otherwise // registration attempt. // Account deregistration is also called under authenticated // session, so // it should be blocked here if registration for domain is // disabled. // Assuming if user cannot register account he cannot also // deregister account Element request = packet.getElement(); boolean remove = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH) != null; if (!session.isAuthorized() || remove) { if (!isRegistrationAllowedForConnection(packet.getFrom())) { results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet, "Registration is not allowed for this connection.", true)); ++statsInvalidRegistrations; return; } if (!session.getDomain().isRegisterEnabled()) { results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet, "Registration is not allowed for this domain.", true)); ++statsInvalidRegistrations; return; } } Authorization result = Authorization.NOT_AUTHORIZED; StanzaType type = packet.getType(); switch (type) { case set: // Is it registration cancel request? Element elem = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH); if (elem != null) { // Yes this is registration cancel request // According to JEP-0077 there must not be any // more subelements apart from <remove/> elem = request.findChildStaticStr(Iq.IQ_QUERY_PATH); if (elem.getChildren().size() > 1) { result = Authorization.BAD_REQUEST; } else { try { result = session.unregister(packet.getStanzaFrom().toString()); Packet ok_result = packet.okResult((String) null, 0); // We have to set SYSTEM priority for the packet // here, // otherwise the network connection is closed // before the // client received a response ok_result.setPriority(Priority.SYSTEM); results.offer(ok_result); Packet close_cmd = Command.CLOSE.getPacket(session.getSMComponentId(), session.getConnectionId(), StanzaType.set, session.nextStanzaId()); close_cmd.setPacketTo(session.getConnectionId()); close_cmd.setPriority(Priority.LOWEST); results.offer(close_cmd); } catch (NotAuthorizedException e) { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must authorize session first.", true)); } // end of try-catch } } else { String user_name; String password; String email; if (signedFormRequired) { final String expectedToken = UUID .nameUUIDFromBytes( (session.getConnectionId() + "|" + session.getSessionId()).getBytes()) .toString(); FormSignatureVerifier verifier = new FormSignatureVerifier(oauthConsumerKey, oauthConsumerSecret); Element queryEl = request.getChild("query", "jabber:iq:register"); Element formEl = queryEl == null ? null : queryEl.getChild("x", "jabber:x:data"); if (formEl == null) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Use Signed Registration Form", true)); ++statsInvalidRegistrations; return; } Form form = new Form(formEl); if (!expectedToken.equals(form.getAsString("oauth_token"))) { log.finest("Received oauth_token is different that sent one."); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Unknown oauth_token", true)); ++statsInvalidRegistrations; return; } if (!oauthConsumerKey.equals(form.getAsString("oauth_consumer_key"))) { log.finest("Unknown oauth_consumer_key"); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Unknown oauth_consumer_key", true)); ++statsInvalidRegistrations; return; } try { long timestamp = verifier.verify(packet.getStanzaTo(), form); user_name = form.getAsString("username"); password = form.getAsString("password"); email = form.getAsString("email"); } catch (FormSignerException e) { log.fine("Form Signature Validation Problem: " + e.getMessage()); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Invalid form signature", true)); ++statsInvalidRegistrations; return; } } else { // No, so assuming this is registration of a new // user or change registration details for existing // user user_name = request.getChildCDataStaticStr(IQ_QUERY_USERNAME_PATH); password = request.getChildCDataStaticStr(IQ_QUERY_PASSWORD_PATH); email = request.getChildCDataStaticStr(IQ_QUERY_EMAIL_PATH); } String pass_enc = null; if (null != password) { pass_enc = XMLUtils.unescape(password); } Map<String, String> reg_params = null; if ((email != null) && !email.trim().isEmpty()) { reg_params = new LinkedHashMap<String, String>(); reg_params.put("email", email); } result = session.register(user_name, pass_enc, reg_params); if (result == Authorization.AUTHORIZED) { results.offer(result.getResponseMessage(packet, null, false)); } else { ++statsInvalidRegistrations; results.offer( result.getResponseMessage(packet, "Unsuccessful registration attempt", true)); } } break; case get: { if (signedFormRequired) { results.offer(packet.okResult(prepareRegistrationForm(session), 0)); } else results.offer(packet.okResult( "<instructions>" + "Choose a user name and password for use with this service." + "Please provide also your e-mail address." + "</instructions>" + "<username/>" + "<password/>" + "<email/>", 1)); break; } case result: // It might be a registration request from transport for // example... Packet pack_res = packet.copyElementOnly(); pack_res.setPacketTo(session.getConnectionId()); results.offer(pack_res); break; default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true)); break; } // end of switch (type) } else { if (session.isUserId(id)) { // It might be a registration request from transport for // example... Packet pack_res = packet.copyElementOnly(); pack_res.setPacketTo(session.getConnectionId()); results.offer(pack_res); } else { results.offer(packet.copyElementOnly()); } } } catch (TigaseStringprepException ex) { results.offer(Authorization.JID_MALFORMED.getResponseMessage(packet, "Incorrect user name, stringprep processing failed.", true)); } catch (NotAuthorizedException e) { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized to change registration settings.\n" + e.getMessage(), true)); } catch (TigaseDBException e) { log.warning("Database problem: " + e); results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet, "Database access problem, please contact administrator.", true)); } // end of try-catch }
From source file:org.apache.nifi.registry.flow.mapping.NiFiRegistryFlowMapper.java
private String getId(final Optional<String> currentVersionedId, final String componentId) { final String versionedId; if (currentVersionedId.isPresent()) { versionedId = currentVersionedId.get(); } else {//from www. j a va 2s. c om versionedId = UUID.nameUUIDFromBytes(componentId.getBytes(StandardCharsets.UTF_8)).toString(); } versionedComponentIds.put(componentId, versionedId); return versionedId; }
From source file:org.kitodo.dataformat.access.DivXmlElementAccess.java
/** * Adds a meta-data section to an administrative meta-data section, if there * is one. This function deduplicates fourfold existing function for four * different meta-data sections.// www . jav a2 s . c o m * * @param optionalMdSec * perhaps existing meta-data section to be added if it exists * @param mdSecType * the type of the mdSec, used in ID generation * @param mdSecTypeGetter * the getter via which the meta-data section can be added to the * administrative meta-data section * @param amdSec * administrative meta-data section to which the meta-data * section should be added, if any * @param div * div where ADMID references must be added to the generated * meta-data sections * @return whether something has been added to the administrative meta-data * section */ private static boolean addMdSec(Optional<MdSecType> optionalMdSec, String metsReferrerId, MdSec mdSecType, Function<AmdSecType, List<MdSecType>> mdSecTypeGetter, AmdSecType amdSec, DivType div) { if (!optionalMdSec.isPresent()) { return false; } else { MdSecType mdSec = optionalMdSec.get(); String name = metsReferrerId + ':' + mdSecType.toString(); mdSec.setID(UUID.nameUUIDFromBytes(name.getBytes(StandardCharsets.UTF_8)).toString()); mdSecTypeGetter.apply(amdSec).add(mdSec); div.getADMID().add(mdSec); return true; } }
From source file:com.orange.clara.cloud.servicedbdumper.dbdumper.DatabaseRefManager.java
protected String generateDatabaseRefName(String srcUrl) { UUID dbRefName = UUID.nameUUIDFromBytes(srcUrl.getBytes()); return dbRefName.toString(); }
From source file:org.apache.usergrid.persistence.cassandra.ConnectionRefImpl.java
public static UUID getId(EntityRef connectingEntity, ConnectedEntityRef connectedEntity, ConnectedEntityRef... pairedConnections) { UUID uuid = null;// w ww. j a va2s .c om try { if (connectionsNull(pairedConnections) && connectionsNull(connectedEntity)) { return connectingEntity.getUuid(); } ByteArrayOutputStream byteStream = new ByteArrayOutputStream(16 + (32 * pairedConnections.length)); byteStream.write(uuidToBytesNullOk(connectingEntity.getUuid())); for (ConnectedEntityRef connection : pairedConnections) { String connectionType = connection.getConnectionType(); UUID connectedEntityID = connection.getUuid(); byteStream.write(ascii(StringUtils.lowerCase(connectionType))); byteStream.write(uuidToBytesNullOk(connectedEntityID)); } String connectionType = connectedEntity.getConnectionType(); if (connectionType == null) { connectionType = NULL_ENTITY_TYPE; } UUID connectedEntityID = connectedEntity.getUuid(); byteStream.write(ascii(StringUtils.lowerCase(connectionType))); byteStream.write(uuidToBytesNullOk(connectedEntityID)); byte[] raw_id = byteStream.toByteArray(); // logger.info("raw connection index id: " + // Hex.encodeHexString(raw_id)); uuid = UUID.nameUUIDFromBytes(raw_id); // logger.info("connection index uuid: " + uuid); } catch (IOException e) { logger.error("Unable to create connection UUID", e); } return uuid; }
From source file:com.atlassian.jira.applinks.JiraAppLinksHostApplication.java
@Override public ApplicationId getId() { String serverId = jiraLicenseService.getServerId(); try {/* ww w . j av a 2 s. c om*/ return new ApplicationId(UUID.nameUUIDFromBytes(serverId.getBytes("UTF-8")).toString()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("UTF-8 is not supported. WTF?", e); } }
From source file:org.lilyproject.util.repo.SystemFields.java
public static synchronized SystemFields getInstance(TypeManager typeManager, IdGenerator idGenerator) { if (INSTANCE == null) { Map<QName, SystemField> fieldsByName = new HashMap<QName, SystemField>(); Map<SchemaId, SystemField> fieldsById = new HashMap<SchemaId, SystemField>(); for (SystemField field : fields) { String stringId = "{" + NS + "}" + field.name; UUID id;/*from w w w. j a va 2s.c o m*/ try { // Normally, the bytes should be prefixed with the UUID of the namespace to which the name // belongs, but for our purpose this is a good enough. id = UUID.nameUUIDFromBytes(stringId.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); // rare enough } SchemaId schemaId = idGenerator.getSchemaId(id); ValueType valueType; try { valueType = field.multiValue ? typeManager.getValueType("LIST<" + field.type + ">") : typeManager.getValueType(field.type); } catch (RepositoryException e) { throw new RuntimeException(e); // unlikely to occur } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); // unlikely to occur } FieldType fieldType = typeManager.newFieldType(valueType, new QName(NS, field.name), Scope.NON_VERSIONED); fieldType.setId(schemaId); field.setFieldType(fieldType); fieldsByName.put(fieldType.getName(), field); fieldsById.put(fieldType.getId(), field); } INSTANCE = new SystemFields(fieldsByName, fieldsById); } return INSTANCE; }
From source file:tigase.hinest.HinestRegister.java
/**{@inheritDoc} * * <br><br>//from ww w. j a va2 s . co m * * TODO: Implement registration form configurable and loading * all the fields from the registration form TODO: rewrite the * plugin using the XMPPProcessorAbstract API */ @Override public void process(Packet packet, XMPPResourceConnection session, NonAuthUserRepository repo, Queue<Packet> results, Map<String, Object> settings) throws XMPPException { if (log.isLoggable(Level.FINEST)) { log.finest("Processing packet: " + packet.toString()); } if (!initConfig && settings != null) { if (settings.containsKey(DEV_DOMAIN_KEY)) { DEV_DOMAIN = (String) settings.get(DEV_DOMAIN_KEY); } if (settings.containsKey(USR_DOMAIN_KEY)) { USR_DOMAIN = (String) settings.get(USR_DOMAIN_KEY); } } //linlinno if (checkInfoList == null) { checkInfoList = new CheckInfoList(); } else { if (checkInfoList.getSize() > MAX_CHECKINFOLIST_SIZE) { checkInfoList.deleteExpiredNode( System.currentTimeMillis() - 1000 * 60 * CheckCodeTool.CHECK_CODE_TIMEOUT); } } if (session == null) { if (log.isLoggable(Level.FINEST)) { log.finest("Session is null, ignoring"); } return; } // end of if (session == null) BareJID id = session.getDomainAsJID().getBareJID(); if (packet.getStanzaTo() != null) { id = packet.getStanzaTo().getBareJID(); } try { // I think it does not make sense to check the 'to', just the // connection // ID // if ((id.equals(session.getDomain()) || // id.equals(session.getUserId().toString())) // && packet.getFrom().equals(session.getConnectionId())) { // Wrong thinking. The user may send an request from his own account // to register with a transport or any other service, then the // connection // ID matches the session id but this is still not a request to the // local // server. The TO address must be checked too..... // if (packet.getPacketFrom().equals(session.getConnectionId())) { if ((packet.getPacketFrom() != null) && packet.getPacketFrom().equals(session.getConnectionId()) && (!session.isAuthorized() || (session.isUserId(id) || session.isLocalDomain(id.toString(), false)))) { // We want to allow password change but not user registration if // registration is disabled. The only way to tell apart // registration // from password change is to check whether the user is // authenticated. // For authenticated user the request means password change, // otherwise // registration attempt. // Account deregistration is also called under authenticated // session, so // it should be blocked here if registration for domain is // disabled. // Assuming if user cannot register account he cannot also // deregister account Element request = packet.getElement(); boolean remove = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH) != null; if (!session.isAuthorized() || remove) { if (!isRegistrationAllowedForConnection(packet.getFrom())) { results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet, "Registration is not allowed for this connection.", true)); ++statsInvalidRegistrations; return; } if (!session.getDomain().isRegisterEnabled()) { results.offer(Authorization.NOT_ALLOWED.getResponseMessage(packet, "Registration is not allowed for this domain.", true)); ++statsInvalidRegistrations; return; } } Authorization result = Authorization.NOT_AUTHORIZED; StanzaType type = packet.getType(); switch (type) { case set: // Is it registration cancel request? Element elem = request.findChildStaticStr(IQ_QUERY_REMOVE_PATH); if (elem != null) { // Yes this is registration cancel request // According to JEP-0077 there must not be any // more subelements apart from <remove/> elem = request.findChildStaticStr(Iq.IQ_QUERY_PATH); if (elem.getChildren().size() > 1) { result = Authorization.BAD_REQUEST; } else { try { result = session.unregister(packet.getStanzaFrom().toString()); Packet ok_result = packet.okResult((String) null, 0); // We have to set SYSTEM priority for the packet // here, // otherwise the network connection is closed // before the // client received a response ok_result.setPriority(Priority.SYSTEM); results.offer(ok_result); Packet close_cmd = Command.CLOSE.getPacket(session.getSMComponentId(), session.getConnectionId(), StanzaType.set, session.nextStanzaId()); close_cmd.setPacketTo(session.getConnectionId()); close_cmd.setPriority(Priority.LOWEST); results.offer(close_cmd); } catch (NotAuthorizedException e) { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You must authorize session first.", true)); } // end of try-catch } } else { String user_name; String password; String email; String phone;//linlinno String check_code; if (signedFormRequired) { final String expectedToken = UUID .nameUUIDFromBytes( (session.getConnectionId() + "|" + session.getSessionId()).getBytes()) .toString(); FormSignatureVerifier verifier = new FormSignatureVerifier(oauthConsumerKey, oauthConsumerSecret); Element queryEl = request.getChild("query", "jabber:iq:register"); Element formEl = queryEl == null ? null : queryEl.getChild("x", "jabber:x:data"); if (formEl == null) { results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Use Signed Registration Form", true)); ++statsInvalidRegistrations; return; } Form form = new Form(formEl); if (!expectedToken.equals(form.getAsString("oauth_token"))) { log.finest("Received oauth_token is different that sent one."); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Unknown oauth_token", true)); ++statsInvalidRegistrations; return; } if (!oauthConsumerKey.equals(form.getAsString("oauth_consumer_key"))) { log.finest("Unknown oauth_consumer_key"); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Unknown oauth_consumer_key", true)); ++statsInvalidRegistrations; return; } try { long timestamp = verifier.verify(packet.getStanzaTo(), form); user_name = form.getAsString("username"); password = form.getAsString("password"); email = form.getAsString("email"); phone = form.getAsString("phone");//linlinno check_code = form.getAsString("checkcode"); } catch (FormSignerException e) { log.fine("Form Signature Validation Problem: " + e.getMessage()); results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Invalid form signature", true)); ++statsInvalidRegistrations; return; } } else { // No, so assuming this is registration of a new // user or change registration details for existing // user user_name = request.getChildCDataStaticStr(IQ_QUERY_USERNAME_PATH); password = request.getChildCDataStaticStr(IQ_QUERY_PASSWORD_PATH); email = request.getChildCDataStaticStr(IQ_QUERY_EMAIL_PATH); phone = request.getChildCDataStaticStr(IQ_QUERY_PHONE_PATH);//linlinno check_code = request.getChildCDataStaticStr(IQ_QUERY_CHECKCODE_PATH); } String pass_enc = null; if (null != password) { pass_enc = XMLUtils.unescape(password); } //linlinno HinestLog.debug("usrname:" + user_name); HinestLog.debug("passwd:" + pass_enc); HinestLog.debug("phone:" + phone); HinestLog.debug("email:" + email); HinestLog.debug("checkcode:" + check_code); Map<String, String> reg_params = new LinkedHashMap<String, String>(); if ((email != null) && !email.trim().isEmpty()) { reg_params.put("email", email); } if ((phone != null) && !phone.trim().isEmpty()) { reg_params.put("phone", phone); } //??to do HinestLog.debug("check check code~~~~to do"); BareJID to = packet.getStanzaTo().getBareJID(); HinestLog.debug("register set:" + to.getDomain()); HinestLog.debug("auth statte:" + session.getAuthState().getErrorCode()); if (session.getAuthState() != Authorization.AUTHORIZED && (to != null) && to.getDomain().equals(USR_DOMAIN)) { // user create new account HinestLog.debug("user create new account..."); Map<String, String> checkInfo = checkInfoList.getCheckInfo(phone, System.currentTimeMillis() - 1000 * 60 * CheckCodeTool.CHECK_CODE_TIMEOUT); checkInfoList.displayAllNodes(); if (checkInfo != null) { String checkCode = checkInfo.get("checkCode"); // ?? if (checkCode.equals(check_code)) { result = session.register(user_name, pass_enc, reg_params); } else { result = Authorization.CHECKCODE_CHECK_FAIL; } } else { result = Authorization.CHECKCODE_CHECK_FAIL; } } else if (session.getAuthState() == Authorization.AUTHORIZED && (to != null) && to.getDomain().equals(USR_DOMAIN)) { //usr change pwd HinestLog.debug("usr change pwd..."); result = session.register(user_name, pass_enc, reg_params); } else if (to != null && to.getDomain().equals(DEV_DOMAIN)) { // dev HinestLog.debug("dev..."); result = session.register(user_name, pass_enc, reg_params); } else { result = Authorization.NOT_ALLOWED; } if (result == Authorization.AUTHORIZED) { results.offer(result.getResponseMessage(packet, null, false)); } else { ++statsInvalidRegistrations; results.offer( result.getResponseMessage(packet, "Unsuccessful registration attempt", true)); } } break; case get: { //linlinno boolean getCheckCode = request.findChildStaticStr(IQ_QUERY_GETCHECKCODE_PATH) != null; if (getCheckCode) { String phone = request.getChildCDataStaticStr(IQ_QUERY_GETCHECKCODE_PATH); String checkCode = CheckCodeTool.createCheckCode(CheckCodeTool.CHECK_CODE_LENGTH); HinestLog.debug(packet.toString()); boolean ret = CheckCodeTool.sendCheckCode(phone, checkCode); System.out.println("phone:" + phone + ", checkcode:" + checkCode); if (ret) { //??????? HinestLog.debug("phone:" + phone); HinestLog.debug("checkcode:" + checkCode); HinestLog.debug("record phone,checkcode,createtime~~~~to do"); checkInfoList.addFirstNode(phone, checkCode, System.currentTimeMillis()); checkInfoList.displayAllNodes(); results.offer(packet.okResult((String) null, 0)); } else { results.offer(Authorization.CHECKCODE_SEND_FAIL.getResponseMessage(packet, "Send check code fail", true)); } return; } if (signedFormRequired) { results.offer(packet.okResult(prepareRegistrationForm(session), 0)); } else { BareJID to = packet.getStanzaTo().getBareJID(); HinestLog.debug("register get:" + to.getDomain()); if ((to != null) && to.getDomain().equals(USR_DOMAIN)) { //linlinno results.offer(packet.okResult("<instructions>" + "Choose a user name and password for use with this service." + "Please provide also your e-mail address." + "</instructions>" + "<username/>" + "<password/>" + "<email/>" + "<phone/>" + "<checkcode/>", 1)); } else { results.offer(packet.okResult( "<instructions>" + "Choose a user name and password for use with this service." + "Please provide also your e-mail address." + "</instructions>" + "<username/>" + "<password/>" + "<email/>", 1)); } } break; } case result: // It might be a registration request from transport for // example... Packet pack_res = packet.copyElementOnly(); pack_res.setPacketTo(session.getConnectionId()); results.offer(pack_res); break; default: results.offer(Authorization.BAD_REQUEST.getResponseMessage(packet, "Message type is incorrect", true)); break; } // end of switch (type) } else { if (session.isUserId(id)) { // It might be a registration request from transport for // example... Packet pack_res = packet.copyElementOnly(); pack_res.setPacketTo(session.getConnectionId()); results.offer(pack_res); } else { results.offer(packet.copyElementOnly()); } } } catch (TigaseStringprepException ex) { results.offer(Authorization.JID_MALFORMED.getResponseMessage(packet, "Incorrect user name, stringprep processing failed.", true)); } catch (NotAuthorizedException e) { results.offer(Authorization.NOT_AUTHORIZED.getResponseMessage(packet, "You are not authorized to change registration settings.\n" + e.getMessage(), true)); } catch (TigaseDBException e) { log.warning("Database problem: " + e); results.offer(Authorization.INTERNAL_SERVER_ERROR.getResponseMessage(packet, "Database access problem, please contact administrator.", true)); } // end of try-catch }
From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTest.java
private void submitAndCheckJob(final int documentationId, final boolean archiveJob) throws Exception { Assume.assumeTrue(SystemUtils.IS_OS_UNIX); final List<String> commandArgs = Lists.newArrayList("-c", "'echo hello world'"); final String clusterTag = LOCALHOST_CLUSTER_TAG; final List<ClusterCriteria> clusterCriteriaList = Lists .newArrayList(new ClusterCriteria(Sets.newHashSet(clusterTag))); final String setUpFile = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile") .getFile().getAbsolutePath(); final String configFile1 = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "config1") .getFile().getAbsolutePath(); final Set<String> configs = Sets.newHashSet(configFile1); final String depFile1 = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "dep1") .getFile().getAbsolutePath(); final Set<String> dependencies = Sets.newHashSet(depFile1); final String commandTag = BASH_COMMAND_TAG; final Set<String> commandCriteria = Sets.newHashSet(commandTag); final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, clusterCriteriaList, commandCriteria).withCommandArgs(commandArgs).withDisableLogArchival(!archiveJob) .withSetupFile(setUpFile).withConfigs(configs).withDependencies(dependencies) .withDescription(JOB_DESCRIPTION).withMetadata(this.metadata).withTags(JOB_TAGS) .withGrouping(JOB_GROUPING).withGroupingInstance(JOB_GROUPING_INSTANCE).build(); final String id = this.submitJob(documentationId, jobRequest, null); this.waitForDone(id); this.checkJobStatus(documentationId, id); this.checkJob(documentationId, id, commandArgs, archiveJob); if (archiveJob) { this.checkJobOutput(documentationId, id); }// w w w . j a v a 2 s.c o m this.checkJobRequest(documentationId, id, commandArgs, setUpFile, clusterTag, commandTag, configFile1, depFile1, archiveJob); this.checkJobExecution(documentationId, id); this.checkJobMetadata(documentationId, id); this.checkJobCluster(documentationId, id); this.checkJobCommand(documentationId, id); this.checkJobApplications(documentationId, id); this.checkFindJobs(documentationId, id, JOB_USER); this.checkJobArchive(id, archiveJob); Assert.assertThat(this.jobRepository.count(), Matchers.is(1L)); // Check if the cluster setup file is cached final String clusterSetUpFilePath = this.resourceLoader .getResource(BASE_DIR + CMD1_ID + FILE_DELIMITER + "setupfile").getFile().getAbsolutePath(); Assert.assertTrue(Files.exists(Paths.get(new URI(this.fileCacheProperties.getLocation()).getPath(), UUID.nameUUIDFromBytes(clusterSetUpFilePath.getBytes(Charset.forName("UTF-8"))).toString()))); // Test for conflicts this.testForConflicts(id, commandArgs, clusterCriteriaList, commandCriteria); }
From source file:com.cloud.hypervisor.xenserver.resource.Xenserver625StorageProcessorTest.java
private void prepareAndExecuteTestcreateNewFileSrTestThrowingException( Class<? extends Throwable> exceptionClass) throws XenAPIException, XmlRpcException { String uuid = "hostUuid"; Mockito.when(citrixResourceBase._host.getUuid()).thenReturn(uuid); String srUuid = UUID.nameUUIDFromBytes(pathMock.getBytes()).toString(); Host hostMock = Mockito.mock(Host.class); PowerMockito.mockStatic(Host.class); PowerMockito.when(Host.getByUuid(connectionMock, uuid)).thenReturn(hostMock); PowerMockito.mockStatic(SR.class); PowerMockito.when(SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock), Mockito.eq(pathMock), Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false), Mockito.anyMapOf(String.class, String.class))).thenThrow(Mockito.mock(exceptionClass)); Mockito.doNothing().when(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock), Mockito.any(SR.class), Mockito.any(PBD.class)); SR sr = xenserver625StorageProcessor.createNewFileSr(connectionMock, pathMock); assertNull(sr);/*from w w w . j ava2 s .c o m*/ Mockito.verify(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock), Mockito.any(SR.class), Mockito.any(PBD.class)); }