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

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

Introduction

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

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:jp.mathes.databaseWiki.web.DbwServlet.java

private void handleHttp(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    req.setCharacterEncoding("UTF-8");
    resp.setCharacterEncoding("UTF-8");
    String user = null;//from  ww  w  .  j a v a  2 s  .  co  m
    String password = null;
    if (req.getHeader("Authorization") != null) {
        String[] split = req.getHeader("Authorization").split(" ");
        String userpw = "";
        if (split.length > 1) {
            userpw = new String(Base64.decodeBase64(split[1]));
        }
        user = StringUtils.substringBefore(userpw, ":");
        password = StringUtils.substringAfter(userpw, ":");
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/xhtml+xml; charset=UTF-8");
        try {
            this.handleAction(req, resp, user, password);
        } catch (InstantiationException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Could not instantiate database backend: " + e.getMessage());
        } catch (IllegalAccessException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Illegal Access: " + e.getMessage());
        } catch (ClassNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "Could not find database backend: " + e.getMessage());
        } catch (TemplateException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Template error: " + e.getMessage());
        } catch (BackendException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error: " + e.getMessage());
        } catch (PluginException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Rendering error: " + e.getMessage());
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setHeader("WWW-Authenticate", "Basic realm=\"databaseWiki\"");
    }
}

From source file:kenh.expl.impl.ExpLParser.java

/**
 * Invoke functioin, support name space. For example, expl:contains(...).
 * @param function/*from   ww  w.j  a  v  a 2s .  c  o  m*/
 * @return  Return string or non-string object. Return empty string instead of null.
 */
private Object executeFunction(String function) throws UnsupportedExpressionException { // function should return a string object;

    if (StringUtils.isBlank(function)) {
        UnsupportedExpressionException e = new UnsupportedExpressionException("Function is null.");
        throw e;
    }

    logger.trace("Func: " + function);

    String parameter = StringUtils.substringBeforeLast(StringUtils.substringAfter(function, "("), ")");

    String[] parts = splitParameter(parameter);
    String funcName = StringUtils.substringBetween(function, "#", "(");
    String nameSpace = null;

    if (StringUtils.contains(funcName, ":")) {
        nameSpace = StringUtils.substringBefore(funcName, ":");
        funcName = StringUtils.substringAfter(funcName, ":");
    }

    if (StringUtils.isBlank(funcName)) {
        UnsupportedExpressionException e = new UnsupportedExpressionException("Failure to get function name");
        e.push(function);
        throw e;
    }

    Object[] objs = new Object[parts.length];
    int i = 0;
    for (String part : parts) {
        if (part.indexOf('{') != -1) {
            Object obj = this.parseExpress(part);
            objs[i++] = obj;
        } else {
            objs[i++] = part;
        }
    }

    try {
        // instantiate it, and create the parameters
        Function func = this.getEnvironment().getFunction(nameSpace, funcName);
        if (func == null)
            throw new UnsupportedExpressionException("Can't find the function. ["
                    + (StringUtils.isBlank(nameSpace) ? funcName : nameSpace + ":" + funcName) + "]");

        func.setEnvironment(this.getEnvironment());

        // invoke
        return func.invoke(objs);
    } catch (UnsupportedExpressionException e) {
        e.push(function);
        throw e;

    } catch (Exception ex) {
        UnsupportedExpressionException e = new UnsupportedExpressionException(ex);
        e.push(function);
        throw e;
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

private void addEmailAttachmentsToJob(final DepositEmailConfiguration depositEmailConfiguration,
        final MimeMessage mimeMessage, final MultiFilesJob job)
        throws MessagingException, IOException, FileNotFoundException {

    final String jobConfigurationFileName = depositEmailConfiguration.getJobConfigurationFileName();
    if (StringUtils.isNotBlank(jobConfigurationFileName)) {
        final File jobConfigurationFile = getJobConfigurationFile(
                depositEmailConfiguration.getApplicationName(), jobConfigurationFileName);
        job.addFile(Constants.MULTIPLE_FILES_JOB_CONFIGURATION, new FileInputStream(jobConfigurationFile));
    }//from   w  w w . ja va  2s  .  c  o m

    final Object content = mimeMessage.getContent();
    Validate.isTrue(content instanceof Multipart, "only multipart emails can be processed");

    final Multipart multipart = (Multipart) content;
    for (int i = 0, n = multipart.getCount(); i < n; i++) {
        final Part part = multipart.getBodyPart(i);

        final String disposition = part.getDisposition();

        if ((disposition != null)
                && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) {
            final String name = part.getFileName();
            final String contentType = StringUtils.substringBefore(part.getContentType(), ";");
            MultiFilesJob.addDataToJob(contentType, name, part.getInputStream(), job);
        }
    }
}

From source file:com.zhumeng.dream.orm.PropertyFilter.java

private void init(final String filterName, final Object value, String propertyNameStr) {
    String firstPart = StringUtils.substringBefore(filterName, "_");

    String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);

    String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());

    try {//from w w  w .j a va  2 s.  co  m
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    // String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    Assert.isTrue(StringUtils.isNotBlank(propertyNameStr),
            "filter??" + filterName + ",??.");

    propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);

}

From source file:de.jcup.egradle.sdk.builder.action.javadoc.ReplaceJavaDocPartsAction.java

License:asdf

private String replaceCommentInLine(String text) {
    if (text.indexOf("//") == -1) {
        return text;
    }//from w ww  .  j  a  v a  2 s . c om
    String before = StringUtils.substringBefore(text, "//");
    int lastindexOpening = before.lastIndexOf('<');
    int lastindexClosing = before.lastIndexOf('>');
    if (lastindexOpening > lastindexClosing) {
        /*
         * e.g. a "< // comment" or a "<><//comment" which will be ignored
         */
        return text;
    }

    String after = StringUtils.substringAfter(text, "//");
    StringBuilder sb = new StringBuilder();
    sb.append(before);
    sb.append("<em class='comment'>//");
    if (after.endsWith("\n")) {
        sb.append(StringUtils.substringBeforeLast(after, "\n"));
        sb.append("</em>\n");

    } else {
        sb.append(after);
        sb.append("</em>");
    }
    return sb.toString();
}

From source file:com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementService.java

private ServiceLevelAgreement saveAndScheduleSla(ServiceLevelAgreementGroup serviceLevelAgreement,
        FeedMetadata feed) {/* ww  w. ja  v  a2s .  c o m*/
    return metadataAccess.commit(() -> {

        if (serviceLevelAgreement != null) {
            ServiceLevelAgreementMetricTransformerHelper transformer = new ServiceLevelAgreementMetricTransformerHelper();
            if (feed != null) {
                transformer.applyFeedNameToCurrentFeedProperties(serviceLevelAgreement,
                        feed.getCategory().getSystemName(), feed.getSystemFeedName());
            }
            ServiceLevelAgreement sla = transformer.getServiceLevelAgreement(serviceLevelAgreement);

            ServiceLevelAgreementBuilder slaBuilder = null;
            com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement.ID existingId = null;
            if (StringUtils.isNotBlank(sla.getId())) {
                existingId = slaProvider.resolve(sla.getId());
            }
            if (existingId != null) {
                slaBuilder = slaProvider.builder(existingId);
            } else {
                slaBuilder = slaProvider.builder();
            }

            slaBuilder.name(sla.getName()).description(sla.getDescription());
            for (com.thinkbiganalytics.metadata.rest.model.sla.ObligationGroup group : sla.getGroups()) {
                ObligationGroupBuilder groupBuilder = slaBuilder
                        .obligationGroupBuilder(ObligationGroup.Condition.valueOf(group.getCondition()));
                for (Obligation o : group.getObligations()) {
                    groupBuilder.obligationBuilder().metric(o.getMetrics()).description(o.getDescription())
                            .build();
                }
                groupBuilder.build();
            }
            com.thinkbiganalytics.metadata.sla.api.ServiceLevelAgreement savedSla = slaBuilder.build();

            List<ServiceLevelAgreementActionConfiguration> actions = transformer
                    .getActionConfigurations(serviceLevelAgreement);

            // now assign the sla checks
            slaProvider.slaCheckBuilder(savedSla.getId()).removeSlaChecks().actionConfigurations(actions)
                    .build();

            //all referencing Feeds
            List<String> systemCategoryAndFeedNames = transformer.getCategoryFeedNames(serviceLevelAgreement);
            Set<Feed> slaFeeds = new HashSet<Feed>();
            Set<Feed.ID> slaFeedIds = new HashSet<Feed.ID>();
            for (String categoryAndFeed : systemCategoryAndFeedNames) {
                //fetch and update the reference to the sla
                String categoryName = StringUtils.trim(StringUtils.substringBefore(categoryAndFeed, "."));
                String feedName = StringUtils.trim(StringUtils.substringAfterLast(categoryAndFeed, "."));
                Feed feedEntity = feedProvider.findBySystemName(categoryName, feedName);
                if (feedEntity != null) {
                    slaFeeds.add(feedEntity);
                    slaFeedIds.add(feedEntity.getId());
                }
            }

            if (feed != null) {
                Feed.ID feedId = feedProvider.resolveFeed(feed.getFeedId());
                if (!slaFeedIds.contains(feedId)) {
                    Feed feedEntity = feedProvider.getFeed(feedId);
                    slaFeeds.add(feedEntity);
                }
            }
            //relate them
            feedSlaProvider.relateFeeds(savedSla, slaFeeds);
            com.thinkbiganalytics.metadata.rest.model.sla.FeedServiceLevelAgreement restModel = ServiceLevelAgreementModelTransform
                    .toModel(savedSla, slaFeeds, true);
            //schedule it
            serviceLevelAgreementScheduler.scheduleServiceLevelAgreement(savedSla);
            return restModel;

        }
        return null;

    });

}

From source file:com.joint.base.util.excel.ImportExcel.java

/**
* ??/*from  www. ja v a2  s  .  c o m*/
* @param cls 
* @param groups 
*/
public <E> List<E> getDataList(Class<E> cls, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field
    Field[] fs = cls.getDeclaredFields();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);
        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                if (StringUtils.isNotBlank(ef.dictType())) {
                    //val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                    //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.wso2.code.quality.matrices.ChangesFinder.java

/**
 * This method will iterate over the saved filenames and their relevant changed line ranges and calls the github graphQL API
 * for getting blame details for each of the files
 *
 * @param repoLocation current selected repository
 * @param commitHash   current selected repository
 * @param gitHubToken  github token for accessing github GraphQL API
 *///  ww w .j a v a  2 s  .  c o  m
public void iterateOverFileChanges(String repoLocation, String commitHash, String gitHubToken) {

    // filtering the owner and the repository name from the repoLocation
    String owner = StringUtils.substringBefore(repoLocation, "/");
    String repositoryName = StringUtils.substringAfter(repoLocation, "/");
    //        iterating over the fileNames arraylist for the given commit
    //         cannot use parallel streams here as the order of the file names is important in the process
    fileNames.stream().forEach(fileName -> {
        int index = fileNames.indexOf(fileName);
        // the relevant arraylist of changed lines for that file
        ArrayList<String> arrayListOfRelevantChangedLinesOfSelectedFile = lineRangesChanged.get(index);
        commitHashesMapOfTheParent = new HashMap<>(); // for storing the parent commit hashes for all the changed line ranges of the relevant file
        graphqlApiJsonObject.put("query", "{repository(owner:\"" + owner + "\",name:\"" + repositoryName
                + "\"){object(expression:\"" + commitHash + "\"){ ... on Commit{blame(path:\"" + fileName
                + "\"){ranges{startingLine endingLine age commit{history(first: 2) { edges { node {  message url } } } author { name email } } } } } } } }");
        JSONObject rootJsonObject = null;
        try {
            //            calling the graphql API for getting blame information for the current file.
            rootJsonObject = (JSONObject) graphQlApiCaller.callGraphQlApi(graphqlApiJsonObject, gitHubToken);
        } catch (CodeQualityMatricesException e) {
            logger.error(e.getMessage(), e.getCause()); // as exceptions cannot be thrown inside lambda expression
            System.exit(1);
        }
        //            reading the above saved output for the current selected file name
        readBlameReceivedForAFile(rootJsonObject, arrayListOfRelevantChangedLinesOfSelectedFile, false, null);
        logger.info("Parent Commits hashes of the lines which are being fixed by the patch in file " + fileName
                + " are saved to commitHashesMapOfTheParent map successfully ");

        iterateOverToFindAuthors(owner, repositoryName, fileName, arrayListOfRelevantChangedLinesOfSelectedFile,
                gitHubToken);
        logger.info(
                "Authors of the bug lines of code which are being fixed from the given patch are saved successfully to authorNames SET");
    });
}

From source file:io.cloudex.cloud.impl.google.GoogleCloudServiceImpl.java

/**
 * Perform initialization before/*from  w  ww .ja v  a2  s . c  o  m*/
 * this cloud service is used
 * @throws IOException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public VmMetaData init() throws IOException {

    // can't do anything without an authentication provider
    Validate.notNull(this.authenticationProvider);

    Map<String, Object> attributes = null;
    String fingerprint = null;

    this.getHttpTransport();

    if (this.remote) {
        // if not running on a vm on the cloud environment, then
        // these values need to be set externally
        Validate.notNull(this.zone);
        Validate.notNull(this.projectId);
        Validate.notNull(this.instanceId);
        Validate.notNull(this.scopes);

        Credential credential = (Credential) this.authenticationProvider.authorize();

        this.getCompute(credential);
        this.getStorage(credential);
        this.getBigquery(credential);

    } else {
        this.projectId = GoogleMetaData.getMetaData(PROJECT_ID_PATH);
        Map<String, Object> metaData = GoogleMetaData.getMetaDataAsMap(INSTANCE_ALL_PATH);
        attributes = (Map<String, Object>) metaData.get(ATTRIBUTES);

        // strangely zone looks like this: "projects/315344313954/zones/us-central1-a"
        this.zone = (String) metaData.get(ZONE);
        this.zone = StringUtils.substringAfterLast(this.zone, "/");

        // the name isn't returned!, but the hostname looks like this:
        // "ecarf-evm-1.c.ecarf-1000.internal"
        this.instanceId = (String) metaData.get(HOSTNAME);
        this.instanceId = StringUtils.substringBefore(this.instanceId, ".");

        // get the default service account
        Map<String, Object> serviceAccountConfig = ((Map) ((Map) metaData.get(SERVICE_ACCOUNTS)).get(DEFAULT));
        this.serviceAccount = (String) serviceAccountConfig.get(EMAIL);
        this.scopes = (List) serviceAccountConfig.get(SCOPES);
        // add the datastore scope as well
        this.scopes.add(DATASTORE_SCOPE);

        // no need for this call right now
        //this.authorise();
        this.getCompute();
        this.getStorage();
        this.getBigquery();

        boolean retrying = true;
        int retries = 0;
        Instance instance = null;

        do {
            try {
                // java.net.SocketTimeoutException: connect timed out
                instance = this.getInstance(instanceId, zone);
                retrying = false;

            } catch (IOException e) {
                log.error("Failed to retrieve instance details, retries: " + retries, e);
                retries++;
                if (retries > 3) {
                    throw e;
                }
                ApiUtils.block(this.getApiRecheckDelay());
            }

        } while (retrying);

        fingerprint = instance.getMetadata().getFingerprint();
    }

    log.debug("Successfully initialized Google Cloud Service: " + this);
    return new VmMetaData(attributes, fingerprint);

}

From source file:cgeo.geocaching.CacheDetailActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState, R.layout.cachedetail_activity);

    // get parameters
    final Bundle extras = getIntent().getExtras();
    final Uri uri = AndroidBeam.getUri(getIntent());

    // try to get data from extras
    String name = null;//from  ww  w  .  ja va2s. c om
    String guid = null;

    if (extras != null) {
        geocode = extras.getString(Intents.EXTRA_GEOCODE);
        name = extras.getString(Intents.EXTRA_NAME);
        guid = extras.getString(Intents.EXTRA_GUID);
    }

    // When clicking a cache in MapsWithMe, we get back a PendingIntent
    if (StringUtils.isEmpty(geocode)) {
        geocode = MapsMeCacheListApp.getCacheFromMapsWithMe(this, getIntent());
    }

    if (geocode == null && uri != null) {
        geocode = ConnectorFactory.getGeocodeFromURL(uri.toString());
    }

    // try to get data from URI
    if (geocode == null && guid == null && uri != null) {
        final String uriHost = uri.getHost().toLowerCase(Locale.US);
        final String uriPath = uri.getPath().toLowerCase(Locale.US);
        final String uriQuery = uri.getQuery();

        if (uriQuery != null) {
            Log.i("Opening URI: " + uriHost + uriPath + "?" + uriQuery);
        } else {
            Log.i("Opening URI: " + uriHost + uriPath);
        }

        if (uriHost.contains("geocaching.com")) {
            if (StringUtils.startsWith(uriPath, "/geocache/gc")) {
                geocode = StringUtils.substringBefore(uriPath.substring(10), "_").toUpperCase(Locale.US);
            } else {
                geocode = uri.getQueryParameter("wp");
                guid = uri.getQueryParameter("guid");

                if (StringUtils.isNotBlank(geocode)) {
                    geocode = geocode.toUpperCase(Locale.US);
                    guid = null;
                } else if (StringUtils.isNotBlank(guid)) {
                    geocode = null;
                    guid = guid.toLowerCase(Locale.US);
                } else {
                    showToast(res.getString(R.string.err_detail_open));
                    finish();
                    return;
                }
            }
        }
    }

    // no given data
    if (geocode == null && guid == null) {
        showToast(res.getString(R.string.err_detail_cache));
        finish();
        return;
    }

    // If we open this cache from a search, let's properly initialize the title bar, even if we don't have cache details
    setCacheTitleBar(geocode, name, null);

    final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(this, progress);

    try {
        String title = res.getString(R.string.cache);
        if (StringUtils.isNotBlank(name)) {
            title = name;
        } else if (geocode != null && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank()
            title = geocode;
        }
        progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true,
                loadCacheHandler.disposeMessage());
    } catch (final RuntimeException ignored) {
        // nothing, we lost the window
    }

    final int pageToOpen = savedInstanceState != null ? savedInstanceState.getInt(STATE_PAGE_INDEX, 0)
            : Settings.isOpenLastDetailsPage() ? Settings.getLastDetailsPage() : 1;
    createViewPager(pageToOpen, new OnPageSelectedListener() {

        @Override
        public void onPageSelected(final int position) {
            if (Settings.isOpenLastDetailsPage()) {
                Settings.setLastDetailsPage(position);
            }
            // lazy loading of cache images
            if (getPage(position) == Page.IMAGES) {
                loadCacheImages();
            }
            requireGeodata = getPage(position) == Page.DETAILS;
            startOrStopGeoDataListener(false);

            // dispose contextual actions on page change
            if (currentActionMode != null) {
                currentActionMode.finish();
            }
        }
    });
    requireGeodata = pageToOpen == 1;

    final String realGeocode = geocode;
    final String realGuid = guid;
    AndroidRxUtils.networkScheduler.scheduleDirect(new Runnable() {
        @Override
        public void run() {
            search = Geocache.searchByGeocode(realGeocode, StringUtils.isBlank(realGeocode) ? realGuid : null,
                    false, loadCacheHandler);
            loadCacheHandler.sendMessage(Message.obtain());
        }
    });

    // Load Generic Trackables
    if (StringUtils.isNotBlank(geocode)) {
        AndroidRxUtils.bindActivity(this,
                // Obtain the active connectors and load trackables in parallel.
                Observable.fromIterable(ConnectorFactory.getGenericTrackablesConnectors())
                        .flatMap(new Function<TrackableConnector, Observable<Trackable>>() {
                            @Override
                            public Observable<Trackable> apply(final TrackableConnector trackableConnector) {
                                processedBrands.add(trackableConnector.getBrand());
                                return Observable.defer(new Callable<Observable<Trackable>>() {
                                    @Override
                                    public Observable<Trackable> call() {
                                        return Observable
                                                .fromIterable(trackableConnector.searchTrackables(geocode));
                                    }
                                }).subscribeOn(AndroidRxUtils.networkScheduler);
                            }
                        }).toList())
                .subscribe(new Consumer<List<Trackable>>() {
                    @Override
                    public void accept(final List<Trackable> trackables) {
                        // Todo: this is not really a good method, it may lead to duplicates ; ie: in OC connectors.
                        // Store trackables.
                        genericTrackables.addAll(trackables);
                        if (!trackables.isEmpty()) {
                            // Update the UI if any trackables were found.
                            notifyDataSetChanged();
                        }
                    }
                });
    }

    locationUpdater = new CacheDetailsGeoDirHandler(this);

    // If we have a newer Android device setup Android Beam for easy cache sharing
    AndroidBeam.enable(this, this);
}