Example usage for org.apache.commons.httpclient.util URIUtil encodeQuery

List of usage examples for org.apache.commons.httpclient.util URIUtil encodeQuery

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util URIUtil encodeQuery.

Prototype

public static String encodeQuery(String unescaped, String charset) throws URIException 

Source Link

Document

Escape and encode a string regarded as the query component of an URI with a given charset.

Usage

From source file:net.hillsdon.fij.text.Escape.java

/**
 * Generate a correctly encoded URI string from the given components.
 * /*from w  w w. jav a2  s  .  c o  m*/
 * @param path The unencoded path. Will be encoded according to RFC3986.
 * @param query The unencoded query. May be null. Will be x-www-form-urlencoded.
 * @param fragment The unencoded fragment. May be null. Will be encoded according to RFC3986.
 * @param extraPath The <strong>encoded</strong> extra part to append to the path.
 * @return
 */
public static String constructEncodedURI(final String path, final String query, final String fragment,
        final String extraPath) {
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(URIUtil.encodeWithinPath(path, "UTF-8"));
        if (extraPath != null) {
            sb.append(extraPath);
        }
        if (query != null) {
            sb.append("?");
            sb.append(URIUtil.encodeQuery(query, "UTF-8"));
        }
        if (fragment != null) {
            sb.append("#");
            sb.append(URIUtil.encodeWithinPath(fragment, "UTF-8"));
        }
        return sb.toString();
    } catch (URIException ex) {
        throw new Error("Java supports UTF-8!", ex);
    }
}

From source file:cz.incad.kramerius.client.tools.Search.java

public JSONObject getUngrouped() {
    try {//w  ww . ja v  a2  s .  c  om

        String q = req.getParameter("q");
        if (q == null || q.equals("")) {
            q = "*:*";
        } else {
            q = URIUtil.encodeQuery(q + getBoost(q), "UTF-8");
        }
        String url = apipoint + "/search" + "?q=" + q + "&wt=json&facet=true" + getStart()
                + getCollectionFilter() + facets + getSort() + getFilters() + otherParams + hlParams;
        return new JSONObject(getJSON(url));
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    } catch (JSONException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:cz.incad.kramerius.client.tools.Search.java

public JSONObject getGrouped() {
    try {//from  w  w  w  .j  a v  a  2 s  .co m

        String q = req.getParameter("q");
        if (q == null || q.equals("")) {
            q = "*:*";
        } else {
            q = URIUtil.encodeQuery(q + getBoost(q), "UTF-8");
        }

        String url = apipoint + "/search" + "?q=" + q + "&wt=json&facet=true&fl=score,*" + getStart()
                + getCollectionFilter() + facets + getSort() + getFilters() + groupedParams + otherParams
                + hlParams;
        return new JSONObject(getJSON(url));
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    } catch (JSONException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:com.liferay.portal.service.impl.UserLocalServiceImpl.java

/**
 * Adds a user with workflow./*w w  w .ja  v a 2 s.  c  om*/
 *
 * <p>
 * This method handles the creation and bookkeeping of the user including
 * its resources, metadata, and internal data structures. It is not
 * necessary to make subsequent calls to any methods to setup default
 * groups, resources, etc.
 * </p>
 *
 * @param  creatorUserId the primary key of the creator
 * @param  companyId the primary key of the user's company
 * @param  autoPassword whether a password should be automatically generated
 *         for the user
 * @param  password1 the user's password
 * @param  password2 the user's password confirmation
 * @param  autoScreenName whether a screen name should be automatically
 *         generated for the user
 * @param  screenName the user's screen name
 * @param  emailAddress the user's email address
 * @param  facebookId the user's facebook ID
 * @param  openId the user's OpenID
 * @param  locale the user's locale
 * @param  firstName the user's first name
 * @param  middleName the user's middle name
 * @param  lastName the user's last name
 * @param  prefixId the user's name prefix ID
 * @param  suffixId the user's name suffix ID
 * @param  male whether the user is male
 * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
 *         January)
 * @param  birthdayDay the user's birthday day
 * @param  birthdayYear the user's birthday year
 * @param  jobTitle the user's job title
 * @param  groupIds the primary keys of the user's groups
 * @param  organizationIds the primary keys of the user's organizations
 * @param  roleIds the primary keys of the roles this user possesses
 * @param  userGroupIds the primary keys of the user's user groups
 * @param  sendEmail whether to send the user an email notification about
 *         their new account
 * @param  serviceContext the user's service context (optionally
 *         <code>null</code>). Can set the universally unique identifier
 *         (with the <code>uuid</code> attribute), asset category IDs, asset
 *         tag names, and expando bridge attributes for the user.
 * @return the new user
 * @throws PortalException if the user's information was invalid
 * @throws SystemException if a system exception occurred
 */
@SuppressWarnings("deprecation")
public User addUserWithWorkflow(long creatorUserId, long companyId, boolean autoPassword, String password1,
        String password2, boolean autoScreenName, String screenName, String emailAddress, long facebookId,
        String openId, Locale locale, String firstName, String middleName, String lastName, int prefixId,
        int suffixId, boolean male, int birthdayMonth, int birthdayDay, int birthdayYear, String jobTitle,
        long[] groupIds, long[] organizationIds, long[] roleIds, long[] userGroupIds, boolean sendEmail,
        ServiceContext serviceContext) throws PortalException, SystemException {

    // User

    Company company = companyPersistence.findByPrimaryKey(companyId);
    screenName = getScreenName(screenName);
    emailAddress = emailAddress.trim().toLowerCase();
    openId = openId.trim();
    Date now = new Date();

    if (PrefsPropsUtil.getBoolean(companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {

        autoScreenName = true;
    }

    long userId = counterLocalService.increment();

    EmailAddressGenerator emailAddressGenerator = EmailAddressGeneratorFactory.getInstance();

    if (emailAddressGenerator.isGenerated(emailAddress)) {
        emailAddress = StringPool.BLANK;
    }

    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED && Validator.isNull(emailAddress)) {

        emailAddress = emailAddressGenerator.generate(companyId, userId);
    }

    validate(companyId, userId, autoPassword, password1, password2, autoScreenName, screenName, emailAddress,
            firstName, middleName, lastName, organizationIds);

    if (!autoPassword) {
        if (Validator.isNull(password1) || Validator.isNull(password2)) {
            throw new UserPasswordException(UserPasswordException.PASSWORD_INVALID);
        }
    }

    if (autoScreenName) {
        ScreenNameGenerator screenNameGenerator = ScreenNameGeneratorFactory.getInstance();

        try {
            screenName = screenNameGenerator.generate(companyId, userId, emailAddress);
        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    User defaultUser = getDefaultUser(companyId);

    FullNameGenerator fullNameGenerator = FullNameGeneratorFactory.getInstance();

    String fullName = fullNameGenerator.getFullName(firstName, middleName, lastName);

    String greeting = LanguageUtil.format(locale, "welcome-x", " " + fullName, false);

    User user = userPersistence.create(userId);

    if (serviceContext != null) {
        String uuid = serviceContext.getUuid();

        if (Validator.isNotNull(uuid)) {
            user.setUuid(uuid);
        }
    }

    user.setCompanyId(companyId);
    user.setCreateDate(now);
    user.setModifiedDate(now);
    user.setDefaultUser(false);
    user.setContactId(counterLocalService.increment());

    if (Validator.isNotNull(password1)) {
        user.setPassword(PwdEncryptor.encrypt(password1));
        user.setPasswordUnencrypted(password1);
    }

    user.setPasswordEncrypted(true);

    PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();

    if ((passwordPolicy != null) && passwordPolicy.isChangeable() && passwordPolicy.isChangeRequired()) {

        user.setPasswordReset(true);
    } else {
        user.setPasswordReset(false);
    }

    user.setDigest(StringPool.BLANK);
    user.setScreenName(screenName);
    user.setEmailAddress(emailAddress);
    user.setFacebookId(facebookId);
    user.setOpenId(openId);
    user.setLanguageId(locale.toString());
    user.setTimeZoneId(defaultUser.getTimeZoneId());
    user.setGreeting(greeting);
    user.setFirstName(firstName);
    user.setMiddleName(middleName);
    user.setLastName(lastName);
    user.setJobTitle(jobTitle);
    user.setStatus(WorkflowConstants.STATUS_DRAFT);
    user.setExpandoBridgeAttributes(serviceContext);

    userPersistence.update(user, false, serviceContext);

    // Resources

    String creatorUserName = StringPool.BLANK;

    if (creatorUserId <= 0) {
        creatorUserId = user.getUserId();

        // Don't grab the full name from the User object because it doesn't
        // have a corresponding Contact object yet

        //creatorUserName = user.getFullName();
    } else {
        User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);

        creatorUserName = creatorUser.getFullName();
    }

    resourceLocalService.addResources(companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
            false, false, false);

    // Contact

    Date birthday = PortalUtil.getDate(birthdayMonth, birthdayDay, birthdayYear,
            ContactBirthdayException.class);

    Contact contact = contactPersistence.create(user.getContactId());

    contact.setCompanyId(user.getCompanyId());
    contact.setUserId(creatorUserId);
    contact.setUserName(creatorUserName);
    contact.setCreateDate(now);
    contact.setModifiedDate(now);
    contact.setAccountId(company.getAccountId());
    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
    contact.setFirstName(firstName);
    contact.setMiddleName(middleName);
    contact.setLastName(lastName);
    contact.setPrefixId(prefixId);
    contact.setSuffixId(suffixId);
    contact.setMale(male);
    contact.setBirthday(birthday);
    contact.setJobTitle(jobTitle);

    contactPersistence.update(contact, false, serviceContext);

    // Group

    try {
        String friendlyURL = StringPool.SLASH + URIUtil.encodeQuery(screenName, "UTF-8");
        groupLocalService.addGroup(user.getUserId(), User.class.getName(), user.getUserId(), null, null, 0,
                friendlyURL, false, true, null);
    } catch (URIException e) {
        _log.error(e);
    }

    // Groups

    if (groupIds != null) {
        groupLocalService.addUserGroups(userId, groupIds);
    }

    addDefaultGroups(userId);

    // Organizations

    updateOrganizations(userId, organizationIds, false);

    // Roles

    if (roleIds != null) {
        roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);

        userPersistence.setRoles(userId, roleIds);
    }

    addDefaultRoles(userId);

    // User groups

    if (userGroupIds != null) {
        if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
            for (long userGroupId : userGroupIds) {
                userGroupLocalService.copyUserGroupLayouts(userGroupId, new long[] { userId });
            }
        }

        userPersistence.setUserGroups(userId, userGroupIds);
    }

    addDefaultUserGroups(userId);

    // Asset

    if (serviceContext != null) {
        updateAsset(creatorUserId, user, serviceContext.getAssetCategoryIds(),
                serviceContext.getAssetTagNames());
    }

    // Indexer

    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
        reindex(user);
    }

    // Workflow

    long workflowUserId = creatorUserId;

    if (workflowUserId == userId) {
        workflowUserId = defaultUser.getUserId();
    }

    ServiceContext workflowServiceContext = serviceContext;

    if (workflowServiceContext == null) {
        workflowServiceContext = new ServiceContext();
    }

    workflowServiceContext.setAttribute("autoPassword", autoPassword);
    workflowServiceContext.setAttribute("sendEmail", sendEmail);

    WorkflowHandlerRegistryUtil.startWorkflowInstance(companyId, workflowUserId, User.class.getName(), userId,
            user, workflowServiceContext);

    if (serviceContext != null) {
        String passwordUnencrypted = (String) serviceContext.getAttribute("passwordUnencrypted");

        if (Validator.isNotNull(passwordUnencrypted)) {
            user.setPasswordUnencrypted(passwordUnencrypted);
        }
    }

    return user;
}

From source file:nl.b3p.viewer.search.OpenLSSearchClient.java

@Override
public SearchResult search(String query) {
    SearchResult result = new SearchResult();
    String queryUrl;//w ww.  j  av a  2s.  co  m
    if (this.url.contains(SEARCHTERM_HOLDER)) {
        queryUrl = this.url.replace(SEARCHTERM_HOLDER, query);
    } else {
        queryUrl = this.url + query;
    }

    JSONArray resultArray = new JSONArray();
    String response = null;
    try {
        String encodedQuery = URIUtil.encodeQuery(queryUrl, "UTF-8");
        response = IOUtils.toString(new URL(encodedQuery).openStream(), "UTF-8");
        GeocodeResponse gecoderResponse = parser.parseOpenLSResponse(response);

        try {
            resultArray = responseToResult(gecoderResponse);
        } catch (JSONException ex) {
            log.error("Error while converting OpenLS result to JSON result", ex);
        }
        result.setResults(resultArray);
        result.setLimitReached(false);
    } catch (IOException ex) {
        log.error("Error while getting OpenLS response", ex);
    }
    return result;
}

From source file:org.apache.eagle.alert.engine.publisher.email.AlertEmailGenerator.java

private Map<String, String> buildAlertContext(AlertStreamEvent event) {
    Map<String, String> alertContext = new HashMap<>();

    if (event.getContext() != null) {
        for (Map.Entry<String, Object> entry : event.getContext().entrySet()) {
            if (entry.getValue() == null) {
                alertContext.put(entry.getKey(), "N/A");
            } else {
                alertContext.put(entry.getKey(), entry.getValue().toString());
            }/*ww w .ja  v  a  2s. c  o m*/
        }
    }

    alertContext.put(PublishConstants.ALERT_EMAIL_SUBJECT, event.getSubject());
    alertContext.put(PublishConstants.ALERT_EMAIL_BODY, getAlertBody(event));
    alertContext.put(PublishConstants.ALERT_EMAIL_POLICY_ID, event.getPolicyId());
    alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_ID, event.getAlertId());
    alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_DATA, event.getDataMap().toString());
    alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_DATA_DESC, generateAlertDataDesc(event));
    alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_CATEGORY, event.getCategory());
    alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_SEVERITY, event.getSeverity().toString());
    alertContext.put(PublishConstants.ALERT_EMAIL_TIME,
            DateTimeUtil.millisecondsToHumanDateWithSeconds(event.getCreatedTime()));
    alertContext.put(PublishConstants.ALERT_EMAIL_STREAM_ID, event.getStreamId());
    alertContext.put(PublishConstants.ALERT_EMAIL_CREATOR, event.getCreatedBy());
    alertContext.put(PublishConstants.ALERT_EMAIL_VERSION, Version.version);

    String rootUrl = this.getServerPort() == 80 ? String.format("http://%s", this.getServerHost())
            : String.format("http://%s:%s", this.getServerHost(), this.getServerPort());
    try {
        alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_DETAIL_URL, String.format("%s/#/alert/detail/%s",
                rootUrl, URIUtil.encodeQuery(event.getAlertId(), "UTF-8")));
        alertContext.put(PublishConstants.ALERT_EMAIL_POLICY_DETAIL_URL, String.format("%s/#/policy/detail/%s",
                rootUrl, URIUtil.encodeQuery(event.getPolicyId(), "UTF-8")));
    } catch (URIException e) {
        LOG.warn(e.getMessage(), e);
        alertContext.put(PublishConstants.ALERT_EMAIL_ALERT_DETAIL_URL,
                String.format("%s/#/alert/detail/%s", rootUrl, event.getAlertId()));
        alertContext.put(PublishConstants.ALERT_EMAIL_POLICY_DETAIL_URL,
                String.format("%s/#/policy/detail/%s", rootUrl, event.getPolicyId()));
    }
    alertContext.put(PublishConstants.ALERT_EMAIL_HOME_URL, rootUrl);
    return alertContext;
}

From source file:org.craftercms.studio.impl.v1.repository.alfresco.AlfrescoContentRepository.java

/**
 * build request URLs /*from   ww w  . ja va2s  .  c  o m*/
 */
protected String buildAlfrescoRequestURL(String uri, Map<String, String> params) throws Exception {
    String url = "";
    String serviceUrlBase = alfrescoUrl + "/service";
    String ticket = getAlfTicket();

    if (params != null) {
        for (String key : params.keySet()) {
            uri = uri.replace("{" + key + "}", URIUtil.encodeQuery(params.get(key), "utf-8"));
        }
    }

    url = serviceUrlBase + uri;
    url += (url.contains("?")) ? "&alf_ticket=" + ticket : "?alf_ticket=" + ticket;

    return url;
}

From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java

private void startOsmLookupEnrichment() {
    // activate the geo position bnode
    enterBnode(this.bnodeIDGeoPos);
    for (int i = 0; i < 2; i++) {
        osmUrl[i] = null;/*from   w  ww  .ja v a 2s . c o  m*/
        urlOsmLookupSearchParameters[1] = null;
    }
    final String firstLiteralOfProperty = getFirstLiteralOfProperty(VcardNs.LOCALITY.uri);
    if (firstLiteralOfProperty != null) {
        // OSM Api doesn't like e.g /Marburg%2FLahn/ but accepts /Marburg/.
        // Having also the postcode we will not encounter ambigous cities
        try {
            this.locality = URIUtil.encodeQuery(
                    (URIUtil.decode(firstLiteralOfProperty, "UTF-8").replaceAll("(.*)\\p{Punct}.*", "$1")),
                    "UTF-8");
        } catch (URIException e1) {
            this.locality = firstLiteralOfProperty;
            e1.printStackTrace();
        }
    }
    this.postalcode = getFirstLiteralOfProperty(VcardNs.POSTAL_CODE.uri);
    this.street = getFirstLiteralOfProperty(VcardNs.STREET_ADDRESS.uri);
    if (!doubles()) {
        this.countryName = getFirstLiteralOfProperty(VcardNs.COUNTRY_NAME.uri);
        if (makeOsmApiSearchParameters()) {
            lookupLocation(); // TODO check whats happening if geo data already in
                              // source file
        }
    }
    if (this.lat != null && this.lon != null) {
        super.literal(GEO_WGS84_POS_LAT, String.valueOf(this.lat));
        super.literal(GEO_WGS84_POS_LONG, String.valueOf(this.lon));
        super.literal(RDF_SYNTAX_NS_TYPE, WGS84_POS_SPATIALTHING);
    }
}

From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java

private void sanitizeStreetnameAndRetrieveOsmApiResultAndStoreLatLon(String regex) throws Exception {
    String tmp = "";
    try {//w w w  .  j  av a 2s.c o m
        tmp = URIUtil.encodeQuery((URIUtil.decode(this.street, "UTF-8").replaceAll(regex, "$1")), "UTF-8");
    } catch (URIException e2) {
        e2.printStackTrace();
    }
    // make new request only if strings differ
    if (!tmp.equals(this.street)) {
        this.street = tmp;
        try {
            if (makeOsmApiSearchParameters()) {
                if (!makeUrlAndLookupIfCached()) {
                    this.osmApiLookupResult = getUrlContent(this.osmUrl[1]);
                    parseJsonAndStoreLatLon();
                }
            }
        } catch (IOException e1) {
            LOG.error(super.subject + " " + e1.getLocalizedMessage());
        }
    }
}

From source file:org.lobid.lodmill.PipeLobidOrganisationEnrichment.java

private String getFirstLiteralOfProperty(String ns) {
    NodeIterator it = this.model.listObjectsOfProperty(this.model.getProperty(ns));
    if (it.hasNext()) {
        try {/*ww  w .j  a  va 2  s.  co  m*/
            return URIUtil.encodeQuery(it.next().asLiteral().getLexicalForm(), "UTF-8");
        } catch (URIException e) {
            LOG.error(super.subject + " " + e.getMessage(), e);
        } catch (LiteralRequiredException le) {
            LOG.warn(le.getMessage(), le);
        }
    }
    return null;
}