Example usage for org.apache.commons.lang3.exception ExceptionUtils getMessage

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getMessage

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getMessage.

Prototype

public static String getMessage(final Throwable th) 

Source Link

Document

Gets a short message summarising the exception.

Usage

From source file:com.baasbox.controllers.ScriptsAdmin.java

public static Result delete(String name) {
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method Start");
    Result result;/*from   w  w  w .ja  v  a 2  s  .co  m*/
    try {
        boolean deleted = ScriptingService.delete(name);
        if (deleted) {
            result = ok();
        } else {
            result = notFound("script: " + name + " not found");
        }
    } catch (ScriptException e) {
        BaasBoxLogger.error("Error while deleting script: " + name, e);
        result = internalServerError(ExceptionUtils.getMessage(e));
    }
    if (BaasBoxLogger.isTraceEnabled())
        BaasBoxLogger.trace("Method end");
    return result;
}

From source file:com.baasbox.service.scripting.ScriptingService.java

public static ScriptResult invoke(ScriptCall call) throws ScriptEvalException {
    if (BaasBoxLogger.isDebugEnabled())
        BaasBoxLogger.debug("Invoking script: " + call.scriptName);
    MAIN.set(call.scriptName);//from www .j  a v a2s .  com
    BaasboxScriptEngine engine = call.engine();
    try {
        ScriptResult res = engine.eval(call);
        return res;
    } catch (Exception e) {
        if (e instanceof ScriptEvalException) {
            throw (ScriptEvalException) e;
        } else {
            throw new ScriptEvalException(ExceptionUtils.getMessage(e), e);
        }
    } finally {
        MAIN.set(null);
    }
}

From source file:com.twosigma.beaker.core.rest.FileIORest.java

private String readAsString(String path) {
    try {/*from  w  w  w  . j  a va 2s . co  m*/
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return StandardCharsets.UTF_8.decode(ByteBuffer.wrap(encoded)).toString();
    } catch (AccessDeniedException ade) {
        throw new FileAccessDeniedException(ExceptionUtils.getMessage(ade));
    } catch (Throwable t) {
        throw new FileOpenException(ExceptionUtils.getStackTrace(t));
    }
}

From source file:com.baasbox.controllers.Social.java

/**
 * Returns for the current user the linked accounts to external
 * social providers.//  ww w .ja  v  a2 s.c  o  m
 * 
 * 
 *  @return a json representation of the list of connected social networks
 *  404 if no social networks are connected 
 */

@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result socialLogins() {
    try {
        ODocument user = UserService.getCurrentUser();
        Map<String, ODocument> logins = user.field(UserDao.ATTRIBUTES_SYSTEM + "." + UserDao.SOCIAL_LOGIN_INFO);
        if (logins == null || logins.isEmpty()) {
            return notFound();
        } else {
            List<UserInfo> result = new ArrayList<UserInfo>();
            for (ODocument d : logins.values()) {
                UserInfo i = UserInfo.fromJson(d.toJSON());
                result.add(i);
            }
            return ok(Json.toJson(result));
        }
    } catch (Exception e) {
        return internalServerError(ExceptionUtils.getMessage(e));
    }
}

From source file:DocumentCountFunctionalTest.java

@Test
public void testRouteRawOrientDB() {
    running(getFakeApplication(), new Runnable() {
        public void run() {

            //creates a fake collection
            String sFakeCollection = new AdminCollectionFunctionalTest().routeCreateCollection();

            //creates a dummy user
            String sFakeUser = "UserTestCount_" + UUID.randomUUID();
            // Prepare test user
            JsonNode node = updatePayloadFieldValue("/adminUserCreatePayload.json", "username", sFakeUser);

            // Create user
            FakeRequest request = new FakeRequest("POST", "/user");
            request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            request = request.withJsonBody(node, "POST");
            Result result = routeAndCall(request);
            assertRoute(result, "testRouteGetDocumentsCountWithStart -create fake user", 201, null, false);

            //insert 2 records using admin
            result = routeCreateDocument(getRouteAddress(sFakeCollection));
            result = routeCreateDocument(getRouteAddress(sFakeCollection));

            try {
                DbHelper.open("1234567890", sFakeUser, "passw1");
            } catch (InvalidAppCodeException e) {
                assertFail("AppCode not valid(??!!!??) - " + ExceptionUtils.getMessage(e));
            }/*www.ja v a 2 s. c om*/

            long count = 0;
            try {
                List<ODocument> listOfdoc = (List<ODocument>) DbHelper
                        .genericSQLStatementExecute("select count(*) from " + sFakeCollection, new String[] {});
                ODocument doc = listOfdoc.get(0);
                count = (Long) doc.field("count");
            } catch (Exception e) {
                assertFail(ExceptionUtils.getMessage(e));
            } finally {
                if (DbHelper.getConnection() != null && !DbHelper.getConnection().isClosed())
                    DbHelper.getConnection().close();
            }

            //these two tests will fail when OrientDB will be patched, actually it will need to be swapped
            //this is WRONG, should not pass when OrientDB will be patched
            Assert.assertTrue("Finally OrientDB is patched", count == 2);
            //this is wrong too
            Assert.assertFalse("Finally OrientDB is patched", count == 0);
        }
    });
}

From source file:com.baasbox.controllers.Social.java

/**
 * Unlink given social network from current user.
 * In case that the user was generated by any social network and
 * at the moment of the unlink the user has only one social network connected
 * the controller will throw an Exception with a clear message.
 * Otherwise a 200 code will be returned
 * @param socialNetwork/* w  w  w . ja  v a  2 s.  co  m*/
 * @return
 * @throws SqlInjectionException 
 */
@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result unlink(String socialNetwork) throws SqlInjectionException {
    ODocument user = null;
    try {
        user = UserService.getCurrentUser();
    } catch (Exception e) {
        internalServerError(ExceptionUtils.getMessage(e));
    }
    Map<String, ODocument> logins = user.field(UserDao.ATTRIBUTES_SYSTEM + "." + UserDao.SOCIAL_LOGIN_INFO);
    if (logins == null || logins.isEmpty() || !logins.containsKey(socialNetwork)
            || logins.get(socialNetwork) == null) {
        return notFound("User's account is not linked with " + StringUtils.capitalize(socialNetwork));
    } else {
        boolean generated = UserService.isSocialAccount(DbHelper.getCurrentUserNameFromConnection());
        if (logins.size() == 1 && generated) {
            return internalServerError("User's account can't be unlinked.");
        } else {
            try {
                UserService.removeSocialLoginTokens(user, socialNetwork);
                return ok();
            } catch (Exception e) {
                return internalServerError(ExceptionUtils.getMessage(e));
            }
        }
    }
}

From source file:com.baasbox.service.push.providers.APNServer.java

@Override
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
    PushLogger pushLogger = PushLogger.getInstance();
    pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
    ApnsService service = null;//from w ww  .  j a  va 2s .  c  o  m
    try {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
        if (!isInit) {
            pushLogger.addMessage("............ APNS is not initialized!");
            return true;
        }

        String payload = null;
        try {
            service = getService();
        } catch (com.notnoop.exceptions.InvalidSSLConfig e) {
            pushLogger.addMessage("Error sending push notification ...");
            pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
            BaasBoxLogger.error("Error sending push notification");
            throw new PushNotInitializedException(
                    "Error decrypting certificate.Verify your password for given certificate");
            //icallbackPush.onError(ExceptionUtils.getMessage(e));
        }

        JsonNode contentAvailableNode = bodyJson.findValue("content-available");
        Integer contentAvailable = null;
        if (!(contentAvailableNode == null)) {
            if (!(contentAvailableNode.isInt()))
                throw new PushContentAvailableFormatException(
                        "Content-available MUST be an Integer (1 for silent notification)");
            contentAvailable = contentAvailableNode.asInt();
        }

        JsonNode categoryNode = bodyJson.findValue("category");
        String category = null;
        if (!(categoryNode == null)) {
            if (!(categoryNode.isTextual()))
                throw new PushCategoryFormatException("Category MUST be a String");
            category = categoryNode.asText();
        }

        JsonNode soundNode = bodyJson.findValue("sound");
        String sound = null;
        if (!(soundNode == null)) {
            if (!(soundNode.isTextual()))
                throw new PushSoundKeyFormatException("Sound value MUST be a String");
            sound = soundNode.asText();
        }

        JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
        String actionLocKey = null;

        if (!(actionLocKeyNode == null)) {
            if (!(actionLocKeyNode.isTextual()))
                throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
            actionLocKey = actionLocKeyNode.asText();
        }

        JsonNode locKeyNode = bodyJson.findValue("localizedKey");
        String locKey = null;

        if (!(locKeyNode == null)) {
            if (!(locKeyNode.isTextual()))
                throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
            locKey = locKeyNode.asText();
        }

        JsonNode locArgsNode = bodyJson.get("localizedArguments");

        List<String> locArgs = new ArrayList<String>();
        if (!(locArgsNode == null)) {
            if (!(locArgsNode.isArray()))
                throw new PushLocalizedArgumentsFormatException(
                        "LocalizedArguments MUST be an Array of String");
            for (JsonNode locArgNode : locArgsNode) {
                if (locArgNode.isNumber())
                    throw new PushLocalizedArgumentsFormatException(
                            "LocalizedArguments MUST be an Array of String");
                locArgs.add(locArgNode.toString());
            }
        }

        JsonNode customDataNodes = bodyJson.get("custom");

        Map<String, JsonNode> customData = new HashMap<String, JsonNode>();

        if (!(customDataNodes == null)) {
            customData.put("custom", customDataNodes);
        }

        JsonNode badgeNode = bodyJson.findValue("badge");
        int badge = 0;
        if (!(badgeNode == null)) {
            if (!(badgeNode.isNumber()))
                throw new PushBadgeFormatException("Badge value MUST be a number");
            else
                badge = badgeNode.asInt();
        }

        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                    + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                    + " with Localized-Key: " + locKey);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Custom Data: " + customData.toString());

        pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                + " with Localized-Key: " + locKey);
        pushLogger.addMessage("Localized arguments: " + locArgs.toString());
        pushLogger.addMessage("Custom Data: " + customData.toString());
        pushLogger.addMessage("Timeout: " + timeout);

        PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound)
                .actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge)
                .customFields(customData).category(category);
        if (contentAvailable != null && contentAvailable.intValue() == 1) {
            payloadBuilder.instantDeliveryOrSilentNotification();
        }
        payload = payloadBuilder.build();

        Collection<? extends ApnsNotification> result = null;
        if (timeout <= 0) {
            try {
                result = service.push(deviceid, payload);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }
        } else {
            try {
                Date expiry = new Date(Long.MAX_VALUE);
                pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout,
                        expiry.toString());
                result = service.push(deviceid, payload, expiry);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending enhanced push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }

        }
        if (result != null) {
            Iterator<? extends ApnsNotification> it = result.iterator();
            while (it.hasNext()) {
                ApnsNotification item = it.next();
                //item.
            }

        }
        //icallbackPush.onSuccess();
        return false;
    } catch (Exception e) {
        pushLogger.addMessage("Error sending push notification (APNS)...");
        pushLogger.addMessage(ExceptionUtils.getMessage(e));
        throw e;
    } finally {
        if (service != null)
            service.stop();
    }
}

From source file:com.baasbox.controllers.Push.java

public static Result sendUsers() throws Exception {
    boolean verbose = false;
    try {/*from ww w. j  a v a 2s .com*/

        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method Start");
        PushLogger pushLogger = PushLogger.getInstance().init();
        if (UserService.isAnAdmin(DbHelper.currentUsername())) {
            pushLogger.enable();
        } else {
            pushLogger.disable();
        }
        if (request().getQueryString("verbose") != null
                && request().getQueryString("verbose").equalsIgnoreCase("true"))
            verbose = true;

        Http.RequestBody body = request().body();
        JsonNode bodyJson = body.asJson(); //{"message":"Text"}
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("send bodyJson: " + bodyJson);
        if (bodyJson == null)
            return status(CustomHttpCode.JSON_PAYLOAD_NULL.getBbCode(),
                    CustomHttpCode.JSON_PAYLOAD_NULL.getDescription());
        pushLogger.addMessage("Payload received: %s", bodyJson.toString());
        JsonNode messageNode = bodyJson.findValue("message");
        pushLogger.addMessage("Payload message received: %s",
                messageNode == null ? "null" : messageNode.asText());
        if (messageNode == null)
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());
        if (!messageNode.isTextual())
            return status(CustomHttpCode.PUSH_MESSAGE_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_MESSAGE_INVALID.getDescription());

        String message = messageNode.asText();

        JsonNode usernamesNodes = bodyJson.get("users");
        pushLogger.addMessage("users: %s", usernamesNodes == null ? "null" : usernamesNodes.toString());

        List<String> usernames = new ArrayList<String>();

        if (!(usernamesNodes == null)) {

            if (!(usernamesNodes.isArray()))
                return status(CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_USERS_FORMAT_INVALID.getDescription());

            for (JsonNode usernamesNode : usernamesNodes) {
                usernames.add(usernamesNode.asText());
            }

            HashSet<String> hs = new HashSet<String>();
            hs.addAll(usernames);
            usernames.clear();
            usernames.addAll(hs);
            pushLogger.addMessage("Users extracted: %s", Joiner.on(",").join(usernames));
        } else {
            return status(CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getBbCode(),
                    CustomHttpCode.PUSH_NOTFOUND_KEY_USERS.getDescription());
        }

        JsonNode pushProfilesNodes = bodyJson.get("profiles");
        pushLogger.addMessage("profiles: %s",
                pushProfilesNodes == null ? "null" : pushProfilesNodes.toString());

        List<Integer> pushProfiles = new ArrayList<Integer>();
        if (!(pushProfilesNodes == null)) {
            if (!(pushProfilesNodes.isArray()))
                return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                        CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
            for (JsonNode pushProfileNode : pushProfilesNodes) {
                if (pushProfileNode.isTextual())
                    return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                            CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
                pushProfiles.add(pushProfileNode.asInt());
            }

            HashSet<Integer> hs = new HashSet<Integer>();
            hs.addAll(pushProfiles);
            pushProfiles.clear();
            pushProfiles.addAll(hs);
        } else {
            pushProfiles.add(1);
        }
        pushLogger.addMessage("Profiles computed: %s", Joiner.on(",").join(pushProfiles));

        boolean[] withError = new boolean[6];
        PushService ps = new PushService();
        Result toRet = null;
        try {
            boolean isValid = (ps.validate(pushProfiles));
            pushLogger.addMessage("Profiles validation: %s", isValid);
            if (isValid)
                withError = ps.send(message, usernames, pushProfiles, bodyJson, withError);
            pushLogger.addMessage("Service result: %s", Booleans.join(", ", withError));
        } catch (UserNotFoundException e) {
            return notFound("Username not found");
        } catch (SqlInjectionException e) {
            return badRequest("The supplied name appears invalid (Sql Injection Attack detected)");
        } catch (PushNotInitializedException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONFIG_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONFIG_INVALID.getDescription());
        } catch (PushProfileDisabledException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_DISABLED.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_DISABLED.getDescription());
        } catch (PushProfileInvalidException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_PROFILE_FORMAT_INVALID.getDescription());
        } catch (PushInvalidApiKeyException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_APIKEY.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_APIKEY.getDescription());
        } catch (UnknownHostException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_HOST_UNREACHABLE.getBbCode(),
                    CustomHttpCode.PUSH_HOST_UNREACHABLE.getDescription());
        } catch (InvalidRequestException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_INVALID_REQUEST.getBbCode(),
                    CustomHttpCode.PUSH_INVALID_REQUEST.getDescription());
        } catch (IOException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return badRequest(ExceptionUtils.getMessage(e));
        } catch (PushSoundKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_SOUND_FORMAT_INVALID.getDescription());
        } catch (PushBadgeFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_BADGE_FORMAT_INVALID.getDescription());
        } catch (PushActionLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_ACTION_LOCALIZED_KEY_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushLocalizedArgumentsFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_LOCALIZED_ARGUMENTS_FORMAT_INVALID.getDescription());
        } catch (PushCollapseKeyFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_COLLAPSE_KEY_FORMAT_INVALID.getDescription());
        } catch (PushTimeToLiveFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_TIME_TO_LIVE_FORMAT_INVALID.getDescription());
        } catch (PushContentAvailableFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CONTENT_AVAILABLE_FORMAT_INVALID.getDescription());
        } catch (PushCategoryFormatException e) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(e));
            return status(CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getBbCode(),
                    CustomHttpCode.PUSH_CATEGORY_FORMAT_INVALID.getDescription());
        }
        if (BaasBoxLogger.isTraceEnabled())
            BaasBoxLogger.trace("Method End");

        for (int i = 0; i < withError.length; i++) {
            if (withError[i] == true)
                return status(CustomHttpCode.PUSH_SENT_WITH_ERROR.getBbCode(),
                        CustomHttpCode.PUSH_SENT_WITH_ERROR.getDescription());
        }
        PushLogger.getInstance().messages();
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        } else {
            return ok("Push Notification(s) has been sent");
        }
    } finally {
        if (UserService.isAnAdmin(DbHelper.currentUsername()) && verbose) {
            return ok(toJson(PushLogger.getInstance().messages()));
        }
        BaasBoxLogger.debug("Push execution flow:\n{}", PushLogger.getInstance().toString());
    }
}

From source file:com.baasbox.controllers.Social.java

/**
 * links current user with specified social network param
 * //from   w w w.  ja  v a2s . c  om
 * In case the token obtained by the service is already existing in the database
 * for another user an exception is raised
 * @param socialNetwork the social network to be linked to
 * @return a 200 code if the link is correctly generated
 * 
 *  
 */
@With({ UserCredentialWrapFilter.class, ConnectToDBFilter.class })
public static Result linkWith(String socialNetwork) {
    //issue #217: "oauth_token" parameter should be moved to request body in Social Login APIs
    Token t = extractOAuthTokensFromRequest(request());
    if (t == null) {
        return badRequest("Both '" + OAUTH_TOKEN + "' and '" + OAUTH_SECRET + "' should be specified.");
    }

    String appcode = (String) ctx().args.get("appcode");
    SocialLoginService sc = SocialLoginService.by(socialNetwork, appcode);

    UserInfo result = null;
    try {
        if (sc.validationRequest(t.getToken())) {
            result = sc.getUserInfo(t);
        } else {
            return badRequest("Provided token is not valid.");
        }
    } catch (BaasBoxSocialException e1) {
        return badRequest(e1.getError());
    } catch (BaasBoxSocialTokenValidationException e2) {
        return badRequest("Unable to validate provided token.");
    }
    result.setFrom(socialNetwork);
    result.setToken(t.getToken());

    //Setting token as secret for one-token only social networks
    result.setSecret(
            t.getSecret() != null && StringUtils.isNotEmpty(t.getSecret()) ? t.getSecret() : t.getToken());
    ODocument user;
    try {
        user = UserService.getCurrentUser();
        ODocument other = UserDao.getInstance().getBySocialUserId(result);
        boolean sameUser = other != null && other.getIdentity().equals(user.getIdentity());
        if (other == null || !sameUser) {
            UserService.addSocialLoginTokens(user, result);
        } else {
            internalServerError("A user with this token already exists and it's not the current user.");
        }
        return ok();
    } catch (SqlInjectionException e) {
        return internalServerError(ExceptionUtils.getMessage(e));
    }

}

From source file:com.thruzero.common.core.security.SimpleCipher.java

/**
 * Construct using the {@code salt}, {@code passPhrase} and {@code iterationCount} defined by the given
 * {@code simpleCipherConfiguration}.//from www  .j a  va 2s . c o m
 *
 * @throws SimpleCipherException
 */
public SimpleCipher(final SimpleCipherConfiguration simpleCipherConfiguration) throws SimpleCipherException {
    try {
        int count = simpleCipherConfiguration.getIterationCount();
        byte[] salt = simpleCipherConfiguration.getSalt();

        KeySpec keySpec = new PBEKeySpec(simpleCipherConfiguration.getPassPhrase(), salt, count);

        AlgorithmParameterSpec parameterSpec = new PBEParameterSpec(salt, count);
        SecretKey key = SecretKeyFactory.getInstance(PBE_WITH_MD5_AND_DES).generateSecret(keySpec);

        encryptionCipher = Cipher.getInstance(key.getAlgorithm());
        encryptionCipher.init(Cipher.ENCRYPT_MODE, key, parameterSpec);

        decryptionCipher = Cipher.getInstance(key.getAlgorithm());
        decryptionCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SimpleCipherException(
                "Couldn't instantiate SimpleCipher because of " + ExceptionUtils.getMessage(e), e);
    } catch (Exception e) {
        throw new SimpleCipherException(
                "Couldn't instantiate SimpleCipher because of " + ExceptionUtils.getMessage(e), e);
    }
}