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:fll.web.admin.CreateUser.java

@Override
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {

    PreparedStatement addUser = null;
    PreparedStatement checkUser = null;
    ResultSet rs = null;//from w  ww  . j a  v  a 2s  .  c  o m
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        final String user = request.getParameter("user");
        final String pass = request.getParameter("pass");
        final String passCheck = request.getParameter("pass_check");
        if (null == pass || null == passCheck || null == user || user.isEmpty() || pass.isEmpty()
                || passCheck.isEmpty()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>You must enter all information in the form.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        if (!pass.equals(passCheck)) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Password and password check do not match.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        checkUser = connection.prepareStatement("SELECT fll_user FROM fll_authentication WHERE fll_user = ?");
        checkUser.setString(1, user);
        rs = checkUser.executeQuery();
        if (rs.next()) {
            session.setAttribute(SessionAttributes.MESSAGE,
                    "<p class='error'>Username '" + user + "' already exists.</p>");
            response.sendRedirect(response.encodeRedirectURL("createUsername.jsp"));
            return;
        }

        final String hashedPass = DigestUtils.md5Hex(pass);
        addUser = connection
                .prepareStatement("INSERT INTO fll_authentication (fll_user, fll_pass) VALUES(?, ?)");
        addUser.setString(1, user);
        addUser.setString(2, hashedPass);
        addUser.executeUpdate();

        session.setAttribute(SessionAttributes.MESSAGE,
                "<p class='success' id='success-create-user'>Successfully created user '" + user + "'</p>");

        // do a login if not already logged in
        final Collection<String> loginKeys = CookieUtils.findLoginKey(request);
        final String authenticatedUser = Queries.checkValidLogin(connection, loginKeys);
        if (null == authenticatedUser) {
            DoLogin.doLogin(request, response, application, session);
        } else {
            response.sendRedirect(response.encodeRedirectURL("index.jsp"));
        }

    } catch (final SQLException e) {
        throw new RuntimeException(e);
    } finally {
        SQLFunctions.close(rs);
        SQLFunctions.close(checkUser);
        SQLFunctions.close(addUser);
        SQLFunctions.close(connection);
    }

}

From source file:com.wipro.ats.bdre.filemon.FileMonitor.java

private static void putEligibleFileInfoInMap(String fileName, FileContent fc) {
    // *Start*   Eligible files moved to data structure for ingestion to HDFS
    FileCopyInfo fileCopyInfo = new FileCopyInfo();
    try {/*w ww.j  a va  2  s.c o  m*/
        fileCopyInfo.setFileName(fileName);
        fileCopyInfo.setSubProcessId(FileMonRunnableMain.getSubProcessId());
        fileCopyInfo.setServerId(Integer.toString(123461));
        fileCopyInfo.setSrcLocation(fc.getFile().getName().getPath());
        fileCopyInfo.setDstLocation(new java.io.File(fileName).getParent()
                .replace(FileMonRunnableMain.getMonitoredDirName(), FileMonRunnableMain.getHdfsUploadDir()));
        fileCopyInfo.setFileHash(DigestUtils.md5Hex(fc.getInputStream()));
        fileCopyInfo.setFileSize(fc.getSize());
        fileCopyInfo.setTimeStamp(fc.getLastModifiedTime());
        // putting element to structure
        addToQueue(fileName, fileCopyInfo);
    } catch (Exception err) {
        LOGGER.error("Error adding file to queue ", err);
        throw new BDREException(err);
    }
    // *End*   Eligible files moved to data structure for ingestion to HDFS
}

From source file:com.atlassian.jira.TestDefaultJiraApplicationContext.java

@Test
public void testGenerateFingerPrint() {
    DefaultJiraApplicationContext applicationContext = new DefaultJiraApplicationContext(applicationProperties,
            jiraLicenseService);//  w  ww  .j  av  a  2s  . c  o m
    String fingerPrint = applicationContext.generateFingerPrint("foo", "bar");
    assertEquals(DigestUtils.md5Hex("foobar"), fingerPrint);
}

From source file:de.shadowhunt.subversion.internal.InfoLoader.java

public Info load(final Resource resource, final Revision revision) throws Exception {
    final File infoFile = new File(root, resolve(revision) + resource.getValue() + SUFFIX);

    final SAXParser saxParser = BasicHandler.FACTORY.newSAXParser();
    final InfoHandler handler = new InfoHandler();

    saxParser.parse(infoFile, handler);// w ww.  j a  v a  2 s. c  om
    final InfoImpl info = handler.getInfo();

    info.setResource(resource);
    final File f = new File(root, resolve(revision) + resource.getValue());
    info.setDirectory(f.isDirectory());
    if (info.isFile()) {
        final FileInputStream fis = new FileInputStream(f);
        try {
            info.setMd5(DigestUtils.md5Hex(fis));
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }

    info.setProperties(resourcePropertyLoader.load(resource, revision));
    Assert.assertEquals("resource must match", resource, info.getResource());
    return info;
}

From source file:com.lehealth.common.sdk.CCPRestSDK.java

/**
 * ???//from  ww  w.j a v  a  2s.co m
 * 
 * @param to
 *            ? ??????????100
 * @param templateId
 *            ? ?Id
 * @param datas
 *            ?? ???{??}
 * @return
 */
public JSONObject sendTemplateSMS(String to, String templateId, String[] datas, String domain, String appId,
        String sid, String token) {
    JSONObject errorInfo = this.accountValidate(domain, appId, sid, token);
    if (errorInfo != null) {
        return errorInfo;
    }

    if (StringUtils.isBlank(to) || StringUtils.isBlank(appId) || StringUtils.isBlank(templateId)) {
        throw new IllegalArgumentException("?:" + (StringUtils.isBlank(to) ? " ?? " : "")
                + (StringUtils.isBlank(templateId) ? " ?Id " : "") + "");
    }

    String timestamp = DateFormatUtils.format(new Date(), Constant.dateFormat_yyyymmddhhmmss);
    String acountName = sid;
    String sig = sid + token + timestamp;
    String acountType = "Accounts";
    String signature = DigestUtils.md5Hex(sig);
    String url = getBaseUrl(domain).append("/" + acountType + "/").append(acountName)
            .append("/" + TemplateSMS + "?sig=").append(signature).toString();

    String src = acountName + ":" + timestamp;
    String auth = Base64.encodeBase64String(src.getBytes());
    Map<String, String> header = new HashMap<String, String>();
    header.put("Accept", "application/json");
    header.put("Content-Type", "application/json;charset=utf-8");
    header.put("Authorization", auth);

    JSONObject json = new JSONObject();
    json.accumulate("appId", appId);
    json.accumulate("to", to);
    json.accumulate("templateId", templateId);
    if (datas != null) {
        JSONArray Jarray = new JSONArray();
        for (String s : datas) {
            Jarray.add(s);
        }
        json.accumulate("datas", Jarray);
    }
    String requestBody = json.toString();

    DefaultHttpClient httpclient = null;
    HttpPost postMethod = null;
    try {
        httpclient = new CcopHttpClient().registerSSL(domain, NumberUtils.toInt(SERVER_PORT), "TLS", "https");
        postMethod = new HttpPost(url);
        if (header != null && !header.isEmpty()) {
            for (Entry<String, String> e : header.entrySet()) {
                postMethod.setHeader(e.getKey(), e.getValue());
            }
        }
        postMethod.setConfig(PoolConnectionManager.requestConfig);
        BasicHttpEntity requestEntity = new BasicHttpEntity();
        requestEntity.setContent(new ByteArrayInputStream(requestBody.getBytes("UTF-8")));
        requestEntity.setContentLength(requestBody.getBytes("UTF-8").length);
        postMethod.setEntity(requestEntity);

        HttpResponse response = httpclient.execute(postMethod);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            EntityUtils.consume(entity);
            return JSONObject.fromObject(result);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
    }
    return getMyError("999999", "");
}

From source file:com.jredrain.controller.AgentController.java

@RequestMapping("/add")
public String add(Agent agent) {
    if (!agent.getWarning()) {
        agent.setMobiles(null);// w  ww . ja  va  2 s.  c o  m
        agent.setEmailAddress(null);
    }

    //?
    if (RedRain.ConnType.CONN.getType().equals(agent.getProxy())) {
        agent.setProxyAgent(null);
    }

    agent.setPassword(DigestUtils.md5Hex(agent.getPassword()));
    agent.setStatus(true);
    agent.setUpdateTime(new Date());
    agentService.addOrUpdate(agent);
    return "redirect:/agent/view";
}

From source file:de.wusel.partyplayer.gui.dialog.ChangePasswordDialog.java

private void ok() {
    if (!oldPasswordField.isEnabled()
            || setting.isPasswordValid(DigestUtils.md5Hex(new String(oldPasswordField.getPassword())))) {
        status = DialogStatus.CONFIRMED;
        dispose();//from ww w.  ja v  a2  s .  c  o m
    } else {
        JOptionPane.showMessageDialog(this, "Das alte Passwort ist ungltig!");
    }
}

From source file:com.oic.net.Callback.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    String code = request.getParameter("code");
    if (request.getParameter("code") == null) { //OAuth??code????
        response.sendRedirect("/");
    } else if (request.getParameter("register") != null) { //ID?
        session.setAttribute("alreadyId", true);
        return;/*w  w  w.j av  a 2s.c  o  m*/
    }
    if (session.isNew()) {
        session.setMaxInactiveInterval(300);
    }
    String email = "";
    try {
        getToken(code);
        System.out.println(code);
        email = getEmailAddress();
    } catch (Exception e) {
        e.printStackTrace();
    }
    Pattern pattern = Pattern.compile("@oic.jp$");
    Matcher matcher = pattern.matcher(email);
    if (matcher.find()) {
        Pattern numberPattern = Pattern.compile("^[a-zA-Z][0-9]{4}");
        Matcher numberMatcher = numberPattern.matcher(email.toLowerCase());
        if (!numberMatcher.find()) {
            response.getWriter().println("????????");
            session.invalidate();
            return;
        }

        String studentNumber = numberMatcher.group();
        String key = DigestUtils.md5Hex(String.valueOf(new Date().getTime()));
        session.setAttribute("studentNumber", studentNumber);
        session.setAttribute("key", key); //md5??
        registerData(studentNumber, key, session);
        response.sendRedirect("/");
    } else {
        response.getWriter().println("????????");
        session.invalidate();
    }

}

From source file:com.boyuanitsm.pay.alipay.util.AlipayCore.java

/** 
 * ??/* w  w  w . ja  v a2 s  . c om*/
 * @param strFilePath 
 * @param file_digest_type ?
 * @return ?
 */
public static String getAbstract(String strFilePath, String file_digest_type) throws IOException {
    PartSource file = new FilePartSource(new File(strFilePath));
    if (file_digest_type.equals("MD5")) {
        return DigestUtils.md5Hex(file.createInputStream());
    } else if (file_digest_type.equals("SHA")) {
        return DigestUtils.sha256Hex(file.createInputStream());
    } else {
        return "";
    }
}

From source file:com.noelios.restlet.ext.oauth.MemoryOAuthProvider.java

@Override
public void generateRequestToken(OAuthAccessor accessor) {
    // generate oauth_token and oauth_secret
    final String consumer_key = (String) accessor.consumer.getProperty("name");
    // generate token and secret based on consumer_key

    // for now use md5 of name + current time as token
    final String token_data = consumer_key + System.nanoTime();
    final String token = DigestUtils.md5Hex(token_data);
    // for now use md5 of name + current time + token as secret
    final String secret_data = consumer_key + System.nanoTime() + token;
    final String secret = DigestUtils.md5Hex(secret_data);

    accessor.requestToken = token;/*from  w ww  . ja va  2 s  . c o m*/
    accessor.tokenSecret = secret;
    accessor.accessToken = null;

    Context.getCurrentLogger().fine("Adding request token " + accessor);

    // add to the local cache
    this.tokens.add(accessor);
}