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:net.sourceforge.vaticanfetcher.util.AppUtil.java

/**
 * Checks whether an instance of this program is already running. The check relies on a lockfile created in the 
 * temporary directory. The argument is the program name to be displayed in the confirmation dialog (see below).
 * <p>/* ww  w  .j a  v a 2s .  com*/
 * The boolean return value should be interpreted as "proceed with running this instance?". More specifically:
 * <ul>
 * <li>If there is no other instance, true is returned.
 * <li>If there is another instance, a confirmation dialog is shown, which asks the user whether 
 * this instance should be launched. If the user confirms, true is returned, otherwise false.
 * </ul>
 * The filename of the lockfile includes the username and the working directory, which means:
 * <ul>
 * <li>The same instance may be launched multiple times by different users.
 * <li>Multiple instances from different locations can be run simultaneously by the same user.
 * </ul>
 * <p>
 * <b>Note</b>: The message container must be loaded before calling this method, otherwise the confirmation dialog will show untranslated strings.
 */
// TODO doc: before calling this method, set USER_DIR_PATH, PROGRAM_NAME and all Msg enums
public static boolean checkSingleInstance() {
    checkConstInitialized();
    ensureNoDisplay();

    /*
     * The lockfile is created in the system's temporary directory to make sure it gets deleted after 
     * OS shutdown - neither File.deleteOnExit() nor a JVM shutdown hook can guarantee this.
     * 
     * The name of the lockfile includes the base64-encoded working directory, thus avoiding filename 
     * collisions if the same user runs multiple program instances from different locations. We'll also put
     * in a SHA-1 digest of the working directory, just in case the base64-encoded working directory 
     * exceeds the system's allowed filename length limit, which we'll assume to be 255 characters.
     * 
     * Note that the included program name is also encoded as base64 since a developer might have 
     * (accidentally?) set a program name that contains special characters such as '/'.
     */

    String dirPath = Const.USER_DIR_PATH.value;
    String shaDirPath = DigestUtils.shaHex(dirPath);
    String programName64 = encodeBase64(Const.PROGRAM_NAME.value);
    String username64 = encodeBase64(System.getProperty("user.name"));
    String dirPath64 = encodeBase64(dirPath);

    String lockname = String.format(".lock-%s-%s-%s-%s.", // dot at the end is intentional
            shaDirPath, programName64, username64, dirPath64);
    // Usual filename length limit is 255 characters
    lockname = lockname.substring(0, Math.min(lockname.length(), 250));
    File lockfile = new File(Util.TEMP_DIR, lockname);

    if (lockfile.exists()) {
        if (SettingsConf.Bool.AllowOnlyOneInstance.get()) {
            sendHotkeyToFront();
            return false;
        } else {
            // Show message, ask whether to launch new instance or to abort
            Display display = new Display();
            Shell shell = new Shell(display);
            MessageBox msgBox = new MessageBox(shell,
                    SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL | SWT.PRIMARY_MODAL);
            msgBox.setText(Messages.confirm_operation.value);
            msgBox.setMessage(Messages.program_running_launch_another.format(Const.PROGRAM_NAME.value));
            int ans = msgBox.open();
            display.dispose();
            if (ans != SWT.OK) {
                sendHotkeyToFront();
                return false;
            }
            /*
             * If the user clicks OK, we'll take over the lockfile we found and delete it on exit. That means: 
             * (1) If there's another instance running, we'll wrongfully "steal" the lockfile from it. 
             * (2) If there's no other instance running (probably because it crashed or was killed by the user), we'll 
             * rightfully take over an orphaned lockfile. This behavior is okay, assuming the second case is more likely.
             */
        }
    } else {
        try {
            lockfile.createNewFile();
        } catch (IOException e) {
        }
    }
    lockfile.deleteOnExit();
    return true;
}

From source file:net.sourceforge.vulcan.jabber.XmppClient.java

@Override
public void refreshConnection(JabberPluginConfig config) {
    String password = config.getPassword();
    if (password == null) {
        password = StringUtils.EMPTY;//  w  w  w .jav a  2 s  . c o m
    }
    final String connectionString = config.getServer() + ":" + config.getPort() + ":" + config.getServiceName()
            + ":" + config.getUsername() + ":" + DigestUtils.shaHex(password);

    synchronized (lock) {
        if (connectionString.equals(this.connectionString) && connection != null && connection.isConnected()) {
            return;
        }

        this.connectionString = connectionString;

        if (connection != null && connection.isConnected()) {
            connection.disconnect();
        }

        connection = null;

        if (isEmpty(config.getServiceName()) && isEmpty(config.getServer())) {
            return;
        }

        LOG.info("Connecting to " + config.getServer() + ":" + config.getPort());

        connect(config);
        if (connection == null) {
            this.connectionString = null;
        }
    }
}

From source file:net.urosk.mifss.core.workers.ApiKeyHandlerImpl.java

@Override
public ApiKey generateNewApiKey(String name, String description, ApiMode apiMode)
        throws ApiKeyHandlerException {

    // api key name is mandatory
    if (StringUtils.isEmpty(name)) {
        throw new ApiKeyHandlerException("Name must be entered");
    }//from  w  w  w .  j  a  v a2  s. c o m
    // api mode must be explicitly entered
    if (apiMode == null) {
        throw new ApiKeyHandlerException("Api mode must be entered! Possible values are: " + ApiMode.values());
    }

    String hash = DigestUtils
            .shaHex("secret x" + (new Date().getTime()) + "mifss" + UUID.randomUUID() + Math.random());

    ApiKey apiKey = new ApiKey();

    apiKey.setApiMode(apiMode);
    apiKey.setDescription(description);
    apiKey.setHash(hash);
    apiKey.setName(name);

    return apiKey;
}

From source file:net.ymate.platform.module.wechat.support.MessageHelper.java

/**
 * SHA1???/*from w ww.j av  a2s. c om*/
 *
 * @param token     ?
 * @param timestamp 
 * @param nonce     ?
 * @param encrypt   
 * @return ??
 */
static String getSHA1(String token, String timestamp, String nonce, String encrypt) {
    String[] array = new String[] { token, timestamp, nonce, encrypt };
    // ?
    Arrays.sort(array);
    // SHA1???
    return DigestUtils.shaHex(StringUtils.join(array, ""));
}

From source file:net.ymate.platform.module.wechat.WeChat.java

/**
 * @param token//  w  w w  . ja  v a 2 s  . c o m
 * @param signature
 * @param timestamp
 * @param nonce
 * @return ??
 */
public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
    List<String> _params = new ArrayList<String>();
    _params.add(token);
    _params.add(timestamp);
    _params.add(nonce);
    Collections.sort(_params, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.compareTo(o2);
        }
    });
    return DigestUtils.shaHex(_params.get(0) + _params.get(1) + _params.get(2)).equals(signature);
}

From source file:net.ymate.platform.module.wechat.WeChat.java

/**
 * ?JSAPI?/*from  w w w  .ja va 2  s .c  o m*/
 *
 * @param accountId ??ID
 * @param url       JSAPI?URL?
 * @return wx.config
 * @throws Exception
 */
public static JSONObject wxCreateJsApiConfig(String accountId, String url) throws Exception {
    String _jsapiTicket = __dataProvider.getJsApiTicket(accountId);
    String _timestamp = DateTimeUtils.currentTimeMillisUTC() + "";
    String _noncestr = UUIDUtils.uuid();
    //
    StringBuilder _signSB = new StringBuilder().append("jsapi_ticket=").append(_jsapiTicket).append("&")
            .append("noncestr=").append(_noncestr).append("&").append("timestamp=").append(_timestamp)
            .append("&").append("url=").append(StringUtils.substringBefore(url, "#"));
    //
    JSONObject _json = new JSONObject();
    _json.put("jsapi_ticket", _jsapiTicket);
    _json.put("timestamp", _timestamp);
    _json.put("nonceStr", _noncestr);
    _json.put("url", url);
    _json.put("signature", DigestUtils.shaHex(_signSB.toString()));
    _json.put("appId", __dataProvider.getAppId(accountId));
    return _json;
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    PostMethod method = new PostMethod(url);
    method.addParameter("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        method.addParameter(entry.getKey(), entry.getValue());
    }/*  ww w .  java 2  s .c  o  m*/
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    method.addParameter("ts", ts);
    method.addParameter("hash", hash);
    logger.debug("Sending POST message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(method.getParameters()));
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendMultiPartMessage(String url, Map<String, String> parameters, Map<String, File> files)
        throws IOException, SlideShareErrorException {
    PostMethod method = new PostMethod(url);
    List<Part> partList = new ArrayList<Part>();
    partList.add(createStringPart("api_key", this.apiKey));
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    partList.add(createStringPart("ts", ts));
    partList.add(createStringPart("hash", hash));
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        partList.add(createStringPart(entry.getKey(), entry.getValue()));
    }//w  w w. j  a  va2  s  .  co  m
    Iterator<Map.Entry<String, File>> entryFileIt = files.entrySet().iterator();
    while (entryFileIt.hasNext()) {
        Map.Entry<String, File> entry = entryFileIt.next();
        partList.add(createFilePart(entry.getKey(), entry.getValue()));
    }
    MultipartRequestEntity requestEntity = new MultipartRequestEntity(
            partList.toArray(new Part[partList.size()]), method.getParams());
    method.setRequestEntity(requestEntity);
    logger.debug("Sending multipart POST message to " + method.getURI().getURI() + " with parts " + partList);
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:org.alfresco.repo.publishing.slideshare.SlideShareConnectorImpl.java

public InputStream sendGetMessage(String url, Map<String, String> parameters)
        throws IOException, SlideShareErrorException {
    GetMethod method = new GetMethod(url);
    NameValuePair[] params = new NameValuePair[parameters.size() + 3];
    int i = 0;/*from   w  ww .  j  av  a  2  s. c  om*/
    params[i++] = new NameValuePair("api_key", this.apiKey);
    Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator();
    while (entryIt.hasNext()) {
        Map.Entry<String, String> entry = entryIt.next();
        params[i++] = new NameValuePair(entry.getKey(), entry.getValue());
    }
    Date now = new Date();
    String ts = Long.toString(now.getTime() / 1000);
    String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase();
    params[i++] = new NameValuePair("ts", ts);
    params[i++] = new NameValuePair("hash", hash);
    method.setQueryString(params);
    logger.debug("Sending GET message to " + method.getURI().getURI() + " with parameters "
            + Arrays.toString(params));
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != HttpStatus.SC_OK) {
        logger.debug("Server replied with a " + statusCode + " HTTP status code ("
                + HttpStatus.getStatusText(statusCode) + ")");
        throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode));
    }
    if (logger.isDebugEnabled()) {
        logger.debug(method.getResponseBodyAsString());
    }
    InputStream result = new ByteArrayInputStream(method.getResponseBody());
    method.releaseConnection();
    return result;
}

From source file:org.apache.accumulo.server.fs.VolumeUtil.java

private static String hash(FileSystem fs, Path dir, String name) throws IOException {
    FSDataInputStream in = fs.open(new Path(dir, name));
    try {/*from  ww w  .j  av a2s .c  o m*/
        return DigestUtils.shaHex(in);
    } finally {
        in.close();
    }

}