Example usage for org.apache.commons.codec.digest DigestUtils md5Hex

List of usage examples for org.apache.commons.codec.digest DigestUtils md5Hex

Introduction

In this page you can find the example usage for org.apache.commons.codec.digest DigestUtils md5Hex.

Prototype

public static String md5Hex(String data) 

Source Link

Usage

From source file:com.comdosoft.financial.manage.service.AgentService.java

@Transactional("transactionManager")
public boolean create(Integer types, String name, String cardId, String companyName, String businessLicense,
        String phone, String email, Integer cityId, String address, String username, String password,
        Byte accountType, String cardIdPhotoPath, String licenseNoPicPath) {
    Customer customer = customerMapper.selectByUsername(username);
    if (customer != null) {
        return false;
    }/*from w  w w.j a  v a 2 s  .c  om*/
    customer = new Customer();
    customer.setUsername(username);
    String md5Password = DigestUtils.md5Hex(password);
    customer.setPassword(md5Password);
    customer.setTypes(Customer.TYPE_AGENT);
    customer.setCityId(cityId);
    customer.setPhone(phone);
    customer.setIntegral(0);
    customer.setStatus(Customer.STATUS_NORMAL);
    customer.setAccountType(accountType);
    customer.setCreatedAt(new Date());
    customerMapper.insert(customer);

    Agent agent = new Agent();
    agent.setCustomerId(customer.getId());
    agent.setStatus(Agent.STATUS_WAITING_FIRST_CHECK);
    agent.setTypes(types);
    agent.setName(name);
    agent.setCardId(cardId);
    agent.setCompanyName(companyName);
    agent.setBusinessLicense(businessLicense);
    agent.setPhone(phone);
    agent.setEmail(email);
    agent.setAddress(address);
    agent.setCardIdPhotoPath(cardIdPhotoPath);
    agent.setLicenseNoPicPath(licenseNoPicPath);
    String code = agentMapper.findMaxOneLevelAgentCode();
    if (code == null || code.equals("")) {
        code = "001";
    } else {
        code = String.format("%03d", Integer.parseInt(code) + 1);
    }
    agent.setParentId(0);
    agent.setCode(code);
    agent.setIsHaveProfit(true);
    agent.setFormTypes(Agent.FORMATTYPE_OP);
    agent.setCreatedAt(new Date());
    agent.setUpdatedAt(new Date());
    agentMapper.insert(agent);
    return true;
}

From source file:mx.edu.ittepic.proyectofinal.ejbs.ejbUsers.java

public String updateUser(String userid, String apikey) {

    Message m = new Message();
    Users r = new Users();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();/* ww  w  .  j a v  a 2  s . c om*/
    try {
        Query q = entity.createNamedQuery("Users.updateUser").

                setParameter("apikey", apikey).setParameter("userid", Integer.parseInt(userid));

        String idapi = userid;
        String md5 = DigestUtils.md5Hex(idapi);

        Query a = entity.createNamedQuery("Users.updateUserE").setParameter("apikey", md5)
                .setParameter("userid", Integer.parseInt(userid));

        if (q.executeUpdate() == 1 && a.executeUpdate() == 1) {
            m.setCode(200);
            m.setMsg("Se actualizo correctamente.");
            m.setDetail("OK");
        } else {
            m.setCode(404);
            m.setMsg("No se realizo la actualizacion");
            m.setDetail("");
        }

    } catch (IllegalStateException e) {
        m.setCode(404);
        m.setMsg("No se realizo la actualizacion");
        m.setDetail(e.toString());
    } catch (TransactionRequiredException e) {
        m.setCode(404);
        m.setMsg("No se realizo la actualizacion");
        m.setDetail(e.toString());
    } catch (QueryTimeoutException e) {
        m.setCode(404);
        m.setMsg("No se realizo la actualizacion");
        m.setDetail(e.toString());
    } catch (PersistenceException e) {
        m.setCode(404);
        m.setMsg("No se realizo la actualizacion");
        m.setDetail(e.toString());
    }
    return gson.toJson(m);
}

From source file:de.ingrid.interfaces.csw.mapping.impl.CSWRecordCache.java

@Override
protected String getRelativePath(Serializable id) {
    return DigestUtils.md5Hex(getRecordIdFromCacheId(id).toString()).substring(0, 3);
}

From source file:edu.lternet.pasta.datapackagemanager.DataPackageArchive.java

/**
 * Generate an "archive" of the data package by parsing and retrieving
 * components of the data package resource map
 * //from w  w  w. jav a2s.c o m
 * @param scope
 *          The scope value of the data package
 * @param identifier
 *          The identifier value of the data package
 * @param revision
 *          The revision value of the data package
 * @param map
 *          The resource map of the data package
 * @param authToken
 *          The authentication token of the user requesting the archive
 * @param transaction
 *          The transaction id of the request
 * @return The file name of the data package archive
 * @throws Exception
 */
public String createDataPackageArchive(String scope, Integer identifier, Integer revision, String userId,
        AuthToken authToken, String transaction) throws Exception {

    String zipName = transaction + ".zip";
    String zipPath = tmpDir + "/";

    EmlPackageId emlPackageId = new EmlPackageId(scope, identifier, revision);

    StringBuffer manifest = new StringBuffer();

    Date now = new Date();
    manifest.append("Manifest file for " + zipName + " created on " + now.toString() + "\n");

    DataPackageManager dpm = null;

    /*
     * It is necessary to create a temporary file while building the ZIP archive
     * to prevent the client from accessing an incomplete product.
     */
    String tmpName = DigestUtils.md5Hex(transaction);
    File zFile = new File(zipPath + tmpName);

    if (zFile.exists()) {
        String gripe = "The resource " + zipName + "already exists!";
        throw new ResourceExistsException(gripe);
    }

    try {
        dpm = new DataPackageManager();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        throw e;
    }

    FileOutputStream fOut = null;

    try {
        fOut = new FileOutputStream(zFile);
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }

    if (dpm != null && fOut != null) {

        String map = null;

        try {
            map = dpm.readDataPackage(scope, identifier, revision.toString(), authToken, userId);
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
            throw e;
        }

        Scanner mapScanner = new Scanner(map);

        ZipOutputStream zOut = new ZipOutputStream(fOut);

        while (mapScanner.hasNextLine()) {

            FileInputStream fIn = null;
            String objectName = null;
            File file = null;

            String line = mapScanner.nextLine();

            if (line.contains(URI_MIDDLE_METADATA)) {

                try {
                    file = dpm.getMetadataFile(scope, identifier, revision.toString(), userId, authToken);
                    objectName = emlPackageId.toString() + ".xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_REPORT)) {

                try {
                    file = dpm.readDataPackageReport(scope, identifier, revision.toString(), emlPackageId,
                            authToken, userId);
                    objectName = emlPackageId.toString() + ".report.xml";
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            } else if (line.contains(URI_MIDDLE_DATA)) {

                String[] lineParts = line.split("/");
                String entityId = lineParts[lineParts.length - 1];
                String dataPackageResourceId = DataPackageManager.composeResourceId(ResourceType.dataPackage,
                        scope, identifier, revision, null);
                String entityResourceId = DataPackageManager.composeResourceId(ResourceType.data, scope,
                        identifier, revision, entityId);

                String entityName = null;
                String xml = null;

                try {
                    entityName = dpm.readDataEntityName(dataPackageResourceId, entityResourceId, authToken);
                    xml = dpm.readMetadata(scope, identifier, revision.toString(), userId, authToken);
                    objectName = dpm.findObjectName(xml, entityName);
                    file = dpm.getDataEntityFile(scope, identifier, revision.toString(), entityId, authToken,
                            userId);
                } catch (UnauthorizedException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                    manifest.append(objectName + " (access denied)\n");
                } catch (ResourceNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (SQLException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

                if (file != null) {
                    try {
                        fIn = new FileInputStream(file);
                        Long size = FileUtils.sizeOf(file);
                        manifest.append(objectName + " (" + size.toString() + " bytes)\n");
                    } catch (FileNotFoundException e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }

            }

            if (objectName != null && fIn != null) {

                ZipEntry zipEntry = new ZipEntry(objectName);

                try {
                    zOut.putNextEntry(zipEntry);

                    int length;
                    byte[] buffer = new byte[1024];

                    while ((length = fIn.read(buffer)) > 0) {
                        zOut.write(buffer, 0, length);
                    }

                    zOut.closeEntry();
                    fIn.close();

                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }

            }

        }

        // Create ZIP archive manifest
        File mFile = new File(zipPath + transaction + ".txt");
        FileUtils.writeStringToFile(mFile, manifest.toString());
        ZipEntry zipEntry = new ZipEntry("manifest.txt");

        try {

            FileInputStream fIn = new FileInputStream(mFile);
            zOut.putNextEntry(zipEntry);

            int length;
            byte[] buffer = new byte[1024];

            while ((length = fIn.read(buffer)) > 0) {
                zOut.write(buffer, 0, length);
            }

            zOut.closeEntry();
            fIn.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        // Close ZIP archive
        zOut.close();

        FileUtils.forceDelete(mFile);

    }

    File tmpFile = new File(zipPath + tmpName);
    File zipFile = new File(zipPath + zipName);

    // Copy hidden ZIP archive to visible ZIP archive, thus making available
    if (!tmpFile.renameTo(zipFile)) {
        String gripe = "Error renaming " + tmpName + " to " + zipName + "!";
        throw new IOException();
    }

    return zipName;

}

From source file:com.cloudera.cdk.tools.JobClasspathHelper.java

/**
 * //from w  ww.j  av  a2  s  . c o m
 * @param conf
 *            Configuration object for the Job. Used to get the FileSystem associated with it.
 * @param libDir
 *            Destination directory in the FileSystem (Usually HDFS) where to upload and look for the libs.
 * @param classesToInclude
 *            Classes that are needed by the job. JarFinder will look for the jar containing these classes.
 * @throws Exception
 */
public void prepareClasspath(final Configuration conf, final Path libDir, Class<?>... classesToInclude)
        throws Exception {
    FileSystem fs = null;
    List<Class<?>> classList = new ArrayList<Class<?>>(Arrays.asList(classesToInclude));
    fs = FileSystem.get(conf);
    Map<String, String> jarMd5Map = new TreeMap<String, String>();
    // for each classes we use JarFinder to locate the jar in the local classpath.
    for (Class<?> clz : classList) {
        if (clz != null) {
            String localJarPath = JarFinder.getJar(clz);
            // we don't want to upload the same jar twice
            if (!jarMd5Map.containsKey(localJarPath)) {
                // We should not push core Hadoop classes with this tool.
                // Should it be the responsibility of the developer or we let
                // this fence here?
                if (!clz.getName().startsWith("org.apache.hadoop.")) {
                    // we compute the MD5 sum of the local jar
                    InputStream in = new FileInputStream(localJarPath);
                    boolean threw = true;
                    try {
                        String md5sum = DigestUtils.md5Hex(in);
                        jarMd5Map.put(localJarPath, md5sum);
                        threw = false;
                    } finally {
                        Closeables.close(in, threw);
                    }
                } else {
                    logger.info("Ignoring {}, since it looks like it's from Hadoop's core libs", localJarPath);
                }
            }
        }
    }

    for (Entry<String, String> entry : jarMd5Map.entrySet()) {
        Path localJarPath = new Path(entry.getKey());
        String jarFilename = localJarPath.getName();
        String localMd5sum = entry.getValue();
        logger.info("Jar {}. MD5 : [{}]", localJarPath, localMd5sum);

        Path remoteJarPath = new Path(libDir, jarFilename);
        Path remoteMd5Path = new Path(libDir, jarFilename + ".md5");

        // If the jar file does not exist in HDFS or if the MD5 file does not exist in HDFS,
        // we force the upload of the jar.
        if (!fs.exists(remoteJarPath) || !fs.exists(remoteMd5Path)) {
            copyJarToHDFS(fs, localJarPath, localMd5sum, remoteJarPath, remoteMd5Path);
        } else {
            // If the jar exist,we validate the MD5 file.
            // If the MD5 sum is different, we upload the jar
            FSDataInputStream md5FileStream = null;

            String remoteMd5sum = "";
            try {
                md5FileStream = fs.open(remoteMd5Path);
                byte[] md5bytes = new byte[32];
                if (32 == md5FileStream.read(md5bytes)) {
                    remoteMd5sum = new String(md5bytes, Charsets.UTF_8);
                }
            } finally {
                if (md5FileStream != null) {
                    md5FileStream.close();
                }
            }

            if (localMd5sum.equals(remoteMd5sum)) {
                logger.info("Jar {} already exists [{}] and md5sum are equals", jarFilename,
                        remoteJarPath.toUri().toASCIIString());
            } else {
                logger.info("Jar {} already exists [{}] and md5sum are different!", jarFilename,
                        remoteJarPath.toUri().toASCIIString());
                copyJarToHDFS(fs, localJarPath, localMd5sum, remoteJarPath, remoteMd5Path);
            }

        }
        // In all case we want to add the jar to the DistributedCache's classpath
        DistributedCache.addFileToClassPath(remoteJarPath, conf, fs);
    }
    // and we create the symlink (was necessary in earlier versions of Hadoop)
    DistributedCache.createSymlink(conf);
}

From source file:com.jredrain.startup.Bootstrap.java

public void start(int port, String password) throws Exception {
    this.port = port;
    this.password = DigestUtils.md5Hex(password).toLowerCase();
    start();//from www. java  2  s  . c  o m
}

From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.PackageRepositoryPoller.java

public PackageRevisionMessage getLatestRevision(PackageMaterialProperties packageConfiguration,
        PackageMaterialProperties repositoryConfiguration) {
    validateData(packageConfiguration, repositoryConfiguration);
    PackageMaterialProperty packageSpec = packageConfiguration.getProperty(Constants.PACKAGE_SPEC);
    RepoUrl url = repoUrl(repositoryConfiguration);
    url.checkConnection();//from ww w. jav  a2 s.c om
    return executeRepoQuery(DigestUtils.md5Hex(url.forDisplay()), url, packageSpec);
}

From source file:com.seajas.search.utilities.spring.security.dao.UserDAO.java

/**
 * Add a new user./* w  w  w .  j a  v a  2s  . c  o m*/
 * 
 * @param username
 * @param password
 * @param fullname
 * @return boolean
 */
public boolean addUser(final String username, final String password, final String fullname) {
    try {
        return jdbc.update("INSERT INTO user (username, password, fullname, is_enabled) VALUES(?, ?, ?, 1)",
                username, DigestUtils.md5Hex(password), fullname) == 1;
    } catch (DataAccessException e) {
        logger.error("Could not add user '" + username + "'", e);
    }

    return false;
}

From source file:com.lingxiang2014.controller.shop.PasswordController.java

@RequestMapping(value = "reset", method = RequestMethod.POST)
public @ResponseBody Message reset(String captchaId, String captcha, String username, String newPassword,
        String key) {//w  ww.ja v  a2s . c o  m
    if (!captchaService.isValid(CaptchaType.resetPassword, captchaId, captcha)) {
        return Message.error("shop.captcha.invalid");
    }
    Member member = memberService.findByUsername(username);
    if (member == null) {
        return ERROR_MESSAGE;
    }
    if (!isValid(Member.class, "password", newPassword, Save.class)) {
        return Message.warn("shop.password.invalidPassword");
    }
    Setting setting = SettingUtils.get();
    if (newPassword.length() < setting.getPasswordMinLength()
            || newPassword.length() > setting.getPasswordMaxLength()) {
        return Message.warn("shop.password.invalidPassword");
    }
    SafeKey safeKey = member.getSafeKey();
    if (safeKey == null || safeKey.getValue() == null || !safeKey.getValue().equals(key)) {
        return ERROR_MESSAGE;
    }
    if (safeKey.hasExpired()) {
        return Message.error("shop.password.hasExpired");
    }
    member.setPassword(DigestUtils.md5Hex(newPassword));
    member.setPassword2(DigestUtils.md5Hex(newPassword));
    safeKey.setExpire(new Date());
    safeKey.setValue(null);
    memberService.update(member);
    return Message.success("shop.password.resetSuccess");
}

From source file:hash.HashFilesController.java

private void generateChecksums(File file) {

    FileInputStream md5fis;/*  w ww .  j ava  2  s .  c o m*/

    String md5 = "";

    try {
        md5fis = new FileInputStream(file);

        md5 = DigestUtils.md5Hex(md5fis);

        md5fis.close();

    } catch (IOException ex) {
        Logger.getLogger(HashFilesController.class.getName()).log(Level.SEVERE, null, ex);
    }

    Checksum aChecksum = new Checksum();
    aChecksum.setMD5Value(md5);
    ;
    aChecksum.setFileName(file.getName());
    aChecksum.setFilePath(file.getPath());

    DateTimeFormatter format = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT);
    LocalDateTime currentDateTime = LocalDateTime.now();
    currentDateTime.format(format);

    aChecksum.setDateTimeGenerated(currentDateTime);

    SessionFactory sFactory = HibernateUtilities.getSessionFactory();
    Session session = sFactory.openSession();
    session.beginTransaction();
    session.saveOrUpdate(aChecksum);

    CaseFile currentCase = (CaseFile) session.get(CaseFile.class, CreateCaseController.getCaseNumber());

    currentCase.getMd5Details().add(aChecksum);
    aChecksum.setCaseFile(currentCase);

    session.getTransaction().commit();
    session.close();

    checksumTableView.getItems().add(aChecksum);

    System.out.println(aChecksum.getMD5Value());
    System.out.println(aChecksum.getFileName());
    System.out.println(aChecksum.getFilePath());

}