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.sammyun.controller.console.AdminController.java

/**
 * /*from   w w  w  .  j  a  v a2 s . c om*/
 */
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(Admin admin, Long dictSchoolId, Long[] roleIds, RedirectAttributes redirectAttributes,
        ModelMap model) {
    DictSchool dictSchool = dictSchoolService.find(dictSchoolId);
    admin.setDictSchool(dictSchool);
    admin.setRoles(new HashSet<Role>(roleService.findList(roleIds)));
    if (!isValid(admin)) {
        return ERROR_VIEW;
    }
    Admin pAdmin = adminService.find(admin.getId());
    if (pAdmin == null) {
        return ERROR_VIEW;
    }
    if (StringUtils.isNotEmpty(admin.getPassword())) {
        admin.setPassword(DigestUtils.md5Hex(admin.getPassword()));
    } else {
        admin.setPassword(pAdmin.getPassword());
    }
    if (pAdmin.getIsLocked() && !admin.getIsLocked()) {
        admin.setLoginFailureCount(0);
        admin.setLockedDate(null);
    } else {
        admin.setIsLocked(pAdmin.getIsLocked());
        admin.setLoginFailureCount(pAdmin.getLoginFailureCount());
        admin.setLockedDate(pAdmin.getLockedDate());
    }
    adminService.update(admin, "username", "loginDate", "loginIp", "orders");
    model.addAttribute("menuId", Admin.class.getSimpleName());
    addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
    return "redirect:list.ct";
}

From source file:es.uvigo.ei.sing.gc.view.models.UserViewModel.java

@Command
public void checkLogin() {
    org.hibernate.Session session = HibernateUtil.currentSession();

    final Object value = session.get(User.class, this.loginEmail);
    if (value instanceof User) {
        final User user = (User) value;

        if (Validator.isPassword(this.loginPassword)
                && user.getPassword().equals(DigestUtils.md5Hex(this.loginPassword))) {
            final Session webSession = Sessions.getCurrent();
            webSession.setAttribute("user", user);
            this.user = user;

            Executions.getCurrent().sendRedirect("home.zul");
        } else {//  www.  ja v  a  2  s . c  om
            Messagebox.show("Incorrect password.", "Invalid login", Messagebox.OK, Messagebox.ERROR);
        }
    } else {
        Messagebox.show("User does not exists.", "Invalid login", Messagebox.OK, Messagebox.ERROR);
    }
}

From source file:com.norconex.collector.core.checksum.impl.MD5DocumentChecksummer.java

@Override
public String doCreateDocumentChecksum(ImporterDocument document) {
    if (disabled) {
        return null;
    }// w  ww  .java  2 s  .c  o m

    // If fields are specified, perform checksum on them.
    if (ArrayUtils.isNotEmpty(sourceFields)) {
        ImporterMetadata meta = document.getMetadata();
        StringBuilder b = new StringBuilder();

        List<String> fields = new ArrayList<String>(Arrays.asList(sourceFields));
        // Sort to make sure field order does not affect checksum.
        Collections.sort(fields);
        for (String field : fields) {
            List<String> values = meta.getStrings(field);
            if (values != null) {
                for (String value : values) {
                    if (StringUtils.isNotBlank(value)) {
                        b.append(field).append('=');
                        b.append(value).append(';');
                    }
                }
            }
        }
        String combinedValues = b.toString();
        if (StringUtils.isNotBlank(combinedValues)) {
            String checksum = DigestUtils.md5Hex(b.toString());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Document checksum from " + StringUtils.join(sourceFields, ',') + " : " + checksum);
            }
            return checksum;
        }
        return null;
    }

    // If field is not specified, perform checksum on whole text file.
    try {
        InputStream is = document.getContent();
        String checksum = DigestUtils.md5Hex(is);
        LOG.debug("Document checksum from content: " + checksum);
        is.close();
        return checksum;
    } catch (IOException e) {
        throw new CollectorException("Cannot create document checksum on : " + document.getReference(), e);
    }
}

From source file:com.jivesoftware.jivesdk.api.definition.TileDefinitionImpl.java

private String createGuid(@Nonnull String instanceName, @Nonnull String tileDefName,
        @Nonnull List<TileField> fields) {
    String fieldsString;//from  www .j  av a 2  s  .c  om
    try {
        fieldsString = new ObjectMapper().writeValueAsString(fields);
    } catch (IOException e) {
        fieldsString = UUID.randomUUID().toString();
        log.error("Failed converting fields to a string, generated UUID instead: " + fieldsString, e);
    }

    String part1 = DigestUtils.md5Hex(instanceName + tileDefName);
    String part2 = DigestUtils.md5Hex(fieldsString);
    return part1 + part2;
}

From source file:it.univaq.incipict.profilemanager.presentation.LayoutController.java

@RequestMapping(value = "/create", method = { RequestMethod.POST })
public String crea(@ModelAttribute User user) {
    Role userRole = new Role();
    userRole.setId(Role.USER_ROLE_ID);
    user.getRoles().add(userRole);//from ww  w  . jav  a2  s  . c om
    user.setPassword(DigestUtils.md5Hex(user.getPassword()));
    userService.create(user);

    // authenticate the user and redirect on the welcome page
    new AuthenticationHolder().updateUser(userService.findByPK(user.getId()));

    return "redirect:/dashboard";
}

From source file:co.kuali.rice.kew.notes.service.impl.RiceAttachmentDataToS3ConversionImpl.java

@Override
public void execute() {
    LOG.info("Starting attachment conversion job for file_data to S3");

    if (!processRecords()) {
        return;//  ww  w . j av a  2 s  .co m
    }

    final Collection<Attachment> attachments = dataObjectService.findMatching(Attachment.class,
            QueryByCriteria.Builder.fromPredicates(PredicateFactory.isNotNull("fileLoc"))).getResults();
    attachments.forEach(attachment -> {
        try {
            final File file = new File(attachment.getFileLoc());
            if (file.isFile() && file.exists()) {
                final byte[] fsBytes = FileUtils.readFileToByteArray(file);
                String fileDataId = attachment.getFileDataId();
                final Object s3File;
                if (StringUtils.isBlank(fileDataId)) {
                    fileDataId = UUID.randomUUID().toString();
                    s3File = null;
                } else {
                    s3File = riceS3FileService.retrieveFile(fileDataId);
                }

                final byte[] s3Bytes;
                if (s3File == null) {
                    final Class<?> s3FileClass = Class.forName(RiceAttachmentDataS3Constants.S3_FILE_CLASS);
                    final Object newS3File = s3FileClass.newInstance();

                    final Method setId = s3FileClass.getMethod(RiceAttachmentDataS3Constants.SET_ID_METHOD,
                            String.class);
                    setId.invoke(newS3File, fileDataId);

                    final Method setFileContents = s3FileClass.getMethod(
                            RiceAttachmentDataS3Constants.SET_FILE_CONTENTS_METHOD, InputStream.class);
                    try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(fsBytes))) {
                        setFileContents.invoke(newS3File, stream);
                        riceS3FileService.createFile(newS3File);
                    }

                    s3Bytes = getBytesFromS3File(riceS3FileService.retrieveFile(fileDataId));
                } else {
                    if (LOG.isDebugEnabled()) {
                        final Method getFileMetaData = s3File.getClass()
                                .getMethod(RiceAttachmentDataS3Constants.GET_FILE_META_DATA_METHOD);
                        LOG.debug("data found in S3, existing id: " + fileDataId + " attachment id "
                                + attachment.getAttachmentId() + " metadata: "
                                + getFileMetaData.invoke(s3File));
                    }
                    s3Bytes = getBytesFromS3File(s3File);
                }

                if (s3Bytes != null && fsBytes != null) {
                    final String s3MD5 = DigestUtils.md5Hex(s3Bytes);
                    final String dbMD5 = DigestUtils.md5Hex(fsBytes);
                    if (!Objects.equals(s3MD5, dbMD5)) {
                        LOG.error("S3 data MD5: " + s3MD5 + " does not equal DB data MD5: " + dbMD5
                                + " for id: " + fileDataId + " attachment id " + attachment.getAttachmentId());
                    } else {
                        attachment.setFileDataId(fileDataId);
                        if (isDeleteFromFileSystem()) {
                            attachment.setFileLoc(null);
                        }
                        try {
                            dataObjectService.save(attachment, PersistenceOption.FLUSH);
                        } finally {
                            if (isDeleteFromFileSystem()) {
                                file.delete();
                            }
                        }
                    }
                }
            }
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IOException
                | ClassNotFoundException | InstantiationException e) {
            throw new RuntimeException(e);
        }
    });
    LOG.info("Finishing attachment conversion job for file_data to S3");
}

From source file:Index.RegisterUserServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from   www  .  j  a v  a  2  s . c  o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    PrintWriter out = response.getWriter();

    try {
        String errorMessage;

        if (request.getParameter("user") != null && request.getParameter("password") != null
                && request.getParameter("email") != null && request.getParameter("passwordConfirmation") != null
                && request.getParameter("name") != null && request.getParameter("address") != null
                && request.getParameter("lastName") != null && request.getParameter("dateBorn") != null) {

            String user = request.getParameter("user");
            String password = request.getParameter("password");
            String passwordConfirmation = request.getParameter("passwordConfirmation");
            String email = request.getParameter("email");
            String name = request.getParameter("name");
            String address = request.getParameter("address");
            String lastName = request.getParameter("lastName");
            String dateBorn = request.getParameter("dateBorn");

            if (user.equalsIgnoreCase("") || password.equalsIgnoreCase("")
                    || passwordConfirmation.equalsIgnoreCase("") || email.equalsIgnoreCase("")
                    || name.equalsIgnoreCase("")) {

                errorMessage = "Ingrese todos los datos.";
                request.setAttribute("error", errorMessage);
                request.setAttribute("funcionalidad", "Registro");

                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            } else {
                if (password.equals(passwordConfirmation)) {
                    QuickOrderWebService webService = new QuickOrderWebService();
                    ControllerInterface port = webService.getQuickOrderWebServicePort();
                    webservice.Cliente listCli = port.infoCliente(user);

                    if (listCli != null && listCli.getApellido() != null) {

                        errorMessage = "Ya existe un usuario con ese nickname";
                        request.setAttribute("error", errorMessage);
                        request.setAttribute("funcionalidad", "Registro");
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    } else {
                        webservice.Cliente usr = new webservice.Cliente();
                        usr.setNickname(user);
                        usr.setNombre(name);
                        usr.setEmail(email);
                        usr.setDireccion(address);
                        usr.setImagen(user + ".jpg");
                        usr.setApellido(lastName);

                        //PORCEDIMIENTO PARA ENCRIPTAR LA CLAVE INGRESADA CUANDO INICIA SESIN UN USUARIO.
                        String encriptMD5 = DigestUtils.md5Hex(password);
                        password = "md5:" + encriptMD5;

                        usr.setPassword(password);
                        Date dt;
                        try {
                            dt = new Date(dateBorn);
                        } catch (Exception ex) {
                            dt = Date.from(Instant.now());
                        }

                        GregorianCalendar c = new GregorianCalendar();
                        c.setTime(dt);
                        XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);
                        usr.setFechaNac(date2);

                        String result = port.registrarCliente(usr);

                        if (result.equals("")) {
                            request.setAttribute("error", null);
                            request.setAttribute("funcionalidad", "Imagen");
                            request.getSession().setAttribute("userName", user);
                        } else {
                            request.setAttribute("error", "Surgio un error al registrar el cliente");
                            request.setAttribute("funcionalidad", "Registro");
                        }
                        request.getRequestDispatcher("/Login.jsp").forward(request, response);
                    }
                } else {
                    errorMessage = "Las contraseas no cohinciden";
                    request.setAttribute("error", errorMessage);
                    request.setAttribute("funcionalidad", "Registro");
                    request.getRequestDispatcher("/Login.jsp").forward(request, response);
                }

            }
        } else {
            errorMessage = "Error al realizar el registro.";
            request.setAttribute("error", errorMessage);
            request.setAttribute("funcionalidad", "Registro");
            request.getRequestDispatcher("/Login.jsp").forward(request, response);
        }
    } catch (Exception ex) {
        out.print("Error en proceso de registro: " + ex.getMessage());
    } finally {
        out.close();
    }
}

From source file:de.undercouch.gradle.tasks.download.AuthenticationTest.java

@Override
protected Handler[] makeHandlers() throws IOException {
    ContextHandler authenticationHandler = new ContextHandler("/" + AUTHENTICATE) {
        @Override//w  ww.  j  ava  2 s.c o  m
        public void handle(String target, HttpServletRequest request, HttpServletResponse response,
                int dispatch) throws IOException, ServletException {
            String ahdr = request.getHeader("Authorization");
            if (ahdr == null) {
                if (!basic) {
                    response.setHeader("WWW-Authenticate",
                            "Digest realm=\"" + REALM + "\"," + "nonce=\"" + NONCE + "\"");
                }
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No authorization header given");
                return;
            }

            if (basic) {
                checkBasic(ahdr, response);
            } else {
                checkDigest(ahdr, response);
            }
        }

        private void checkBasic(String ahdr, HttpServletResponse response) throws IOException {
            if (!ahdr.startsWith("Basic ")) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                        "Authorization header does not start with 'Basic '");
                return;
            }

            ahdr = ahdr.substring(6);
            ahdr = new String(Base64.decodeBase64(ahdr));
            String[] userAndPass = ahdr.split(":");
            if (!USERNAME.equals(userAndPass[0]) || !PASSWORD.equals(userAndPass[1])) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong credentials");
                return;
            }

            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.write("auth: " + ahdr);
            rw.close();
        }

        private void checkDigest(String ahdr, HttpServletResponse response) throws IOException {
            if (!ahdr.startsWith("Digest ")) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                        "Authorization header does not start with 'Digest '");
                return;
            }

            String expectedResponse = USERNAME + ":" + REALM + ":" + PASSWORD;
            expectedResponse = DigestUtils.md5Hex(expectedResponse);

            ahdr = ahdr.substring(7);
            String[] parts = ahdr.split(",");
            for (String p : parts) {
                if (p.startsWith("username") && !p.equals("username=\"" + USERNAME + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong username");
                    return;
                } else if (p.startsWith("nonce") && !p.equals("nonce=\"" + NONCE + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong nonce");
                    return;
                } else if (p.startsWith("realm") && !p.equals("realm=\"" + REALM + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong realm");
                    return;
                } else if (p.startsWith("response") && !p.equals("response=\"" + expectedResponse + "\"")) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Wrong response");
                    return;
                }
            }

            response.setStatus(200);
            PrintWriter rw = response.getWriter();
            rw.close();
        }
    };
    return new Handler[] { authenticationHandler };
}

From source file:beans.ClienteBean.java

public void login(ActionEvent event) {
    RequestContext context = RequestContext.getCurrentInstance();
    FacesMessage message = null;//from   w  w  w.j a  va 2  s  .  c  o  m
    Cliente c = clienteFacade.find(rut);
    clave = DigestUtils.md5Hex(clave);

    if (c != null && clave != null && clave.equals(c.getClave()) && confirmarRut()) {
        loggedIn = true;
        message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenido(a) ",
                c.getNombre() + " " + c.getApellidoPaterno());
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("cliente", c);
        FacesContext.getCurrentInstance().addMessage(null, message);
        context.addCallbackParam("loggedIn", loggedIn);
        context.addCallbackParam("view", "index.xhtml");
    } else {
        loggedIn = false;
        message = new FacesMessage(FacesMessage.SEVERITY_WARN, "Error", "RUT o Clave no validas");
        FacesContext.getCurrentInstance().addMessage(null, message);
        context.addCallbackParam("view", "logueo.xhtml");
    }

}

From source file:cn.wanghaomiao.seimi.def.DefaultRedisQueue.java

@Override
public boolean isProcessed(Request req) {
    Jedis jedis = null;//from ww w  .ja  v a2  s. c o m
    boolean res = false;
    try {
        jedis = getWClient();
        String sign = DigestUtils.md5Hex(req.getUrl());
        res = jedis.sismember(setNamePrefix + req.getCrawlerName(), sign);
    } catch (Exception e) {
        logger.warn(e.getMessage());
        refresh();
    } finally {
        if (jedis != null) {
            jedis.close();
        }
    }
    return res;
}