Example usage for java.util UUID toString

List of usage examples for java.util UUID toString

Introduction

In this page you can find the example usage for java.util UUID toString.

Prototype

public String toString() 

Source Link

Document

Returns a String object representing this UUID .

Usage

From source file:QRCode.java

public static String createQRCode(String arg) {
    int size = 125;
    String fileType = "png";
    File myFile = null;//  w ww. ja v a  2  s .  c om
    UUID uuid = UUID.nameUUIDFromBytes(arg.getBytes());

    try {
        myFile = File.createTempFile("temp-file-name", ".png");

        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix byteMatrix = qrCodeWriter.encode(uuid.toString(), BarcodeFormat.QR_CODE, size, size, hintMap);
        int CrunchifyWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();

        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth);
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < CrunchifyWidth; i++) {
            for (int j = 0; j < CrunchifyWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i, j, 1, 1);
                }
            }
        }
        ImageIO.write(image, fileType, myFile);
        //System.out.println("\n\nYou have successfully created QR Code " + myFile.getCanonicalPath());
        return myFile.getCanonicalPath();
    } catch (WriterException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.security.ch08_rsa.RSACoderTextKey.java

/**
 * ?//  w w  w  .  ja v a  2 s  .com
 *
 * @return Map Map
 * @throws Exception
 */
public static Map<String, String> initKey(UUID licenseCode) throws Exception {
    // ?
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);

    // ??
    //        keyPairGen.initialize(KEY_SIZE);
    keyPairGen.initialize(KEY_SIZE, new SecureRandom(licenseCode.toString().getBytes(UTF_8)));

    // ?
    KeyPair keyPair = keyPairGen.generateKeyPair();

    // 
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    // ?
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

    // ?
    Map<String, String> keyMap = new HashMap<String, String>();

    keyMap.put(PUBLIC_KEY, Base64.encodeBase64String(publicKey.getEncoded()));
    keyMap.put(PRIVATE_KEY, Base64.encodeBase64String(privateKey.getEncoded()));
    keyMap.put(LICENSE_CODE, licenseCode.toString());

    return keyMap;
}

From source file:me.ryanhamshire.griefprevention.migrator.RedProtectMigrator.java

public static void migrate(World world, Path redProtectFilePath, Path gpClaimDataPath)
        throws FileNotFoundException, ClassNotFoundException {
    if (!GriefPreventionPlugin.getGlobalConfig().getConfig().migrator.redProtectMigrator) {
        return;//from  www .  jav  a  2  s.  com
    }

    int count = 0;
    try {
        GriefPreventionPlugin.instance.getLogger().info("Starting RedProtect region data migration for world "
                + world.getProperties().getWorldName() + "...");
        ConfigurationLoader<CommentedConfigurationNode> regionManager = HoconConfigurationLoader.builder()
                .setPath(redProtectFilePath).build();
        CommentedConfigurationNode region = regionManager.load();
        GriefPreventionPlugin.instance.getLogger()
                .info("Scanning RedProtect regions in world data file '" + redProtectFilePath + "'...");
        for (Object key : region.getChildrenMap().keySet()) {
            String rname = key.toString();
            if (!region.getNode(rname).hasMapChildren()) {
                continue;
            }
            int maxX = region.getNode(rname, "maxX").getInt();
            int maxY = region.getNode(rname, "maxY").getInt(255);
            int maxZ = region.getNode(rname, "maxZ").getInt();
            int minX = region.getNode(rname, "minX").getInt();
            int minY = region.getNode(rname, "minY").getInt(0);
            int minZ = region.getNode(rname, "minZ").getInt();
            List<String> owners = new ArrayList<String>();
            owners.addAll(region.getNode(rname, "owners").getList(TypeToken.of(String.class)));

            List<String> members = new ArrayList<String>();
            members.addAll(region.getNode(rname, "members").getList(TypeToken.of(String.class)));

            String creator = region.getNode(rname, "creator").getString();
            String welcome = region.getNode(rname, "welcome").getString();

            // create GP claim data file
            GriefPreventionPlugin.instance.getLogger()
                    .info("Migrating RedProtect region data '" + rname + "'...");
            UUID ownerUniqueId = null;
            if (validate(creator)) {
                try {
                    // check cache first
                    ownerUniqueId = PlayerUtils.getUUIDByName(creator);
                    if (ownerUniqueId == null) {
                        ownerUniqueId = UUID.fromString(getUUID(creator));
                    }
                } catch (Throwable e) {
                    // assume admin claim
                }
            }

            UUID claimUniqueId = UUID.randomUUID();
            Location<World> lesserBoundaryCorner = new Location<>(world, minX, minY, minZ);
            Location<World> greaterBoundaryCorner = new Location<>(world, maxX, maxY, maxZ);
            Path claimFilePath = gpClaimDataPath.resolve(claimUniqueId.toString());
            if (!Files.exists(claimFilePath)) {
                Files.createFile(claimFilePath);
            }

            ClaimStorageData claimStorage = new ClaimStorageData(claimFilePath);
            ClaimDataConfig claimDataConfig = claimStorage.getConfig();
            claimDataConfig.setName(Text.of(rname));
            claimDataConfig.setWorldUniqueId(world.getUniqueId());
            claimDataConfig.setOwnerUniqueId(ownerUniqueId);
            claimDataConfig.setLesserBoundaryCorner(BlockUtils.positionToString(lesserBoundaryCorner));
            claimDataConfig.setGreaterBoundaryCorner(BlockUtils.positionToString(greaterBoundaryCorner));
            claimDataConfig.setDateLastActive(Instant.now());
            claimDataConfig.setType(ownerUniqueId == null ? ClaimType.ADMIN : ClaimType.BASIC);
            if (!welcome.equals("")) {
                claimDataConfig.setGreeting(Text.of(welcome));
            }
            List<String> rpUsers = new ArrayList<>(owners);
            rpUsers.addAll(members);
            List<UUID> builders = claimDataConfig.getBuilders();
            for (String builder : rpUsers) {
                if (!validate(builder)) {
                    continue;
                }

                UUID builderUniqueId = null;
                try {
                    builderUniqueId = PlayerUtils.getUUIDByName(builder);
                    if (builderUniqueId == null) {
                        builderUniqueId = UUID.fromString(getUUID(builder));
                    }
                } catch (Throwable e) {
                    GriefPreventionPlugin.instance.getLogger().error("Could not locate a valid UUID for user '"
                            + builder + "' in region '" + rname + "'. Skipping...");
                    continue;
                }
                if (!builders.contains(builderUniqueId) && ownerUniqueId != null
                        && !builderUniqueId.equals(ownerUniqueId)) {
                    builders.add(builderUniqueId);
                }
            }

            claimDataConfig.setRequiresSave(true);
            claimStorage.save();
            GriefPreventionPlugin.instance.getLogger().info(
                    "Successfully migrated RedProtect region data '" + rname + "' to '" + claimFilePath + "'");
            count++;
        }
        GriefPreventionPlugin.instance.getLogger().info("Finished RedProtect region data migration for world '"
                + world.getProperties().getWorldName() + "'." + " Migrated a total of " + count + " regions.");
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ObjectMappingException e) {
        e.printStackTrace();
    }
}

From source file:edu.jhu.pha.vospace.jobs.JobsProcessor.java

/**
 * Returns the JobDescription object serialized from the database record
 * @param jobId The identifier of a job/*from  w  ww  .  j  a  v a  2 s.c o  m*/
 * @return The job java object
 */
public static JobDescription getJob(final UUID jobId) {
    return DbPoolServlet.goSql("GetJob request", "select json_notation, note from jobs where id = ?",
            new SqlWorker<JobDescription>() {
                @Override
                public JobDescription go(Connection conn, PreparedStatement stmt) throws SQLException {
                    JobDescription returnJob = null;
                    stmt.setString(1, jobId.toString());
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        byte[] jobJsonNotation = rs.getBytes(1);
                        try {
                            returnJob = (new ObjectMapper()).readValue(jobJsonNotation, 0,
                                    jobJsonNotation.length, JobDescription.class);
                            returnJob.setNote(rs.getString("note"));
                        } catch (JsonMappingException ex) { // Shouldn't happen
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (JsonParseException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        } catch (IOException ex) {
                            throw new InternalServerErrorException(ex.getMessage());
                        }
                    }
                    return returnJob;
                }
            });
}

From source file:org.nebulaframework.deployment.classloading.node.exporter.GridNodeClassExporterSupport.java

/**
 * Creates and starts the {@code GridNodeClassExporter} service for the
 * local {@code GridNode}. This method creates the service itself, and the
 * necessary JMS resources, along with Spring JMS Remoting services, and
 * starts the remote service.//w w w. j a  v  a 2 s .c  o m
 * 
 * @throws IllegalArgumentException
 *             if any argument is {@code null}
 */
public static void startService() throws IllegalArgumentException {

    UUID nodeId = GridNode.getInstance().getId();
    ConnectionFactory cf = GridNode.getInstance().getConnectionFactory();
    String queueName = getExporterQueueName(nodeId);

    // Create Service
    GridNodeClassExporterImpl service = new GridNodeClassExporterImpl();
    DefaultMessageListenerContainer container = JMSRemotingSupport.createService(cf, queueName, service,
            GridNodeClassExporter.class);

    // CleanUpHook
    CleanUpSupport.shutdownContainerWhenNodeLeft(nodeId.toString(), container);

    log.debug("[GridNodeClassExporter] Service Started");
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccXMsg.CFAccXMsgSchemaMessageFormatter.java

public static String formatRspnLoggedIn(String separator, long clusterId, String clusterName, long tenantId,
        String tenantName, UUID secUserId, String secUserName, UUID secSessionId) {
    String retval = "<RspnLoggedIn " + CFLibXmlUtil.formatRequiredInt64(null, "ClusterId", clusterId)
            + CFLibXmlUtil.formatRequiredXmlString(separator, "ClusterName", clusterName)
            + CFLibXmlUtil.formatRequiredInt64(separator, "TenantId", tenantId)
            + CFLibXmlUtil.formatRequiredXmlString(separator, "TenantName", tenantName)
            + CFLibXmlUtil.formatRequiredXmlString(separator, "SecUserId", secUserId.toString())
            + CFLibXmlUtil.formatRequiredXmlString(separator, "SecUserName", secUserName)
            + CFLibXmlUtil.formatRequiredXmlString(separator, "SecSessionId", secSessionId.toString()) + " />";
    return (retval);
}

From source file:de.eod.jliki.users.utils.UserDBHelper.java

/**
 * Logs in a user returned from database after the login test was made.<br/>
 * @param dbUser the user from database (session may not be closed!)
 * @param passedLogin did the user pass the login test?
 * @param rememberMe will the user stay logged in?
 * @param userLogin the login object/*from w w  w  . j av a2 s  . co m*/
 * @param session the hibernate session for further queries
 * @return true if the user was logged in
 */
private static boolean loginUser(final User dbUser, final boolean passedLogin, final boolean rememberMe,
        final LoginBean userLogin, final Session session) {
    boolean didLogin = false;
    if (passedLogin && dbUser.getActive() == ActiveState.ACTIVE) {
        didLogin = true;
        userLogin.setUserName(dbUser.getName());
        userLogin.setLoggedIn(true);
    } else {
        didLogin = false;
        userLogin.setUserName(userLogin.getUserName());
        userLogin.setLoggedIn(false);
    }

    dbUser.setLastlogin(new Date());

    final UUID loginUUID = UUID.randomUUID();
    Cookie cookie = null;
    final int tenDays = 60 * 60 * 24 * 10;
    if (rememberMe && passedLogin) {
        cookie = new Cookie("login", loginUUID.toString());
        cookie.setMaxAge(tenDays);
        dbUser.setCookieid(loginUUID.toString());
    } else {
        cookie = new Cookie("login", "");
        cookie.setMaxAge(0);
        dbUser.setCookieid("");
    }

    userLogin.clearPermissions();
    dbUser.transferPermissionsToLogin(userLogin);
    for (final UserGroup grp : dbUser.getGroups()) {
        grp.transferPermissionsToLogin(userLogin);
    }

    final HttpServletResponse httpServletResponse = (HttpServletResponse) FacesContext.getCurrentInstance()
            .getExternalContext().getResponse();
    httpServletResponse.addCookie(cookie);

    return didLogin;
}

From source file:com.google.cloud.hadoop.gcsio.GoogleCloudStorageIntegrationTest.java

/**
 * Gets randomly generated name of a bucket with the given suffix.
 * The name is prefixed with an identifiable string. A bucket created by this method
 * can be identified by calling isTestBucketName() for that bucket.
 *//*from ww w .  j  a va  2  s .c om*/
public static String getUniqueBucketName(String suffix) {
    UUID uuid = UUID.randomUUID();
    String uniqueBucketName = TEST_BUCKET_NAME_PREFIX + uuid.toString() + suffix;
    // In most cases, caller creates a bucket with this name therefore we proactively add the name
    // to the list of buckets to be deleted. It is ok even if a bucket is not created with
    // this name because deleteBuckets() will ignore non-existent buckets.
    addToDeleteBucketList(uniqueBucketName);
    return uniqueBucketName;
}

From source file:edu.jhu.pha.vospace.rest.TransfersController.java

/**
 * Submit the job to database/*from   w ww.  ja  v  a  2  s. co  m*/
 * @param xmlNode the job XML document
 * @param username the username of the job owner
 * @return the job ID
 */
public static UUID submitJob(String xmlNode, String username) {
    StringReader strRead = new StringReader(xmlNode);
    UUID jobUID = UUID.randomUUID();
    try {

        JobDescription job = new JobDescription();
        job.setId(jobUID.toString());
        job.setUsername(username);
        job.setStartTime(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime());
        job.setState(JobDescription.STATE.PENDING);

        SAXBuilder xmlBuilder = new SAXBuilder();
        Element nodeElm = xmlBuilder.build(strRead).getRootElement();
        List<Element> paramNodes = nodeElm.getChildren();
        for (Iterator<Element> it = paramNodes.iterator(); it.hasNext();) {
            Element param = it.next();
            if (param.getName().equals("target")) {
                try {
                    job.setTarget(param.getValue());
                } catch (URISyntaxException e) {
                    logger.error("Error in job parse: " + e.getMessage());
                    throw new BadRequestException("InvalidURI");
                }
            } else if (param.getName().equals("direction")) {

                JobDescription.DIRECTION direct = JobDescription.DIRECTION.LOCAL;
                if (param.getValue().toUpperCase().endsWith("SPACE"))
                    direct = JobDescription.DIRECTION.valueOf(param.getValue().toUpperCase());

                job.setDirection(direct);

                if (direct == JobDescription.DIRECTION.PULLFROMVOSPACE) {
                    job.addProtocol(conf.getString("transfers.protocol.httpget"),
                            conf.getString("application.url") + "/data/" + job.getId());
                } else if (direct == JobDescription.DIRECTION.PUSHTOVOSPACE) {
                    job.addProtocol(conf.getString("transfers.protocol.httpput"),
                            conf.getString("application.url") + "/data/" + job.getId());
                } else if (direct == JobDescription.DIRECTION.LOCAL) {
                    try {
                        job.setDirectionTarget(param.getValue());
                    } catch (URISyntaxException e) {
                        logger.error("Error in job parse: " + e.getMessage());
                        throw new BadRequestException("InvalidURI");
                    }
                }
            } else if (param.getName().equals("view")) {
                job.addView(param.getValue());
            } else if (param.getName().equals("keepBytes")) {
                job.setKeepBytes(Boolean.parseBoolean(param.getValue()));
            } else if (param.getName().equals("protocol")) {
                String protocol = param.getAttributeValue("uri");
                String protocolEndpoint = param.getChildText("protocolEndpoint",
                        Namespace.getNamespace(VOS_NAMESPACE));

                if (job.getDirection().equals(DIRECTION.PULLFROMVOSPACE)
                        || job.getDirection().equals(DIRECTION.PUSHTOVOSPACE)) {
                    protocolEndpoint = conf.getString("application.url") + "/data/" + job.getId();
                }

                if (null != protocol && null != protocolEndpoint)
                    job.addProtocol(protocol, protocolEndpoint);
                else
                    throw new BadRequestException("InvalidArgument");
            }
        }

        JobsProcessor.getDefaultImpl().submitJob(username, job);
    } catch (JDOMException e) {
        e.printStackTrace();
        throw new InternalServerErrorException(e);
    } catch (IOException e) {
        logger.error(e);
        throw new InternalServerErrorException(e);
    } catch (IllegalArgumentException e) {
        logger.error("Error calling the job task: " + e.getMessage());
        throw new InternalServerErrorException("InternalFault");
    } finally {
        strRead.close();
    }
    return jobUID;
}

From source file:net.modsec.ms.connector.ConnRequestHandler.java

/**
 * Parses the json, extracts the rules and deploy those rules into modsecurity. It takes the rule 
 * string from the json and creates a rule file then copy it to modsecurity rule file folder. It alsp
 * restarts the modsecurity after deploying the rule
 * @param json reponses whether the rule is successfully deployed or not.
 *//*from w  w w  . j ava 2  s.co m*/
@SuppressWarnings("unchecked")
public static void onDeployMSRules(JSONObject json) {

    log.info("onDeployMSRules called.. : " + json.toJSONString());

    MSConfig serviceCfg = MSConfig.getInstance();
    JSONObject jsonResp = new JSONObject();

    String ruleDirPath = serviceCfg.getConfigMap().get("RuleFileDir");
    String ruleFileString = (String) json.get("ruleString");
    String ruleFileName = "";

    InputStream ins = null;
    FileOutputStream out = null;
    BufferedReader br = null;

    if (json.containsKey("groupName")) {

        ruleFileName += ((String) json.get("groupName")).toLowerCase() + ".conf";

    } else {

        UUID randomName = UUID.randomUUID();
        ruleFileName += randomName.toString() + ".conf";

    }

    try {

        //modified string writing to modsecurity configurations
        log.info("Writing a rule to File :" + ruleFileName);
        File file = new File(ruleDirPath + "/" + ruleFileName);
        file.createNewFile();
        out = new FileOutputStream(file);
        out.write(ruleFileString.getBytes());
        out.close();

        log.info("ModSecurity Rules Written ... ");

        //For Restarting modsecurity so that modified configuration can be applied
        JSONObject restartJson = new JSONObject();
        restartJson.put("action", "restart");

        String cmd = serviceCfg.getConfigMap().get("MSRestart");

        String status = (String) executeShScript(cmd, restartJson).get("status");

        //if rule file is giving syntax error while deploying rules on server end 
        if (status.equals("1")) {

            if (file.delete()) {
                log.info("Successfully deleted conflicting file : " + file.getName());
                executeShScript(cmd, restartJson);
            } else {
                log.info("unable to delete file : " + file.getName());
            }
            jsonResp.put("action", "deployRules");
            jsonResp.put("status", "1");
            jsonResp.put("message", "Unable to deploy specified Rules. They either"
                    + "conflicting to the already deployed rules");

        } else {

            jsonResp.put("action", "deployRules");
            jsonResp.put("status", "0");
            jsonResp.put("message", "Rules Deployed!");

        }

    } catch (FileNotFoundException e1) {

        jsonResp.put("action", "deployRules");
        jsonResp.put("status", "1");
        jsonResp.put("message", "Internal Service is down!");
        e1.printStackTrace();

    } catch (IOException | NullPointerException e) {

        jsonResp.put("action", "deployRules");
        jsonResp.put("status", "0");
        jsonResp.put("message", "Unable to create rule file on Server.");
        e.printStackTrace();

    }

    log.info("Sending Json :" + jsonResp.toJSONString());
    ConnectorService.getConnectorProducer().send(jsonResp.toJSONString());
    jsonResp.clear();
}