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

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

Introduction

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

Prototype

@Deprecated
    public static String shaHex(String data) 

Source Link

Usage

From source file:org.appcelerator.titanium.util.TiResponseCache.java

@Override
public CacheResponse get(URI uri, String rqstMethod, Map<String, List<String>> rqstHeaders) throws IOException {
    if (uri == null || cacheDir == null)
        return null;

    // Get our key, which is a hash of the URI
    String hash = DigestUtils.shaHex(uri.toString());

    // Make our cache files
    File hFile = new File(cacheDir, hash + HEADER_SUFFIX);
    File bFile = new File(cacheDir, hash + BODY_SUFFIX);

    if (!bFile.exists() || !hFile.exists()) {
        return null;
    }/*from ww w .java2 s . com*/

    // Read in the headers
    Map<String, List<String>> headers = new HashMap<String, List<String>>();
    BufferedReader rdr = new BufferedReader(new FileReader(hFile), 1024);
    for (String line = rdr.readLine(); line != null; line = rdr.readLine()) {
        String keyval[] = line.split("=", 2);
        if (!headers.containsKey(keyval[0])) {
            headers.put(keyval[0], new ArrayList<String>());
        }
        headers.get(keyval[0]).add(keyval[1]);
    }
    rdr.close();

    // Update the access log
    hFile.setLastModified(System.currentTimeMillis());

    // Respond with the cache
    return new TiCacheResponse(headers, new FileInputStream(bFile));
}

From source file:org.appcelerator.titanium.util.TiResponseCache.java

@Override
public CacheRequest put(URI uri, URLConnection conn) throws IOException {
    if (cacheDir == null)
        return null;

    // Make sure the cacheDir exists, in case user clears cache while app is running
    if (!cacheDir.exists()) {
        cacheDir.mkdirs();//from   ww w.j av  a  2s .  c om
    }

    // Gingerbread 2.3 bug: getHeaderField tries re-opening the InputStream
    // getHeaderFields() just checks the response itself
    Map<String, List<String>> headers = makeLowerCaseHeaders(conn.getHeaderFields());
    String cacheControl = getHeader(headers, "cache-control");
    if (cacheControl != null && cacheControl.matches("^.*(no-cache|no-store|must-revalidate).*")) {
        return null; // See RFC-2616
    }

    boolean skipTransferEncodingHeader = false;
    String tEncoding = getHeader(headers, "transfer-encoding");
    if (tEncoding != null && tEncoding.toLowerCase().equals("chunked")) {
        skipTransferEncodingHeader = true; // don't put "chunked" transfer-encoding into our header file, else the http connection object that gets our header information will think the data starts with a chunk length specification
    }

    // Form the headers and generate the content length
    String newl = System.getProperty("line.separator");
    long contentLength = getHeaderInt(headers, "content-length", 0);
    StringBuilder sb = new StringBuilder();
    for (String hdr : headers.keySet()) {
        if (!skipTransferEncodingHeader || !hdr.equals("transfer-encoding")) {
            for (String val : headers.get(hdr)) {
                sb.append(hdr);
                sb.append("=");
                sb.append(val);
                sb.append(newl);
            }
        }
    }
    if (contentLength + sb.length() > maxCacheSize) {
        return null;
    }

    // Work around an android bug which gives us the wrong URI
    try {
        uri = conn.getURL().toURI();
    } catch (URISyntaxException e) {
    }

    // Get our key, which is a hash of the URI
    String hash = DigestUtils.shaHex(uri.toString());

    // Make our cache files
    File hFile = new File(cacheDir, hash + HEADER_SUFFIX);
    File bFile = new File(cacheDir, hash + BODY_SUFFIX);

    // Write headers synchronously
    FileWriter hWriter = new FileWriter(hFile);
    try {
        hWriter.write(sb.toString());
    } finally {
        hWriter.close();
    }

    synchronized (this) {
        // Don't add it to the cache if its already being written
        if (!bFile.createNewFile()) {
            return null;
        }
        return new TiCacheRequest(uri, bFile, hFile, contentLength);
    }
}

From source file:org.appcelerator.titanium.util.TiResponseCache.java

private static final void fireCacheCompleted(URI uri) {
    synchronized (completeListeners) {
        String hash = DigestUtils.shaHex(uri.toString());
        if (completeListeners.containsKey(hash)) {
            for (CompleteListener listener : completeListeners.get(hash)) {
                listener.cacheCompleted(uri);
            }//from  w w w .jav  a 2 s . co m
            completeListeners.remove(hash);
        }
    }
}

From source file:org.artifactory.storage.db.ha.itest.dao.ArtifactoryServersDaoTest.java

public void hasServerNonExistingServer() throws SQLException {
    assertFalse(dao.hasArtifactoryServer(DigestUtils.shaHex("nosuchserver")));
}

From source file:org.artifactory.storage.db.ha.itest.dao.ArtifactoryServersDaoTest.java

public void loadServer() throws SQLException {
    ArtifactoryServer insertedServer = new ArtifactoryServer(DigestUtils.shaHex("create'n'load"), 1000000L,
            "152.45.32.56", 5700, ArtifactoryServerState.RUNNING, ArtifactoryServerRole.STANDALONE,
            System.currentTimeMillis(), "6.1", 2, 3L, ArtifactoryRunningMode.OSS, LICENSE_HASH);

    dao.createArtifactoryServer(insertedServer);

    ArtifactoryServer loadedServer = dao.getArtifactoryServer(DigestUtils.shaHex("create'n'load"));

    assertTrue(EqualsBuilder.reflectionEquals(insertedServer, loadedServer), "Orig and copy differ");
}

From source file:org.artifactory.storage.db.ha.itest.dao.ArtifactoryServersDaoTest.java

public void updateServer() throws SQLException {
    ArtifactoryServer server = new ArtifactoryServer(DigestUtils.shaHex("toupdate"), 1000000L, "152.45.32.56",
            5700, ArtifactoryServerState.RUNNING, ArtifactoryServerRole.PRIMARY, System.currentTimeMillis(),
            "6.1", 2, 3L, ArtifactoryRunningMode.OSS, LICENSE_HASH);
    dao.createArtifactoryServer(server);

    ArtifactoryServer updatedServer = new ArtifactoryServer(DigestUtils.shaHex("toupdate"), 11000000L,
            "152.45.32.57", 5700, ArtifactoryServerState.STOPPED, ArtifactoryServerRole.STANDALONE,
            System.currentTimeMillis(), "6.2", 3, 2L, ArtifactoryRunningMode.OSS, LICENSE_HASH);

    int updateCount = dao.updateArtifactoryServer(updatedServer);
    assertEquals(updateCount, 1);//from  ww w.  j  av  a2  s  . c  o m

    ArtifactoryServer serverFromDb = dao.getArtifactoryServer(server.getServerId());
    assertTrue(EqualsBuilder.reflectionEquals(updatedServer, serverFromDb));
}

From source file:org.artificer.common.maven.MavenGavInfo.java

public static MavenGavInfo fromCommandLine(String gavArg, File file) throws Exception {
    String[] split = gavArg.split(":");
    String groupId = split[0];/*from   ww w  .  j a  v  a2  s.  co m*/
    String artifactId = split[1];
    String version = split[2];
    String filename = file.getName();
    if (file.getName().endsWith(".tmp")) {
        filename = filename.substring(0, filename.indexOf(".jar") + 4);
    }
    String type = null;
    if (filename.endsWith(".sha1")) {
        type = filename.substring(0, filename.length() - 5);
        type = type.substring(type.lastIndexOf('.') + 1) + ".sha1";
    } else if (filename.endsWith(".md5")) {
        type = filename.substring(0, filename.length() - 4);
        type = type.substring(type.lastIndexOf('.') + 1) + ".md5";
    } else if (filename.contains(".")) {
        type = filename.substring(filename.lastIndexOf('.') + 1);
    }
    String classifier = null;
    if (split.length >= 5) {
        classifier = split[5];
    }
    boolean snapshot = version != null && version.endsWith("-SNAPSHOT");
    String snapshotId = null;
    if (snapshot && !filename.contains(version)) {
        snapshotId = extractSnapshotId(filename, version, type, classifier);
    }
    // MD5 hash
    InputStream is = new FileInputStream(file);
    String md5 = DigestUtils.md5Hex(is);
    IOUtils.closeQuietly(is);
    // SHA-1 hash
    is = new FileInputStream(file);
    String sha1 = DigestUtils.shaHex(is);
    IOUtils.closeQuietly(is);

    MavenGavInfo gav = new MavenGavInfo();
    gav.setName(filename);
    gav.setGroupId(groupId);
    gav.setArtifactId(artifactId);
    gav.setVersion(version);
    gav.setClassifier(classifier);
    gav.setType(type);
    gav.setSnapshot(snapshot);
    gav.setSnapshotId(snapshotId);
    gav.setMd5(md5);
    gav.setSha1(sha1);
    return gav;
}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

private void processDocument(ArtificerDocumentArtifact artificerArtifact, ArtifactContent content)
        throws Exception {
    InputStream inputStream = null;
    try {//from  w  w w.  j  a v  a 2s. c o m
        if (content != null) {
            artificerArtifact.setContentSize(content.getSize());
            inputStream = content.getInputStream();
            String sha1Hash = DigestUtils.shaHex(inputStream);
            artificerArtifact.setContentHash(sha1Hash);
        } else {
            artificerArtifact.setContentSize(0);
            artificerArtifact.setContentHash("");
        }
    } finally {
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

From source file:org.artificer.repository.jcr.JCRArtifactPersister.java

private void persistDocumentProperties(Node artifactNode, ArtifactType artifactType) throws Exception {
    // Document/* w w  w  . ja va2 s. co  m*/
    if (DocumentArtifactType.class.isAssignableFrom(artifactType.getArtifactType().getTypeClass())) {
        artifactNode.setProperty(JCRConstants.SRAMP_CONTENT_TYPE, artifactType.getMimeType());
        artifactNode.setProperty(JCRConstants.SRAMP_CONTENT_SIZE,
                artifactNode.getProperty(JCRConstants.JCR_CONTENT_DATA).getLength());
        Binary binary = artifactNode.getProperty(JCRConstants.JCR_CONTENT_DATA).getBinary();
        if (binary != null) {
            String sha1Hash;
            if (binary instanceof org.modeshape.jcr.api.Binary) {
                // Optimization -- reuse the hash generated by ModeShape
                sha1Hash = ((org.modeshape.jcr.api.Binary) binary).getHexHash();
            } else {
                InputStream inputStream = null;
                try {
                    inputStream = binary.getStream();
                    sha1Hash = DigestUtils.shaHex(inputStream);
                } finally {
                    if (inputStream != null) {
                        IOUtils.closeQuietly(inputStream);
                    }
                }
            }
            artifactNode.setProperty(JCRConstants.SRAMP_CONTENT_HASH, sha1Hash);
        }
    }
    // XMLDocument
    if (primaryArtifact instanceof XmlDocument) {
        artifactNode.setProperty(JCRConstants.SRAMP_CONTENT_ENCODING,
                ((XmlDocument) primaryArtifact).getContentEncoding());
    }
}

From source file:org.artificer.shell.maven.DeployCommand.java

@Override
protected CommandResult doExecute(CommandInvocation commandInvocation) throws Exception {
    if (CollectionUtils.isEmpty(arguments)) {
        return doHelp(commandInvocation);
    }/*from www . ja v a  2 s  .co m*/

    String filePathArg = requiredArgument(commandInvocation, arguments, 0);

    ArtificerAtomApiClient client = client(commandInvocation);

    // Validate the file
    File file = new File(filePathArg);
    if (!file.exists()) {
        URL url = this.getClass().getClassLoader().getResource(filePathArg);
        if (url != null) {
            file = new File(url.toURI());
        } else {
            commandInvocation.getShell().out()
                    .println(Messages.i18n.format("DeployCommand.FileNotFound", filePathArg));
            return CommandResult.FAILURE;
        }
    }

    ArtifactType artifactType = null;
    if (StringUtils.isNotBlank(type)) {
        artifactType = ArtifactType.valueOf(type);
        if (artifactType.isExtendedType()) {
            artifactType = ArtifactType.ExtendedDocument(artifactType.getExtendedType());
        }
    }
    // Process GAV and other meta-data, then update the artifact
    MavenGavInfo mavenGavInfo = MavenGavInfo.fromCommandLine(gav, file);
    if (mavenGavInfo.getType() == null) {
        commandInvocation.getShell().out()
                .println(Messages.i18n.format("DeployCommand.TypeNotSet", file.getName()));
        return CommandResult.FAILURE;
    }
    if (!ALLOW_SNAPSHOT && mavenGavInfo.isSnapshot()) {
        commandInvocation.getShell().out()
                .println(Messages.i18n.format("DeployCommand.SnapshotNotAllowed", gav));
        return CommandResult.FAILURE;
    }

    InputStream content = null;
    try {
        BaseArtifactType artifact = findExistingArtifactByGAV(client, mavenGavInfo);
        if (artifact != null) {
            commandInvocation.getShell().out()
                    .println(Messages.i18n.format("DeployCommand.Failure.ReleaseArtifact.Exist", gav));
            return CommandResult.FAILURE;
        } else {
            content = FileUtils.openInputStream(file);
            artifact = client.uploadArtifact(artifactType, content, file.getName());
        }

        // Process GAV and other meta-data, then update the artifact
        String artifactName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion();
        String pomName = mavenGavInfo.getArtifactId() + '-' + mavenGavInfo.getVersion() + ".pom";
        ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_GROUP_ID,
                mavenGavInfo.getGroupId());
        ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_ARTIFACT_ID,
                mavenGavInfo.getArtifactId());
        ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_VERSION,
                mavenGavInfo.getVersion());
        ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_MD5, mavenGavInfo.getMd5());
        ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_HASH_SHA1, mavenGavInfo.getSha1());
        if (StringUtils.isNotBlank(mavenGavInfo.getSnapshotId())) {
            ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID,
                    mavenGavInfo.getSnapshotId());
        } else if (mavenGavInfo.isSnapshot()) {
            ArtificerModelUtils.setCustomProperty(artifact, JavaModel.PROP_MAVEN_SNAPSHOT_ID,
                    generateSnapshotTimestamp());
        }
        if (mavenGavInfo.getClassifier() != null) {
            ArtificerModelUtils.setCustomProperty(artifact, "maven.classifier", mavenGavInfo.getClassifier());
            artifactName += '-' + mavenGavInfo.getClassifier();
        }
        if (mavenGavInfo.getType() != null) {
            ArtificerModelUtils.setCustomProperty(artifact, "maven.type", mavenGavInfo.getType());
            artifactName += '.' + mavenGavInfo.getType();
        }
        artifact.setName(artifactName);
        client.updateArtifactMetaData(artifact);

        // Generate and add a POM for the artifact
        String pom = generatePom(mavenGavInfo);
        InputStream pomContent = new ByteArrayInputStream(pom.getBytes("UTF-8"));
        BaseArtifactType pomArtifact = ArtifactType.ExtendedDocument(JavaModel.TYPE_MAVEN_POM_XML)
                .newArtifactInstance();
        pomArtifact.setName(pomName);
        ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_TYPE, "pom");
        ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_MD5,
                DigestUtils.md5Hex(pom));
        ArtificerModelUtils.setCustomProperty(pomArtifact, JavaModel.PROP_MAVEN_HASH_SHA1,
                DigestUtils.shaHex(pom));

        client.uploadArtifact(pomArtifact, pomContent);

        // Put the artifact in the session as the active artifact
        context(commandInvocation).setCurrentArtifact(artifact);
        commandInvocation.getShell().out().println(Messages.i18n.format("DeployCommand.Success"));
        PrintArtifactMetaDataVisitor visitor = new PrintArtifactMetaDataVisitor(commandInvocation);
        ArtifactVisitorHelper.visitArtifact(visitor, artifact);

        return CommandResult.SUCCESS;
    } catch (Exception e) {
        commandInvocation.getShell().out().println(Messages.i18n.format("DeployCommand.Failure"));
        commandInvocation.getShell().out().println("\t" + e.getMessage());
        return CommandResult.FAILURE;
    } finally {
        IOUtils.closeQuietly(content);
    }
}