List of usage examples for org.apache.commons.codec.binary Hex encodeHex
public static char[] encodeHex(byte[] data)
From source file:com.zimbra.cs.mailbox.ACL.java
public static String generateAccessKey() { SecureRandom random = new SecureRandom(); byte[] key = new byte[ACCESSKEY_SIZE_BYTES]; random.nextBytes(key);/*from www . java 2 s .c o m*/ // in the form of e.g. 8d159aed5fb9431d8ac52db5e20baafb return new String(Hex.encodeHex(key)); }
From source file:es.javocsoft.android.lib.toucan.client.ToucanClient.java
private static String generateSHA1(String data) { return new String(Hex.encodeHex(DigestUtils.sha(data))); }
From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java
private String generateToken(String attachLocation) { if (StringUtils.isEmpty(attachment_key)) return ""; SecretKeySpec keySpec = new SecretKeySpec(attachment_key.getBytes(), "HmacMD5"); Mac mac;/*from w w w . jav a 2 s.c om*/ try { mac = Mac.getInstance("HmacMD5"); mac.init(keySpec); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } String timestamp = "" + (getSystemTime() + serverTimeDelta); byte[] raw = mac.doFinal((timestamp + attachLocation).getBytes()); return new String(Hex.encodeHex(raw)) + ":" + timestamp; }
From source file:com.edgenius.core.repository.SimpleRepositoryServiceImpl.java
@SuppressWarnings("unchecked") public List<FileNode> saveFile(ITicket ticket, FileNode attachment, boolean md5DigestRequired, boolean discardSaveDiffMd5) throws RepositoryException, RepositoryTiemoutExcetpion, RepositoryQuotaException { List<FileNode> checkedIn = new ArrayList<FileNode>(); if (!attachment.isBulkZip()) { //TODO: does it need return only check-in successfully? checkedIn.add(attachment);// w w w.ja va 2 s .c om } else { //process bulk upload String dir = null; try { dir = FileUtil.createTempDirectory(TMP_BULK_CHECKIN); ZipFileUtil.expandZipToFolder(attachment.getFile(), dir); //retrieve all files and check-in Collection<File> files = FileUtils.listFiles(new File(dir), null, true); if (files != null) { MimetypesFileTypeMap mineMap = new MimetypesFileTypeMap(); for (File file : files) { try { FileNode node = new FileNode(); //use same comment for all upload node.setComment(attachment.getComment()); node.setShared(attachment.isShared()); node.setFile(new FileInputStream(file)); node.setFilename(FileUtil.getFileName(file.getName())); node.setContentType(mineMap.getContentType(file)); node.setType(RepositoryService.TYPE_ATTACHMENT); node.setIdentifier(attachment.getIdentifier()); node.setCreateor(attachment.getCreateor()); node.setStatus(attachment.getStatus()); node.setSize(file.length()); node.setBulkZip(false); checkedIn.addAll(saveFile(ticket, node, md5DigestRequired, discardSaveDiffMd5)); } catch (Exception e) { log.error("Unable process some files in bulk zip", e); } } } } catch (FileUtilException e) { throw new RepositoryException("Unable create temp dir for bulk upload", e); } catch (ZipFileUtilException e) { throw new RepositoryException("Unable unzip bulk uploaded file", e); } finally { if (dir != null) { try { FileUtil.deleteDir(dir); } catch (IOException e) { log.error("Unable to delete directory " + dir); } } } return checkedIn; } //TODO: consider thread-safe if (!ticket.isAllowWrite()) { String error = "Workspace has not write permission " + ticket.getSpacename() + " for identifierUuid " + attachment.getIdentifier(); log.warn(error); throw new RepositoryException("Permission denied: " + error); } checkSpaceQuota(ticket, attachment.getSize()); try { //lock at identifier level so that multiple users upload will still keep version works. acquireLock(ticket.getSpacename(), attachment.getIdentifier(), null); CrWorkspace crW = getCrWorkspace(ticket); List<CrFileNode> nodes = getBaseNodes(attachment.getType(), attachment.getIdentifier()); CrFileNode existFile = null, filenode = new CrFileNode(); log.info("File is going to save to " + ticket.getSpacename() + ""); //page->attachment->file->resource for (Iterator<CrFileNode> iter = nodes.iterator(); iter.hasNext();) { CrFileNode node = iter.next(); //if file is under same Identifier(page), and file name is same, then version the item. if (StringUtils.equalsIgnoreCase(node.getFilename(), attachment.getFilename())) { existFile = node; break; } } if (existFile != null) { //increase version filenode.setVersion(existFile.getVersion() + 1); filenode.setNodeUuid(existFile.getNodeUuid()); log.info("FileNode is appending version to a existed node :" + filenode.getNodeUuid() + " with new version " + filenode.getVersion()); } else { //this node name is useless now, so just create a random unique one filenode.setVersion(1); filenode.setNodeUuid(UUID.randomUUID().toString()); //TODO: encoding is important for lucene index building and search, here just set empty. filenode.setEncoding(""); File id = new File(FileUtil.getFullPath(homeDir, crW.getSpaceUuid(), attachment.getType(), attachment.getIdentifier(), filenode.getNodeUuid())); if (id.exists()) { throw new RepositoryException("Node uuid directory already exist"); } if (!id.mkdirs()) { throw new RepositoryException( "Node uuid directory create failed. Full path is " + id.getAbsolutePath()); } log.info("FileNode is creating a new node :" + filenode.getNodeUuid()); } filenode.setSpaceUname(ticket.getSpacename()); resetMetaData(attachment, filenode); String verRootDir = FileUtil.getFullPath(homeDir, crW.getSpaceUuid(), filenode.getNodeType(), filenode.getIdentifierUuid(), filenode.getNodeUuid(), new Integer(filenode.getVersion()).toString()); File verFile = new File(verRootDir); if (!verFile.mkdirs()) { //this is just ensure the case if MD5 is duplicated, system try to delete that version directory but failed... //at that case, only empty directory left there. if (verFile.exists() && verFile.list().length > 0) { throw new RepositoryException( "Node uuid " + filenode.getNodeUuid() + " can not create version directory " + Integer.valueOf(filenode.getVersion()).toString()); } } OutputStream file = null; File ofile = new File(verRootDir, DEFAULT_FILE_NAME); try { file = new FileOutputStream(ofile); //save physical file byte[] content = new byte[1024 * 1024]; int len; md5DigestRequired = md5DigestRequired && (md5Digest != null); while ((len = attachment.getFile().read(content)) != -1) { if (md5DigestRequired) { md5Digest.update(content, 0, len); } file.write(content, 0, len); } file.flush(); if (md5DigestRequired) { filenode.setMd5Digest(new String(Hex.encodeHex(md5Digest.digest()))); } if (discardSaveDiffMd5 && filenode.getVersion() > 1) { //compare if (filenode.getMd5Digest().equals(existFile.getMd5Digest())) { //tell to delete version directory as well in finally{}! checkedIn = null; log.info("MD5 is same and ignore checked in"); return null; } } //create new record in DB crFileNodeDAO.saveOrUpdate(filenode); //set back NodeUuid and Version to attachment attachment.setNodeUuid(filenode.getNodeUuid()); attachment.setVersion(Integer.valueOf(filenode.getVersion()).toString()); attachment.setDate(filenode.getModifiedDate().getTime()); log.debug("File node create on " + filenode.getModifiedDate() + " by version " + attachment.getVersion()); } catch (Exception e) { throw new RepositoryException("Failed save node " + e); } finally { if (file != null) { try { file.close(); } catch (Exception e) { log.error("Unable to close uploaded file"); } if (checkedIn == null) { if (!ofile.delete()) { log.error("Version file {} deleted failed when MD5 duplicated case", ofile.getAbsolutePath()); ofile.deleteOnExit(); } } } if (checkedIn == null) { //ignored check-in if (!verFile.delete()) { log.error("Version directory {} deleted failed when MD5 duplicated case", verRootDir); } } } } finally { releaseLock(ticket.getSpacename(), attachment.getIdentifier(), null); if (attachment.getFile() != null) { try { attachment.getFile().close(); } catch (Exception e) { } } } return checkedIn; }
From source file:ca.sqlpower.architect.enterprise.ArchitectClientSideSession.java
/** * This method can update any users password on the server given the correct * old password and done by a user with the privileges to change the user's * password./*from w w w . j ava 2 s . c o m*/ * * @param session * The client session that has the correct server information to * post requests to the server. * @param username * The user name of the user to update. * @param oldPassword * The old password of the user to validate that the password can * be updated correctly. * @param newPassword * The new password to update to. * @param upf * A user prompter to display message and error information to * the user as necessary. */ public void updateUserPassword(User user, String oldPassword, String newPassword, UserPrompterFactory upf) { SPServerInfo serviceInfo = getProjectLocation().getServiceInfo(); HttpClient client = ClientSideSessionUtils.createHttpClient(serviceInfo, cookieStore); MessageDigest digester; try { digester = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } try { JSONObject begin = new JSONObject(); begin.put("uuid", JSONObject.NULL); begin.put("method", "begin"); JSONObject persist = new JSONObject(); persist.put("uuid", user.getUUID()); persist.put("propertyName", "password"); persist.put("type", Datatype.STRING.toString()); if (oldPassword == null) { persist.put("method", "persistProperty"); } else { persist.put("method", "changeProperty"); persist.put("oldValue", new String(Hex.encodeHex(digester.digest(oldPassword.getBytes())))); } persist.put("newValue", new String(Hex.encodeHex(digester.digest(newPassword.getBytes())))); JSONObject commit = new JSONObject(); commit.put("uuid", JSONObject.NULL); commit.put("method", "commit"); JSONArray transaction = new JSONArray(); transaction.put(begin); transaction.put(persist); transaction.put(commit); URI serverURI = new URI("http", null, serviceInfo.getServerAddress(), serviceInfo.getPort(), serviceInfo.getPath() + "/" + ClientSideSessionUtils.REST_TAG + "/project/system", "currentRevision=" + getCurrentRevisionNumber(), null); HttpPost postRequest = new HttpPost(serverURI); postRequest.setEntity(new StringEntity(transaction.toString())); postRequest.setHeader("Content-Type", "application/json"); HttpUriRequest request = postRequest; JSONMessage result = client.execute(request, new JSONResponseHandler()); if (result.getStatusCode() != 200) { logger.warn("Failed password change"); if (result.getStatusCode() == 412) { upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); } else { upf.createUserPrompter( "Could not change the password due to the following: " + result.getBody() + " See logs for more details.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK") .promptUser(""); } } else { upf.createUserPrompter( "Password successfully changed. Please log into open projects" + " with your new password.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK") .promptUser(""); } } catch (AccessDeniedException ex) { logger.warn("Failed password change", ex); upf.createUserPrompter("The password you have entered is incorrect.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); } catch (Exception ex) { logger.warn("Failed password change", ex); upf.createUserPrompter( "Could not change the password due to the following: " + ex.getMessage() + " See logs for more details.", UserPromptType.MESSAGE, UserPromptOptions.OK, UserPromptResponse.OK, "OK", "OK").promptUser(""); } }
From source file:edu.ncsa.sstde.indexing.postgis.PostgisIndexer.java
private String setInsertValue(Object[] varNames, int[] types, PreparedStatement statement, BindingSet bindingSet) throws SQLException { for (int i = 0; i < varNames.length; i++) { Value value = bindingSet.getValue(varNames[i].toString()); statement.setObject(i + 2, getSQLValue(bindingSet.getValue(varNames[i].toString()), types[i])); DIGEST.update(value.toString().getBytes()); }//from ww w . ja va 2s . co m String result = new String(Hex.encodeHex(DIGEST.digest())); statement.setString(1, result); return result; }
From source file:edu.hawaii.soest.pacioos.text.SimpleTextSource.java
/** * Validate the sample string against the sample pattern provided in the configuration * //from w w w. j a va 2 s . c o m * @param sample the sample string to validate * @return isValid true if the sample string match the sample pattern */ public boolean validateSample(String sample) { boolean isValid = false; // test the line for the expected data pattern Matcher matcher = this.dataPattern.matcher(sample); if (matcher.matches()) { isValid = true; } else { String sampleAsReadableText = sample.replaceAll("\\x0D", "0D"); sampleAsReadableText = sampleAsReadableText.replaceAll("\\x0A", "0A"); log.warn("The sample did not validate, and was not sent. The text was: " + sampleAsReadableText); } try { log.debug("Sample bytes: " + new String(Hex.encodeHex(sample.getBytes("US-ASCII")))); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } log.debug("Data pattern is: '" + this.dataPattern.toString() + "'"); log.debug("Sample is : " + sample); return isValid; }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Write//from w ww . ja v a2 s. co m * * @param req * the HttpServletRequest object that contains the request the * client made of the servlet * @param resp * the HttpServletResponse object that contains the response the * servlet returns to the client * @throws IOException * if an input or output error occurs while the servlet is * handling the PUT request * @throws ServletException * if the request for the PUT cannot be handled */ @SuppressWarnings("unchecked") public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { OutputStream out = null; try { S3ObjectRequest or; try { or = S3ObjectRequest.create(req, resolvedHost(), (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR)); } catch (InvalidAccessKeyIdException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId"); return; } catch (InvalidSecurityException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } catch (RequestTimeTooSkewedException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed"); return; } catch (SignatureDoesNotMatchException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch"); return; } catch (AuthenticatorException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } logger.debug("S3ObjectRequest: " + or); CanonicalUser requestor = or.getRequestor(); if (or.getKey() != null) { String value; long contentLength; MessageDigest messageDigest = MessageDigest.getInstance("MD5"); DigestOutputStream digestOutputStream = null; S3Object oldS3Object = null; S3Object s3Object; StorageService storageService; Bucket bucket; String bucketName = or.getBucket(); String key = or.getKey(); if (!isValidKey(key)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong"); return; } storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // write access control policy Acp acp; CanonicalUser owner; s3Object = storageService.load(bucketName, key); if (s3Object == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } acp = s3Object.getAcp(); try { acp.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // save owner owner = acp.getOwner(); try { acp = Acp.decode(req.getInputStream()); } catch (IOException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError"); return; } // maintain owner acp.setOwner(owner); s3Object.setAcp(acp); storageService.store(s3Object); } else { // make sure requestor can "WRITE" to the bucket try { bucket = storageService.loadBucket(bucketName); bucket.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { oldS3Object = storageService.load(bucket.getName(), key); } catch (DataRetrievalFailureException e) { // ignore } // create a new S3Object for this request to store an object try { s3Object = storageService.createS3Object(bucket, key, requestor); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } out = s3Object.getOutputStream(); digestOutputStream = new DigestOutputStream(out, messageDigest); // Used instead of req.getContentLength(); because Amazon // limit is 5 gig, which is bigger than an int value = req.getHeader("Content-Length"); if (value == null) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength"); return; } contentLength = Long.valueOf(value).longValue(); if (contentLength > 5368709120L) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge"); return; } long written = 0; int count; byte[] b = new byte[4096]; ServletInputStream in = req.getInputStream(); while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) { digestOutputStream.write(b, 0, count); written += count; } digestOutputStream.flush(); if (written != contentLength) { // transmission truncated if (out != null) { out.close(); out = null; } if (digestOutputStream != null) { digestOutputStream.close(); digestOutputStream = null; } // clean up storageService.remove(s3Object); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody"); return; } s3Object.setContentDisposition(req.getHeader("Content-Disposition")); s3Object.setContentLength(contentLength); s3Object.setContentMD5(req.getHeader("Content-MD5")); value = req.getContentType(); logger.debug("Put - Content-Type: " + value); if (value == null) { value = S3Object.DEFAULT_CONTENT_TYPE; } s3Object.setContentType(value); logger.debug("Put - get content-type: " + s3Object.getContentType()); s3Object.setLastModified(System.currentTimeMillis()); // metadata int prefixLength = HEADER_PREFIX_USER_META.length(); String name; for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) { String headerName = (String) headerNames.nextElement(); if (headerName.startsWith(HEADER_PREFIX_USER_META)) { name = headerName.substring(prefixLength).toLowerCase(); for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) { value = (String) headers.nextElement(); s3Object.addMetadata(name, value); } } } // calculate ETag, hex encoding of MD5 value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest())); resp.setHeader("ETag", value); s3Object.setETag(value); grantCannedAccessPolicies(req, s3Object.getAcp(), requestor); // NOTE: This could be reengineered to have a two-phase // commit. if (oldS3Object != null) { storageService.remove(oldS3Object); } storageService.store(s3Object); } } else if (or.getBucket() != null) { StorageService storageService; Bucket bucket; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // write access control policy Acp acp; CanonicalUser owner; logger.debug("User is providing new ACP for bucket " + or.getBucket()); try { bucket = storageService.loadBucket(or.getBucket()); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } acp = bucket.getAcp(); try { acp.canWrite(requestor); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // save owner owner = acp.getOwner(); try { acp = Acp.decode(req.getInputStream()); } catch (IOException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError"); return; } // maintain owner acp.setOwner(owner); bucket.setAcp(acp); logger.debug("Saving bucket ACP"); logger.debug("ACP: " + Acp.encode(bucket.getAcp())); storageService.storeBucket(bucket); } else { // validate bucket String bucketName = or.getBucket(); if (!isValidBucketName(bucketName)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName"); return; } try { bucket = storageService.createBucket(bucketName, requestor); } catch (BucketAlreadyExistsException e) { resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists"); return; } grantCannedAccessPolicies(req, bucket.getAcp(), requestor); storageService.storeBucket(bucket); } } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); logger.error("Unable to use MD5", e); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError"); } catch (IOException e) { e.printStackTrace(); throw e; } finally { if (out != null) { out.close(); out = null; } } }
From source file:net.sf.iqser.plugin.csv.CsvContentProvider.java
private String createContentUrlWithHashFromRawRecord(String rawRecord) throws UnsupportedEncodingException { byte[] digest = digestForContenUrlAsHashFromRecord.digest(rawRecord.getBytes()); return createContentUrl(null, digestForContenUrlAsHashFromRecord.getAlgorithm(), String.valueOf(Hex.encodeHex(digest))); }
From source file:com.linkedin.databus.core.DbusEventV1.java
@Override public String toString() { if (null == _buf) { return "_buf=null"; }//from w w w.j ava 2 s. c o m boolean valid = true; try { valid = isValid(true); } catch (Exception ex) { LOG.error("DbusEventV1.toString() : Got Exception while trying to validate the event ", ex); valid = false; } if (!valid) { StringBuilder sb = new StringBuilder("Position: "); sb.append(_position); sb.append(", _buf: "); sb.append(null != _buf ? _buf.toString() : "null"); sb.append(", validity: false; hexDump:"); if (null != _buf && _position >= 0) { sb.append(StringUtils.hexdumpByteBufferContents(_buf, _position, 100)); } return sb.toString(); } StringBuilder sb = new StringBuilder(200); sb.append("Position=").append(_position).append(";Version=").append(getVersion()) .append(";isEndOfPeriodMarker=").append(isEndOfPeriodMarker()).append(";HeaderCrc=") .append(headerCrc()).append(";Length=").append(size()).append(";Key="); if (isKeyString()) { sb.append(new String(keyBytes())); } else { sb.append(key()); } sb.append(";Sequence=").append(sequence()).append(";LogicalPartitionId=").append(logicalPartitionId()) .append(";PhysicalPartitionId=").append(physicalPartitionId()).append(";Timestamp=") .append(timestampInNanos()).append(";SrcId=").append(srcId()).append(";SchemaId=") .append(Hex.encodeHex(schemaId())).append(";ValueCrc=").append(bodyCrc()); //Do not output value - as it's too long. /* .append(";Value = "); try { sb.append(Utils.byteBufferToString(value(), "UTF-8")); } catch (UnsupportedEncodingException e) { sb.append(value().toString()); } */ return sb.toString(); }