Example usage for org.apache.commons.lang3 StringUtils removeStart

List of usage examples for org.apache.commons.lang3 StringUtils removeStart

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils removeStart.

Prototype

public static String removeStart(final String str, final String remove) 

Source Link

Document

Removes a substring only if it is at the beginning of a source string, otherwise returns the source string.

A null source string will return null .

Usage

From source file:demo.CamelConfig.java

@Bean
public RouteBuilder route() {
    return new RouteBuilder() {

        @Override//from  w  w  w  .  j  a v a2s  . com
        public void configure() throws Exception {

            Processor myProcessor = new Processor() {
                public void process(Exchange exchange) {
                    System.out.println("processing !! " + exchange);
                    System.out.println(exchange.getProperties());
                    System.out.println(exchange.getIn().getExchange().getProperties());

                    exchange.getProperty("photo");
                    exchange.setProperty("blah", "blah");
                    List<Photo> photos = (List<Photo>) exchange.getProperty("photos");

                    /*                  for (Photo photo : photos) {
                                         Long photoId = photo.getId();
                                         System.out.println("integration: handling photo #" + photoId);
                                         photoService.dogifyPhoto(photo);
                            
                                      }
                                      */
                    Gson gson = new Gson();

                    MessageEnvelop envelop = new MessageEnvelop();

                    envelop.setPhotos(photos);
                    envelop.setExecutionId(exchange.getProperty("PROCESS_ID_PROPERTY") + "");
                    HashMap<String, Object> message = new HashMap<>();
                    message.put("photos", photos);
                    message.put("PROCESS_ID_PROPERTY", exchange.getProperty("PROCESS_ID_PROPERTY"));

                    String msg = gson.toJson(envelop);

                    System.out.println("mdg >>" + msg);

                    exchange.getOut().setBody(msg);

                }
            };

            Processor myProcessor2 = new Processor() {
                public void process(Exchange exchange) throws JsonSyntaxException, InvalidPayloadException {
                    System.out.println(
                            "processing !! " + exchange.getIn() + "  " + exchange.getIn().getMessageId());

                    Gson gson = new Gson();

                    String normalizedStr = StringUtils.removeStart(exchange.getIn() + "  ", "Message: ");
                    System.out.println("normalizedStr" + normalizedStr);

                    MessageEnvelop env = gson.fromJson(normalizedStr, MessageEnvelop.class);

                    System.out.println("env" + env);
                    System.out.println(env.getPhotos());
                    System.out.println(env.getExecutionId());

                    List<Photo> photos = (List<Photo>) env.getPhotos();

                    sleepForSomeTime();

                    for (Photo photo : photos) {
                        Long photoId = photo.getId();
                        System.out.println("integration: handling photo #" + photoId);
                        photoService.dogifyPhoto(photo);

                    }

                    runtimeService.signal(env.getExecutionId());

                    System.out.println("signalled !!!");

                }

                private void sleepForSomeTime() {

                    System.out.println("seconds left for dogification >>");

                    int j = 60;

                    for (int i = 0; i < 20; i++) {

                        try {
                            Thread.sleep(1000);
                            System.out.print((j - 1) + " ");

                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                }
            };

            from("activiti:photoProcess:theCamelTask")
                    // .lounmarshal(jaxb)
                    .log("Testing Camel route invocation from a Camel task. ${property.photo}")
                    .process(myProcessor)
                    //.setBody(body().append("Hello World!"))
                    .to("rabbitmq:localhost:5672/tasks?username=guest&password=guest&autoDelete=false&routingKey=camel&queue=task_queue");
            // .to("mock:result");

            from("rabbitmq:localhost:5672/tasks?username=guest&password=guest&autoDelete=false&routingKey=camel&queue=task_queue")
                    // .lounmarshal(jaxb)
                    .log("message recieved... ${in.body}").process(myProcessor2);

        }

    };
}

From source file:com.infinities.keystone4j.policy.Rules.java

private static List<Entry<String, BaseCheck>> parseTokenize(String rule) {
    String[] tokens = rule.split("\\s+");

    List<Entry<String, BaseCheck>> entrys = Lists.newArrayList();

    for (String token : tokens) {
        token = token.trim();//from w w  w. j a  va  2s  .c o  m
        if (Strings.isNullOrEmpty(token)) {
            continue;
        }
        String clean = StringUtils.removeStart(token, "(");
        int range = token.length() - clean.length();
        // logger.debug("lstrip: {}, range:{}", new Object[] { clean, range
        // });
        for (int i = 0; i < range; i++) {
            BaseCheck check = new StringCheck("(");
            entrys.add(Maps.immutableEntry("(", check));
        }

        if (Strings.isNullOrEmpty(clean)) {
            continue;
        } else {
            token = clean;
        }

        clean = StringUtils.removeEnd(token, ")");
        int trail = token.length() - clean.length();
        // logger.debug("rstrip: {}, trail:{}", new Object[] { clean, trail
        // });
        String lowered = clean.toLowerCase();
        if (logicOperators.contains(lowered)) {
            BaseCheck check = new StringCheck(clean);
            entrys.add(Maps.immutableEntry(lowered, check));
        } else if (!Strings.isNullOrEmpty(clean)) {
            if (token.length() >= 2 && ((token.charAt(0) == '\"' && token.charAt(token.length()) == '\"')
                    || (token.charAt(0) == '\'' && token.charAt(token.length()) == '\''))) {
                BaseCheck check = new StringCheck(token.substring(1, token.length() - 1));
                entrys.add(Maps.immutableEntry("string", check));
            } else {
                entrys.add(Maps.immutableEntry("check", parseCheck(clean)));
            }
        }

        for (int i = 0; i < trail; i++) {
            BaseCheck check = new StringCheck(")");
            entrys.add(Maps.immutableEntry(")", check));
        }
    }

    return entrys;
}

From source file:com.wallissoftware.pushstate.client.PushStateHistorianImpl.java

private String stripStartSlash(final String pinput) {
    return StringUtils.removeStart(pinput, "/");
}

From source file:com.threewks.thundr.http.URLEncoder.java

/**
 * Decodes the given query parameter string into key value pairs.
 * //from   w ww  . j a  va 2 s  .c o  m
 * If the given string begins with '?', it will be stripped off. Pairs are decoded before being returned.
 * 
 * @param query
 * @return
 */
public static Map<String, List<String>> decodeQueryString(String query) {
    query = StringUtils.trimToEmpty(query);
    query = StringUtils.removeStart(query, "?");
    Map<String, List<String>> results = new LinkedHashMap<>();
    if (StringUtils.isNotBlank(query)) {
        for (String pair : query.split("&")) {
            String[] parts = StringUtils.split(pair, "=", 2);
            String key = unescape(parts[0]);
            String value = parts.length > 1 ? unescape(parts[1]) : null;
            List<String> existing = results.get(key);
            if (existing == null) {
                existing = new ArrayList<>();
                results.put(key, existing);
            }
            existing.add(value);
        }
    }
    return results;
}

From source file:com.erudika.scoold.utils.ScooldRequestInterceptor.java

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
        ModelAndView modelAndView) throws Exception {

    if (modelAndView == null || StringUtils.startsWith(modelAndView.getViewName(), "redirect:")) {
        return; // skip if redirect
    }//from   w  w w.  j a va2  s.  c om

    /*============================*
     * COMMON MODEL FOR ALL PAGES *
     *============================*/

    // Misc
    modelAndView.addObject("HOMEPAGE", HOMEPAGE);
    modelAndView.addObject("APPNAME", Config.APP_NAME);
    modelAndView.addObject("CDN_URL", CDN_URL);
    modelAndView.addObject("DESCRIPTION", Config.getConfigParam("meta_description", ""));
    modelAndView.addObject("KEYWORDS", Config.getConfigParam("meta_keywords", ""));
    modelAndView.addObject("IN_PRODUCTION", Config.IN_PRODUCTION);
    modelAndView.addObject("IN_DEVELOPMENT", !Config.IN_PRODUCTION);
    modelAndView.addObject("MAX_ITEMS_PER_PAGE", Config.MAX_ITEMS_PER_PAGE);
    modelAndView.addObject("SESSION_TIMEOUT_SEC", Config.SESSION_TIMEOUT_SEC);
    modelAndView.addObject("TOKEN_PREFIX", TOKEN_PREFIX);
    modelAndView.addObject("FB_APP_ID", Config.FB_APP_ID);
    modelAndView.addObject("GMAPS_API_KEY", Config.getConfigParam("gmaps_api_key", ""));
    modelAndView.addObject("GOOGLE_CLIENT_ID", Config.getConfigParam("google_client_id", ""));
    modelAndView.addObject("GOOGLE_ANALYTICS_ID", Config.getConfigParam("google_analytics_id", ""));
    modelAndView.addObject("includeHighlightJS", Config.getConfigBoolean("code_highlighting_enabled", true));
    modelAndView.addObject("isAjaxRequest", utils.isAjaxRequest(request));
    modelAndView.addObject("reportTypes", ReportType.values());
    modelAndView.addObject("returnto", StringUtils.removeStart(request.getRequestURI(), CONTEXT_PATH));
    // Configurable constants
    modelAndView.addObject("MAX_TEXT_LENGTH", MAX_TEXT_LENGTH);
    modelAndView.addObject("MAX_TAGS_PER_POST", MAX_TAGS_PER_POST);
    modelAndView.addObject("MAX_REPLIES_PER_POST", MAX_REPLIES_PER_POST);
    modelAndView.addObject("MAX_FAV_TAGS", MAX_FAV_TAGS);
    modelAndView.addObject("ANSWER_VOTEUP_REWARD_AUTHOR", ANSWER_VOTEUP_REWARD_AUTHOR);
    modelAndView.addObject("QUESTION_VOTEUP_REWARD_AUTHOR", QUESTION_VOTEUP_REWARD_AUTHOR);
    modelAndView.addObject("VOTEUP_REWARD_AUTHOR", VOTEUP_REWARD_AUTHOR);
    modelAndView.addObject("ANSWER_APPROVE_REWARD_AUTHOR", ANSWER_APPROVE_REWARD_AUTHOR);
    modelAndView.addObject("ANSWER_APPROVE_REWARD_VOTER", ANSWER_APPROVE_REWARD_VOTER);
    modelAndView.addObject("POST_VOTEDOWN_PENALTY_AUTHOR", POST_VOTEDOWN_PENALTY_AUTHOR);
    modelAndView.addObject("POST_VOTEDOWN_PENALTY_VOTER", POST_VOTEDOWN_PENALTY_VOTER);
    modelAndView.addObject("VOTER_IFHAS", VOTER_IFHAS);
    modelAndView.addObject("COMMENTATOR_IFHAS", COMMENTATOR_IFHAS);
    modelAndView.addObject("CRITIC_IFHAS", CRITIC_IFHAS);
    modelAndView.addObject("SUPPORTER_IFHAS", SUPPORTER_IFHAS);
    modelAndView.addObject("GOODQUESTION_IFHAS", GOODQUESTION_IFHAS);
    modelAndView.addObject("GOODANSWER_IFHAS", GOODANSWER_IFHAS);
    modelAndView.addObject("ENTHUSIAST_IFHAS", ENTHUSIAST_IFHAS);
    modelAndView.addObject("FRESHMAN_IFHAS", FRESHMAN_IFHAS);
    modelAndView.addObject("SCHOLAR_IFHAS", SCHOLAR_IFHAS);
    modelAndView.addObject("TEACHER_IFHAS", TEACHER_IFHAS);
    modelAndView.addObject("PROFESSOR_IFHAS", PROFESSOR_IFHAS);
    modelAndView.addObject("GEEK_IFHAS", GEEK_IFHAS);
    // Cookies
    modelAndView.addObject("localeCookieName", LOCALE_COOKIE);
    modelAndView.addObject("csrfCookieName", CSRF_COOKIE);
    // Paths
    modelAndView.addObject("imageslink", IMAGESLINK); // do not add context path prefix!
    modelAndView.addObject("scriptslink", SCRIPTSLINK); // do not add context path prefix!
    modelAndView.addObject("styleslink", STYLESLINK); // do not add context path prefix!
    modelAndView.addObject("peoplelink", CONTEXT_PATH + PEOPLELINK);
    modelAndView.addObject("profilelink", CONTEXT_PATH + PROFILELINK);
    modelAndView.addObject("searchlink", CONTEXT_PATH + SEARCHLINK);
    modelAndView.addObject("signinlink", CONTEXT_PATH + SIGNINLINK);
    modelAndView.addObject("signoutlink", CONTEXT_PATH + SIGNOUTLINK);
    modelAndView.addObject("aboutlink", CONTEXT_PATH + ABOUTLINK);
    modelAndView.addObject("privacylink", CONTEXT_PATH + PRIVACYLINK);
    modelAndView.addObject("termslink", CONTEXT_PATH + TERMSLINK);
    modelAndView.addObject("tagslink", CONTEXT_PATH + TAGSLINK);
    modelAndView.addObject("settingslink", CONTEXT_PATH + SETTINGSLINK);
    modelAndView.addObject("translatelink", CONTEXT_PATH + TRANSLATELINK);
    modelAndView.addObject("reportslink", CONTEXT_PATH + REPORTSLINK);
    modelAndView.addObject("adminlink", CONTEXT_PATH + ADMINLINK);
    modelAndView.addObject("votedownlink", CONTEXT_PATH + VOTEDOWNLINK);
    modelAndView.addObject("voteuplink", CONTEXT_PATH + VOTEUPLINK);
    modelAndView.addObject("questionlink", CONTEXT_PATH + QUESTIONLINK);
    modelAndView.addObject("questionslink", CONTEXT_PATH + QUESTIONSLINK);
    modelAndView.addObject("commentlink", CONTEXT_PATH + COMMENTLINK);
    modelAndView.addObject("postlink", CONTEXT_PATH + POSTLINK);
    modelAndView.addObject("revisionslink", CONTEXT_PATH + REVISIONSLINK);
    modelAndView.addObject("feedbacklink", CONTEXT_PATH + FEEDBACKLINK);
    modelAndView.addObject("languageslink", CONTEXT_PATH + LANGUAGESLINK);
    // Visual customization
    modelAndView.addObject("navbarFixedClass",
            Config.getConfigBoolean("fixed_nav", false) ? "navbar-fixed" : "none");
    modelAndView.addObject("showBranding", Config.getConfigBoolean("show_branding", true));
    modelAndView.addObject("logoUrl", Config.getConfigParam("logo_url", IMAGESLINK + "/logo.svg"));
    modelAndView.addObject("logoWidth", Config.getConfigInt("logo_width", 90));
    modelAndView.addObject("stylesheetUrl", Config.getConfigParam("stylesheet_url", STYLESLINK + "/style.css"));
    // Auth & Badges
    Profile authUser = (Profile) request.getAttribute(AUTH_USER_ATTRIBUTE);
    modelAndView.addObject("infoStripMsg",
            authUser == null ? Config.getConfigParam("welcome_message", "") : "");
    modelAndView.addObject("authenticated", authUser != null);
    modelAndView.addObject("canComment", utils.canComment(authUser, request));
    modelAndView.addObject("isMod", utils.isMod(authUser));
    modelAndView.addObject("isAdmin", utils.isAdmin(authUser));
    modelAndView.addObject("utils", Utils.getInstance());
    modelAndView.addObject("scooldUtils", utils);
    modelAndView.addObject("authUser", authUser);
    modelAndView.addObject("badgelist", utils.checkForBadges(authUser, request));
    modelAndView.addObject("request", request);
    // Spaces
    modelAndView.addObject("currentSpace",
            utils.getValidSpaceId(authUser, getCookieValue(request, SPACE_COOKIE)));
    // Language
    Locale currentLocale = utils.getCurrentLocale(utils.getLanguageCode(request), request);
    modelAndView.addObject("currentLocale", currentLocale);
    modelAndView.addObject("lang", utils.getLang(currentLocale));
    modelAndView.addObject("langDirection", utils.isLanguageRTL(currentLocale.getLanguage()) ? "RTL" : "LTR");
    // Pagination
    // check for AJAX pagination requests
    if (utils.isAjaxRequest(request) && (utils.param(request, "page") || utils.param(request, "page1")
            || utils.param(request, "page2"))) {
        modelAndView.setViewName("pagination"); // switch to page fragment view
    }
    // CSP, HSTS, etc, headers. See https://securityheaders.com
    utils.setSecurityHeaders(request, response);

    // default metadata for social meta tags
    if (!modelAndView.getModel().containsKey("title")) {
        modelAndView.addObject("title", Config.APP_NAME);
    }
    if (!modelAndView.getModel().containsKey("description")) {
        modelAndView.addObject("description", Config.getConfigParam("meta_description", ""));
    }
    if (!modelAndView.getModel().containsKey("ogimage")) {
        modelAndView.addObject("ogimage", IMAGESLINK + "/logowhite.png");
    }
}

From source file:gobblin.metrics.event.sla.SlaEventSubmitter.java

/**
 * Construct an {@link SlaEventSubmitter} by extracting Sla event metadata from the properties. See
 * {@link SlaEventKeys} for keys to set in properties
 * <p>//from  ww w . ja v  a  2  s . c  om
 * The <code>props</code> MUST have required property {@link SlaEventKeys#DATASET_URN_KEY} set.<br>
 * All properties with prefix {@link SlaEventKeys#EVENT_ADDITIONAL_METADATA_PREFIX} will be automatically added as
 * event metadata
 * </p>
 * <p>
 * Use {@link SlaEventSubmitter#builder()} to build an {@link SlaEventSubmitter} directly with event metadata.
 * </p>
 *
 * @param submitter used to submit the event
 * @param name of the event
 * @param props reference that contains event metadata
 */
public SlaEventSubmitter(EventSubmitter submitter, String name, Properties props) {

    this.eventName = name;
    this.eventSubmitter = submitter;
    this.datasetUrn = props.getProperty(SlaEventKeys.DATASET_URN_KEY);
    if (props.containsKey(SlaEventKeys.DATASET_URN_KEY)) {
        this.datasetUrn = props.getProperty(SlaEventKeys.DATASET_URN_KEY);
    } else {
        this.datasetUrn = props.getProperty(ConfigurationKeys.DATASET_URN_KEY);
    }
    this.partition = props.getProperty(SlaEventKeys.PARTITION_KEY);
    this.originTimestamp = props.getProperty(SlaEventKeys.ORIGIN_TS_IN_MILLI_SECS_KEY);
    this.upstreamTimestamp = props.getProperty(SlaEventKeys.UPSTREAM_TS_IN_MILLI_SECS_KEY);
    this.completenessPercentage = props.getProperty(SlaEventKeys.COMPLETENESS_PERCENTAGE_KEY);
    this.recordCount = props.getProperty(SlaEventKeys.RECORD_COUNT_KEY);
    this.previousPublishTimestamp = props.getProperty(SlaEventKeys.PREVIOUS_PUBLISH_TS_IN_MILLI_SECS_KEY);
    this.dedupeStatus = props.getProperty(SlaEventKeys.DEDUPE_STATUS_KEY);
    this.isFirstPublish = props.getProperty(SlaEventKeys.IS_FIRST_PUBLISH);

    this.additionalMetadata = Maps.newHashMap();
    for (Entry<Object, Object> entry : props.entrySet()) {
        if (StringUtils.startsWith(entry.getKey().toString(), SlaEventKeys.EVENT_ADDITIONAL_METADATA_PREFIX)) {
            this.additionalMetadata.put(StringUtils.removeStart(entry.getKey().toString(),
                    SlaEventKeys.EVENT_ADDITIONAL_METADATA_PREFIX), entry.getValue().toString());
        }
    }
}

From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java

/**
 * Copies a directory from a {@link JarURLConnection} to a destination
 * Directory outside the jar./*from   w  ww.  j a  v  a  2  s  .c  o m*/
 * 
 * @param destDir
 * @param jarConnection
 * @return true if copy is successful, false otherwise.
 * @throws IOException
 */
public static boolean copyJarResourcesRecursively(final File destDir, final JarURLConnection jarConnection)
        throws IOException {
    logger.debug("copyJarResourcesRecursively()");
    boolean success = true;
    final JarFile jarFile = jarConnection.getJarFile();

    for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
        final JarEntry entry = e.nextElement();
        if (entry.getName().startsWith(jarConnection.getEntryName())) {
            final String filename = StringUtils.removeStart(entry.getName(), //
                    jarConnection.getEntryName());

            final File f = new File(destDir, filename);
            if (!entry.isDirectory()) {
                final InputStream entryInputStream = jarFile.getInputStream(entry);
                if (!FileInstaller.copyStream(entryInputStream, f)) {
                    success = false;
                    logger.debug("returning " + success);
                    return success;
                }
                entryInputStream.close();
            } else {
                if (!FileInstaller.ensureDirectoryExists(f)) {
                    logger.debug("throwing an IOException");
                    throw new IOException("Could not create directory: " + f.getAbsolutePath());
                }
            }
        }
    }
    logger.debug("returning " + success);
    return success;
}

From source file:it.polimi.meteocal.ejb.HandleAuthFacebookImpl.java

@Override
public boolean doLoginFacebook(String faceCode) {
    if (faceCode != null && !"".equals(faceCode)) {
        String redirectUrl = URL_BASE + "/MeteoCal-web/loginFacebook.xhtml";
        String newUrl = "https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&redirect_uri="
                + redirectUrl + "&client_secret=" + APPSECRET + "&code=" + faceCode;
        LOGGER.log(Level.INFO, "URL FB: " + newUrl);
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        try {/*from   ww  w  . j  a  v  a2s . c om*/
            HttpGet httpget = new HttpGet(newUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httpget, responseHandler);
            LOGGER.log(Level.INFO, "Response Body: " + responseBody);
            accessToken = StringUtils.removeStart(responseBody, "access_token=");
            int i = accessToken.indexOf("&");
            accessToken = accessToken.substring(0, i);
            LOGGER.log(Level.INFO, "AccessToken: " + accessToken);

            facebookClient = new DefaultFacebookClient(accessToken, APPSECRET, Version.VERSION_2_5);
            com.restfb.types.User userFB = facebookClient.fetchObject("me", com.restfb.types.User.class);

            if (!AuthUtil.isUserLogged()) {
                // Save the new data of the user
                User utente;
                TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_FACEBOOK_ID, User.class);
                q.setParameter("facebookId", userFB.getId());

                TypedQuery<User> q2 = em.createNamedQuery(User.FIND_BY_EMAIL, User.class);
                q2.setParameter("email", userFB.getEmail());

                if (q.getResultList().isEmpty() && q2.getResultList().isEmpty()) {
                    // The userFB isn't in the system
                    utente = setupNewUser(userFB);
                    em.persist(utente);
                    em.flush();
                    em.refresh(utente);
                } else if (!q.getResultList().isEmpty()) {
                    // The User is already in the system with fb
                    LOGGER.log(Level.INFO, "User already registered with Facebook");
                    utente = q.getResultList().get(0);
                    if (utente.getFacebookToken().equals(accessToken)) {
                        LOGGER.log(Level.INFO, "Facebook token no needed change");
                    } else {
                        LOGGER.log(Level.INFO, "Facebook token updated");
                        utente.setFacebookToken(accessToken);
                        em.merge(utente);
                        em.flush();
                    }

                } else {
                    LOGGER.log(Level.INFO, "User already registered with classic method");
                    utente = q2.getResultList().get(0);
                    //TODO merge informazioni da facebook mancanti

                    em.merge(utente);
                    em.flush();

                }

                // Make the session for the user
                AuthUtil.makeUserSession(utente.getId());

            } else {
                // User already logged in the system
                User utente = em.find(User.class, AuthUtil.getUserID());

                TypedQuery<User> q = em.createNamedQuery(User.FIND_BY_FACEBOOK_ID, User.class);
                q.setParameter("facebookId", userFB.getId());
                if (q.getResultList().isEmpty()) {
                    // The user account isn't already present in the db so set the new FB data
                    utente.setFacebookId(userFB.getId());
                    utente.setFacebookToken(accessToken);
                    em.merge(utente);
                    em.flush();
                } else {

                    // User account already in the system
                    LOGGER.log(Level.INFO, "User already registered with Facebook");
                    User oldUser = q.getResultList().get(0);
                    if (!Objects.equals(utente.getId(), oldUser.getId())) {
                        // Need to merge the two account
                        utente = HandleUserImpl.mergeUserAccount(utente, oldUser);

                        // set the new facebook data
                        utente.setFacebookId(userFB.getId());
                        utente.setFacebookToken(accessToken);

                        em.merge(utente);
                        em.flush();

                        // Transfer all the data that can block the old user remove
                        HandleUserImpl.mergeOldUserNewUser(em, utente, oldUser);

                        em.remove(oldUser);
                        em.flush();
                    }
                }

            }

        } catch (ClientProtocolException e) {
            LOGGER.log(Level.ERROR, e);
        } catch (IOException e) {
            LOGGER.log(Level.ERROR, e);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {

                LOGGER.log(Level.WARN, e);
            }
        }
    }

    return true;
}

From source file:com.neatresults.mgnltweaks.ui.column.ColumnFormatterUtils.java

private static Button createButton(final String title, final String appName, final String subAppName,
        final String path, final Object itemId, final String rootPath, EventBus adminEventBus,
        EventBus eventBus, NeatTweaks4DevelopersModule module) {
    Button selectButton = new NativeButton();
    selectButton.addStyleName("neatmagnoliabutton");
    selectButton.setCaption(title);/*from www  .  j a  va2s  .com*/
    selectButton.addClickListener(new ClickListener() {

        @Override
        public void buttonClick(ClickEvent event) {
            String workPath = path;
            if (StringUtils.isNotBlank(rootPath) && !"/".equals(rootPath)) {
                workPath = StringUtils.removeStart(workPath, rootPath);
            }
            if ("browser".equals(subAppName)) {
                Location location = new BrowserLocation(appName, subAppName, workPath + ":treeview:");
                adminEventBus.fireEvent(new LocationChangedEvent(location));
            } else {
                // open app (subapp)
                Location location = new RerootBrowserLocation(appName, subAppName, workPath,
                        module.isShowSubtreeOnlyInHelper());
                adminEventBus.fireEvent(new LocationChangedEvent(location));
                // expand selected node
                try {
                    ContentChangedEvent cce = new ContentChangedEvent(
                            JcrItemUtil.getItemId(RepositoryConstants.CONFIG, path), true);
                    eventBus.fireEvent(cce);
                } catch (RepositoryException e) {
                    log.error(
                            "Ooops, failed to retrieve node at path {} and open it while trying to open definition with {}",
                            path, e.getMessage(), e);
                }
            }
        }
    });
    return selectButton;
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

/** {@inheritDoc} */
@Override/*from   ww  w  . ja  va2  s  .  co m*/
public void execute() throws MojoExecutionException {
    if (skip) {
        getLog().info("Skipping type transformation!");
        return;
    }

    trackExecution("start");

    final ClassLoader classLoader = getClassloader();
    final List<ClassFileTransformer> transformers = getClassFileTransformers(classLoader);

    List<File> classFiles = FileUtils.getFiles(project.getBuild().getOutputDirectory(),
            f -> f.getAbsolutePath().endsWith(".class"));
    getLog().debug("Found class files for processing: "
            + classFiles.stream().map(f -> f.getName()).collect(Collectors.joining(", ")));

    if (CollectionUtils.isNotEmpty(transformers)) {
        if (CollectionUtils.isNotEmpty(classFiles)) {
            getLog().info(String.format("Transforming %s classes", classFiles.size()));

            for (final File f : classFiles) {
                if (f.getName().endsWith(Constants.CLASS_EXTENSION)) {
                    String relativeClassFilePath = StringUtils.remove(f.getPath(),
                            project.getBuild().getOutputDirectory());
                    relativeClassFilePath = StringUtils.removeStart(relativeClassFilePath, "/");
                    final String className = relativeClassFilePath.substring(0,
                            relativeClassFilePath.length() - Constants.CLASS_EXTENSION.length());

                    trackExecution("Loading class: " + f.getAbsolutePath());

                    byte[] byteCode;
                    try {
                        byteCode = Files.readAllBytes(f.toPath());
                    } catch (final IOException e) {
                        String message = String.format("Can't read bytecode for class %s", className);
                        buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                        throw new IllegalStateException(message, e);
                    }

                    trackExecution("Loaded class: " + f.getAbsolutePath());

                    for (final ClassFileTransformer t : transformers) {
                        try {

                            // log exceptions into separate folder, to be able to inspect them even if Eclipse swallows them ...
                            if (t instanceof AbstractBaseClassTransformer) {
                                ((AbstractBaseClassTransformer) t).setErrorLogger(this::logError);
                            }

                            // returns null if nothing has been transformed
                            byteCode = t.transform(classLoader, className, null, null, byteCode);
                        } catch (final Exception e) {
                            String exception = "Exception during transformation of class: "
                                    + f.getAbsolutePath() + "\n" + e.getMessage();
                            trackExecution(exception);
                            String message = String.format("Can't transform class %s, transformer %s: %s",
                                    className, t.getClass().getSimpleName(), ExceptionUtils.getStackTrace(e));
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new MojoExecutionException(exception, e);
                        }
                    }

                    if (byteCode != null && byteCode.length > 0) {
                        try {
                            Files.write(f.toPath(), byteCode, StandardOpenOption.CREATE,
                                    StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING);

                            trackExecution("Saved transformed class: " + f.getAbsolutePath());
                        } catch (final IOException e) {
                            String message = "Could not write modified class: " + relativeClassFilePath;
                            buildContext.addMessage(f, 0, 0, message, BuildContext.SEVERITY_ERROR, e);
                            throw new IllegalStateException(message);
                        } finally {
                            buildContext.refresh(f);
                            getLog().info("Applied transformation to type: " + f.getAbsolutePath());
                        }
                    } else {
                        trackExecution("No changes made for class: " + f.getAbsolutePath());
                        getLog().debug("No transformation was applied to type: " + f.getAbsolutePath());
                    }
                }
            }
        } else {
            getLog().info("No class files found");
        }

        trackExecution("All classes in build output folder transformed");

        if (includeJars) {
            final String packaging = project.getPackaging();
            final Artifact artifact = project.getArtifact();

            if ("jar".equals(packaging) && artifact != null) {
                try {
                    final File source = artifact.getFile();

                    if (source.isFile()) {
                        final File destination = new File(source.getParent(), "instrument.jar");

                        final JarTransformer transformer = new JarTransformer(getLog(), classLoader,
                                Arrays.asList(source), transformers);
                        transformer.transform(destination);

                        final File sourceRename = new File(source.getParent(),
                                "notransform-" + source.getName());

                        if (source.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    source.toString(), sourceRename.toString()));
                        }

                        if (destination.renameTo(sourceRename)) {
                            throw new MojoExecutionException(String.format("Could not move %s to %s",
                                    destination.toString(), sourceRename.toString()));
                        }

                        buildContext.refresh(destination);
                    }
                } catch (final Exception e) {
                    buildContext.addMessage(artifact.getFile(), 0, 0, e.getMessage(),
                            BuildContext.SEVERITY_ERROR, e);
                    throw new MojoExecutionException(e.getMessage(), e);
                }
            } else {
                getLog().debug(String.format("Artifact %s not a jar file",
                        artifact != null ? (artifact.getGroupId() + ":" + artifact.getArtifactId())
                                : "<null>"));
            }
        }
    } else {
        getLog().info("No class transformers configured");
    }
}