Example usage for org.apache.http.client.utils URLEncodedUtils parse

List of usage examples for org.apache.http.client.utils URLEncodedUtils parse

Introduction

In this page you can find the example usage for org.apache.http.client.utils URLEncodedUtils parse.

Prototype

public static List<NameValuePair> parse(final String s, final Charset charset) 

Source Link

Document

Returns a list of NameValuePair NameValuePairs as parsed from the given string using the given character encoding.

Usage

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

@Override
public void onStart() throws ConnectorTaskException {
    String channelId = getChannelId();
    String channelName = getChannel().getName();
    host = replacer.replaceValues(connectorProperties.getListenerConnectorProperties().getHost(), channelId,
            channelName);/*from  w w  w. ja  v  a  2 s. co  m*/
    port = NumberUtils.toInt(replacer.replaceValues(
            connectorProperties.getListenerConnectorProperties().getPort(), channelId, channelName));
    timeout = NumberUtils
            .toInt(replacer.replaceValues(connectorProperties.getTimeout(), channelId, channelName), 0);

    // Initialize contextPath to "" or its value after replacements
    String contextPath = (connectorProperties.getContextPath() == null ? ""
            : replacer.replaceValues(connectorProperties.getContextPath(), channelId, channelName)).trim();

    /*
     * Empty string and "/" are both valid and equal functionally. However if there is a
     * resource defined, we need to make sure that the context path starts with a slash and
     * doesn't end with one.
     */
    if (!contextPath.startsWith("/")) {
        contextPath = "/" + contextPath;
    }
    if (contextPath.endsWith("/")) {
        contextPath = contextPath.substring(0, contextPath.length() - 1);
    }

    try {
        server = new Server();
        configuration.configureReceiver(this);

        HandlerCollection handlers = new HandlerCollection();
        Handler serverHandler = handlers;

        // Add handlers for each static resource
        if (connectorProperties.getStaticResources() != null) {
            NavigableMap<String, List<HttpStaticResource>> staticResourcesMap = new TreeMap<String, List<HttpStaticResource>>();

            // Add each static resource to a map first to allow sorting and deduplication
            for (HttpStaticResource staticResource : connectorProperties.getStaticResources()) {
                String resourceContextPath = replacer.replaceValues(staticResource.getContextPath(), channelId,
                        channelName);
                Map<String, List<String>> queryParameters = new HashMap<String, List<String>>();

                // If query parameters were specified, extract them here
                int queryIndex = resourceContextPath.indexOf('?');
                if (queryIndex >= 0) {
                    String query = resourceContextPath.substring(queryIndex + 1);
                    resourceContextPath = resourceContextPath.substring(0, queryIndex);

                    for (NameValuePair param : URLEncodedUtils.parse(query, Charset.defaultCharset())) {
                        List<String> currentValue = queryParameters.get(param.getName());
                        String value = StringUtils.defaultString(param.getValue());

                        if (currentValue == null) {
                            currentValue = new ArrayList<String>();
                            queryParameters.put(param.getName(), currentValue);
                        }
                        currentValue.add(value);
                    }
                }

                // We always want to append resources starting with "/" to the base context path
                if (resourceContextPath.endsWith("/")) {
                    resourceContextPath = resourceContextPath.substring(0, resourceContextPath.length() - 1);
                }
                if (!resourceContextPath.startsWith("/")) {
                    resourceContextPath = "/" + resourceContextPath;
                }
                resourceContextPath = contextPath + resourceContextPath;

                List<HttpStaticResource> staticResourcesList = staticResourcesMap.get(resourceContextPath);
                if (staticResourcesList == null) {
                    staticResourcesList = new ArrayList<HttpStaticResource>();
                    staticResourcesMap.put(resourceContextPath, staticResourcesList);
                }
                staticResourcesList
                        .add(new HttpStaticResource(resourceContextPath, staticResource.getResourceType(),
                                staticResource.getValue(), staticResource.getContentType(), queryParameters));
            }

            // Iterate through each context path in reverse so that more specific contexts take precedence
            for (List<HttpStaticResource> staticResourcesList : staticResourcesMap.descendingMap().values()) {
                for (HttpStaticResource staticResource : staticResourcesList) {
                    logger.debug("Adding static resource handler for context path: "
                            + staticResource.getContextPath());
                    ContextHandler resourceContextHandler = new ContextHandler();
                    resourceContextHandler.setContextPath(staticResource.getContextPath());
                    // This allows resources to be requested without a relative context path (e.g. "/")
                    resourceContextHandler.setAllowNullPathInfo(true);
                    resourceContextHandler.setHandler(new StaticResourceHandler(staticResource));
                    handlers.addHandler(resourceContextHandler);
                }
            }
        }

        // Add the main request handler
        ContextHandler contextHandler = new ContextHandler();
        contextHandler.setContextPath(contextPath);
        contextHandler.setHandler(new RequestHandler());
        handlers.addHandler(contextHandler);

        // Wrap the handler collection in a security handler if needed
        if (authenticatorProvider != null) {
            serverHandler = createSecurityHandler(handlers);
        }
        server.setHandler(serverHandler);

        logger.debug("starting HTTP server with address: " + host + ":" + port);
        server.start();
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.IDLE));
    } catch (Exception e) {
        eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(),
                getSourceName(), ConnectionStatusEventType.FAILURE));
        throw new ConnectorTaskException("Failed to start HTTP Listener", e);
    }
}

From source file:org.openhmis.oauth2.OAuth2Utils.java

public Map handleURLEncodedResponse(HttpResponse response) {
    Map<String, Charset> map = Charset.availableCharsets();
    Map<String, String> oauthResponse = new HashMap<String, String>();
    Set<Map.Entry<String, Charset>> set = map.entrySet();
    Charset charset = null;/*from   w  ww .  j  a  v  a  2 s.  co  m*/
    HttpEntity entity = response.getEntity();

    System.out.println();
    System.out.println("********** Response Received **********");

    for (Map.Entry<String, Charset> entry : set) {
        System.out.println(String.format("  %s = %s", entry.getKey(), entry.getValue()));
        if (entry.getKey().equalsIgnoreCase(HTTP.UTF_8)) {
            charset = entry.getValue();
        }
    }

    try {
        List<NameValuePair> list = URLEncodedUtils.parse(EntityUtils.toString(entity),
                Charset.forName(HTTP.UTF_8));
        for (NameValuePair pair : list) {
            System.out.println(String.format("  %s = %s", pair.getName(), pair.getValue()));
            oauthResponse.put(pair.getName(), pair.getValue());
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException("Could not parse URLEncoded Response");
    }

    return oauthResponse;
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.AuthController.java

/**
 * Handles the redirection to the specified target after the login has been
 * performed. Given the user data collected during the login, updates the
 * user information in DB and populates the security context with the user
 * credentials./*from w  w w  .j  a va2  s  .co  m*/
 * 
 * @param authorityUrl
 *            the authority used by the user to sign in.
 * @param target
 *            target functionality address.
 * @param req
 * @return
 * @throws Exception
 */
@RequestMapping("/eauth/{authorityUrl}")
public ModelAndView forward(@PathVariable String authorityUrl, @RequestParam(required = false) String target,
        HttpServletRequest req, HttpServletResponse res) throws Exception {
    List<GrantedAuthority> list = Collections
            .<GrantedAuthority>singletonList(new SimpleGrantedAuthority("ROLE_USER"));

    String nTarget = (String) req.getSession().getAttribute("redirect");
    if (nTarget == null)
        return new ModelAndView("redirect:/logout");

    String clientId = (String) req.getSession().getAttribute("client_id");
    if (clientId != null) {
        Set<String> idps = clientDetailsAdapter.getIdentityProviders(clientId);
        if (!idps.contains(authorityUrl)) {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("message", "incorrect identity provider for the app");
            return new ModelAndView("oauth_error", model);
        }
    }

    // HOOK for testing
    if (testMode && target == null) {
        target = "/eauth/" + authorityUrl + "?target=" + URLEncoder.encode(nTarget, "UTF8")
                + "&OIDC_CLAIM_email=my@mail&OIDC_CLAIM_given_name=name&OIDC_CLAIM_family_name=surname";
    } else {

        if (!testMode && nTarget != null) {
            target = nTarget;
        }

        Authentication old = SecurityContextHolder.getContext().getAuthentication();
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            if (!authorityUrl.equals(old.getDetails())) {
                new SecurityContextLogoutHandler().logout(req, res, old);
                SecurityContextHolder.getContext().setAuthentication(null);

                req.getSession().setAttribute("redirect", target);
                req.getSession().setAttribute("client_id", clientId);

                return new ModelAndView("redirect:/eauth/" + authorityUrl);
                //               return new ModelAndView("redirect:/logout");
            }
        }

        List<NameValuePair> pairs = URLEncodedUtils.parse(URI.create(nTarget), "UTF-8");

        eu.trentorise.smartcampus.permissionprovider.model.User userEntity = null;
        if (old != null && old instanceof UsernamePasswordAuthenticationToken) {
            String userId = old.getName();
            userEntity = userRepository.findOne(Long.parseLong(userId));
        } else {
            userEntity = providerServiceAdapter.updateUser(authorityUrl, toMap(pairs), req);
        }

        UserDetails user = new User(userEntity.getId().toString(), "", list);

        AbstractAuthenticationToken a = new UsernamePasswordAuthenticationToken(user, null, list);
        a.setDetails(authorityUrl);

        SecurityContextHolder.getContext().setAuthentication(a);

    }
    return new ModelAndView("redirect:" + target);
}

From source file:org.keycloak.testsuite.admin.concurrency.ConcurrentLoginTest.java

private static Map<String, String> getQueryFromUrl(String url) throws URISyntaxException {
    return URLEncodedUtils.parse(new URI(url), Charset.forName("UTF-8")).stream()
            .collect(Collectors.toMap(p -> p.getName(), p -> p.getValue()));
}

From source file:com.smartling.api.sdk.FileApiClientAdapterTest.java

@Test
public void testLastModified() throws ApiException, IOException {
    Date lastModifiedAfter = new Date();

    when(response.getContents())/*from  w  w w .  j a va  2  s.  c  o m*/
            .thenReturn(String.format(LAST_MODIFIED_RESPONSE, LOCALE, DateFormatter.format(lastModifiedAfter)));

    ApiResponse<FileLastModified> apiResponse = fileApiClientAdapter.getLastModified(FILE_URI,
            lastModifiedAfter, LOCALE);

    // Validate the request
    HttpRequestBase request = requestCaptor.getValue();
    List<NameValuePair> params = URLEncodedUtils.parse(request.getURI(), "UTF-8");
    assertLatModifiedRequestParams(lastModifiedAfter, params);
    assertEquals(HOST, request.getURI().getHost());

    // Validate the response
    assertEquals("SUCCESS", apiResponse.getCode());
    assertNotNull(apiResponse.getData());

    FileLastModified fileLastModified = apiResponse.getData();
    assertEquals(1, fileLastModified.getItems().size());

    FileLocaleLastModified fileLocaleLastModified = fileLastModified.getItems().get(0);
    assertEquals(lastModifiedAfter.getTime() / 1000, fileLocaleLastModified.getLastModified().getTime() / 1000);
    assertEquals(LOCALE, fileLocaleLastModified.getLocale());
}

From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java

private void signRequest(HttpUriRequest request, String postParams, String token, String tokenSecret,
        String consumerKey, String consumerSecret) {
    // TODO: this is a little odd: we already encoded the values earlier, but using URLEncodedUtils.parse will decode the values,
    // which we will encode again.
    List<NameValuePair> httpGetParams = null;

    if (request.getURI().getRawQuery() == null) {
        httpGetParams = new ArrayList<NameValuePair>();
    } else {/* ww  w .  j  a va  2s.  co m*/
        httpGetParams = URLEncodedUtils.parse(request.getURI().getRawQuery(), Charsets.UTF_8);
    }

    List<Pair> javaParams = new ArrayList<Pair>(httpGetParams.size());
    for (NameValuePair params : httpGetParams) {
        Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
        javaParams.add(tuple);
    }

    if (postParams != null) {
        List<NameValuePair> httpPostParams = URLEncodedUtils.parse(postParams, Charsets.UTF_8);

        for (NameValuePair params : httpPostParams) {
            Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue()));
            javaParams.add(tuple);
        }
    }

    long timestampSecs = generateTimestamp();
    String nonce = generateNonce();

    OAuthParams.OAuth1Params oAuth1Params = new OAuthParams.OAuth1Params(token, consumerKey, nonce,
            timestampSecs, Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1, OAuthParams.ONE_DOT_OH);

    int port = request.getURI().getPort();
    if (port <= 0) {
        // getURI can return a -1 for a port
        if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTP_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTP_PORT;
        } else if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTPS_SCHEME)) {
            port = HttpConstants.DEFAULT_HTTPS_PORT;
        } else {
            throw new IllegalStateException("Bad URI scheme: " + request.getURI().getScheme());
        }
    }

    String normalized = Normalizer.getStandardNormalizer().normalize(request.getURI().getScheme(),
            request.getURI().getHost(), port, request.getMethod().toUpperCase(), request.getURI().getPath(),
            javaParams, oAuth1Params);

    String signature;
    try {
        signature = Signer.getStandardSigner().getString(normalized, tokenSecret, consumerSecret);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> oauthHeaders = new HashMap<String, String>();
    oauthHeaders.put(OAuthParams.OAUTH_CONSUMER_KEY, quoted(consumerKey));
    oauthHeaders.put(OAuthParams.OAUTH_TOKEN, quoted(token));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE, quoted(signature));
    oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE_METHOD, quoted(OAuthParams.HMAC_SHA1));
    oauthHeaders.put(OAuthParams.OAUTH_TIMESTAMP, quoted(Long.toString(timestampSecs)));
    oauthHeaders.put(OAuthParams.OAUTH_NONCE, quoted(nonce));
    oauthHeaders.put(OAuthParams.OAUTH_VERSION, quoted(OAuthParams.ONE_DOT_OH));
    String header = Joiner.on(", ").withKeyValueSeparator("=").join(oauthHeaders);

    request.setHeader(HttpHeaders.AUTHORIZATION, "OAuth " + header);

}

From source file:io.apicurio.hub.editing.EditApiDesignEndpoint.java

/**
 * Parses the query string into a map./*from  www  . ja v  a 2s. co m*/
 * @param queryString
 */
protected static Map<String, String> parseQueryString(String queryString) {
    Map<String, String> rval = new HashMap<>();
    List<NameValuePair> list = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
    for (NameValuePair nameValuePair : list) {
        rval.put(nameValuePair.getName(), nameValuePair.getValue());
    }
    return rval;
}

From source file:com.snowplowanalytics.snowplow.hadoop.hive.SnowPlowEventStruct.java

/**
 * Parses the input row String into a Java object.
 * For performance reasons this works in-place updating the fields
 * within this SnowPlowEventStruct, rather than creating a new one.
 *
 * @param row The raw String containing the row contents
 * @return true if row was successfully parsed, false otherwise
 * @throws SerDeException For any exception during parsing
 *///from  w  ww.j  av  a2 s. c  om
public boolean updateByParsing(String row) throws SerDeException {

    // First we reset the object's fields
    nullify();

    // We have to handle any header rows
    if (row.startsWith("#Version:") || row.startsWith("#Fields:")) {
        return false; // Empty row will be discarded by Hive
    }

    final Matcher m = cfRegex.matcher(row);

    // 0. First check our row is kosher

    // -> is row from a CloudFront log? Will throw an exception if not
    if (!m.matches())
        throw new SerDeException("Row does not match expected CloudFront regexp pattern");

    // -> was generated by sp.js? If not (e.g. favicon.ico request), then silently return
    final String object = m.group(8);
    final String querystring = m.group(12);
    if (!(object.startsWith("/ice.png") || object.equals("/i") || object.startsWith("/i?"))
            || isNullField(querystring)) { // Also works if Forward Query String = yes
        return false;
    }

    // 1. Now we retrieve the fields which get directly passed through
    this.dt = m.group(1);
    this.collector_dt = this.dt;
    this.collector_tm = m.group(2); // CloudFront date format matches Hive's
    this.user_ipaddress = m.group(5);

    // 2. Now grab the user agent
    final String ua = m.group(11);
    try {
        this.useragent = decodeSafeString(ua);
    } catch (Exception e) {
        getLog().warn(e.getClass().getSimpleName() + " on { useragent: " + ua + " }");
    }

    // 3. Next we dis-assemble the user agent...
    final UserAgent userAgent = UserAgent.parseUserAgentString(ua);

    // -> browser fields
    final Browser b = userAgent.getBrowser();
    this.br_name = b.getName();
    this.br_family = b.getGroup().getName();
    final Version v = userAgent.getBrowserVersion();
    this.br_version = (v == null) ? null : v.getVersion();
    this.br_type = b.getBrowserType().getName();
    this.br_renderengine = b.getRenderingEngine().toString();

    // -> OS-related fields
    final OperatingSystem os = userAgent.getOperatingSystem();
    this.os_name = os.getName();
    this.os_family = os.getGroup().getName();
    this.os_manufacturer = os.getManufacturer().getName();

    // -> device/hardware-related fields
    this.dvce_type = os.getDeviceType().getName();
    this.dvce_ismobile = os.isMobileDevice();
    this.dvce_ismobile_bt = (byte) (this.dvce_ismobile ? 1 : 0);

    // 4. Now for the versioning (tracker versioning is handled below)
    this.v_collector = collectorVersion;
    this.v_etl = "serde-" + ProjectSettings.VERSION;

    // 5. Now we generate the event vendor and ID
    this.event_vendor = eventVendor; // TODO: this becomes part of the protocol eventually
    this.event_id = generateEventId();

    // 6. Now we dis-assemble the querystring.
    String qsUrl = null; // We use this in the block below, and afterwards
    List<NameValuePair> params = null; // We re-use this for efficiency
    try {
        params = URLEncodedUtils.parse(URI.create("http://localhost/?" + querystring), cfEncoding);

        // For performance, don't convert to a map, just loop through and match to our variables as we go
        for (NameValuePair pair : params) {

            final String name = pair.getName();
            final String value = pair.getValue();

            final QuerystringFields field;
            try {
                field = QuerystringFields.valueOf(name.toUpperCase()); // Java pre-7 can't switch on a string, so hash the string
            } catch (IllegalArgumentException e) {
                getLog().warn("Unexpected params { " + name + ": " + value + " }");
                continue;
            }

            try {
                switch (field) {
                // Common fields
                case E:
                    this.event = asEventType(value);
                    break;
                case IP:
                    this.user_ipaddress = value;
                    break;
                case AID:
                    this.app_id = value;
                    break;
                case P:
                    this.platform = value;
                    break;
                case TID:
                    this.txn_id = value;
                    break;
                case UID:
                    this.user_id = value;
                    break;
                case DUID:
                    this.domain_userid = value;
                    break;
                case NUID:
                    this.network_userid = value;
                    break;
                case FP:
                    this.user_fingerprint = value;
                    break;
                case VID:
                    this.domain_sessionidx = Integer.parseInt(value);
                    break;
                case DTM:
                    // Set our dvce_dt, _tm and _epoch fields
                    this.dvce_epoch = Long.parseLong(value);
                    Date deviceDate = new Date(this.dvce_epoch);
                    this.dvce_dt = dateFormat.format(deviceDate);
                    this.dvce_tm = timeFormat.format(deviceDate);
                    break;
                case TV:
                    this.v_tracker = value;
                    break;
                case LANG:
                    this.br_lang = value;
                    break;
                case CS:
                    this.doc_charset = value;
                    break;
                case VP:
                    String[] viewport = value.split("x");
                    if (viewport.length != 2)
                        throw new Exception("Couldn't parse vp field");
                    this.br_viewwidth = Integer.parseInt(viewport[0]);
                    this.br_viewheight = Integer.parseInt(viewport[1]);
                    break;
                case DS:
                    String[] docsize = value.split("x");
                    if (docsize.length != 2)
                        throw new Exception("Couldn't parse ds field");
                    this.doc_width = Integer.parseInt(docsize[0]);
                    this.doc_height = Integer.parseInt(docsize[1]);
                    break;
                case F_PDF:
                    if ((this.br_features_pdf = stringToByte(value)) == 1)
                        this.br_features.add("pdf");
                    break;
                case F_FLA:
                    if ((this.br_features_flash = stringToByte(value)) == 1)
                        this.br_features.add("fla");
                    break;
                case F_JAVA:
                    if ((this.br_features_java = stringToByte(value)) == 1)
                        this.br_features.add("java");
                    break;
                case F_DIR:
                    if ((this.br_features_director = stringToByte(value)) == 1)
                        this.br_features.add("dir");
                    break;
                case F_QT:
                    if ((this.br_features_quicktime = stringToByte(value)) == 1)
                        this.br_features.add("qt");
                    break;
                case F_REALP:
                    if ((this.br_features_realplayer = stringToByte(value)) == 1)
                        this.br_features.add("realp");
                    break;
                case F_WMA:
                    if ((this.br_features_windowsmedia = stringToByte(value)) == 1)
                        this.br_features.add("wma");
                    break;
                case F_GEARS:
                    if ((this.br_features_gears = stringToByte(value)) == 1)
                        this.br_features.add("gears");
                    break;
                case F_AG:
                    if ((this.br_features_silverlight = stringToByte(value)) == 1)
                        this.br_features.add("ag");
                    break;
                case COOKIE:
                    this.br_cookies = stringToBoolean(value);
                    this.br_cookies_bt = (byte) (this.br_cookies ? 1 : 0);
                    break;
                case RES:
                    String[] resolution = value.split("x");
                    if (resolution.length != 2)
                        throw new Exception("Couldn't parse res field");
                    this.dvce_screenwidth = Integer.parseInt(resolution[0]);
                    this.dvce_screenheight = Integer.parseInt(resolution[1]);
                    break;
                case CD:
                    this.br_colordepth = value;
                    break;
                case TZ:
                    this.os_timezone = decodeSafeString(value);
                    break;
                case REFR:
                    this.page_referrer = decodeSafeString(value);
                    break;
                case URL:
                    qsUrl = pair.getValue(); // We might use this later for the page URL
                    break;

                // Page-view only
                case PAGE:
                    this.page_title = decodeSafeString(value);
                    break;

                // Event only
                case EV_CA:
                    this.ev_category = decodeSafeString(value);
                    break;
                case EV_AC:
                    this.ev_action = decodeSafeString(value);
                    break;
                case EV_LA:
                    this.ev_label = decodeSafeString(value);
                    break;
                case EV_PR:
                    this.ev_property = decodeSafeString(value);
                    break;
                case EV_VA:
                    this.ev_value = decodeSafeString(value);
                    break;

                // Ecommerce
                case TR_ID:
                    this.tr_orderid = decodeSafeString(value);
                    break;
                case TR_AF:
                    this.tr_affiliation = decodeSafeString(value);
                    break;
                case TR_TT:
                    this.tr_total = decodeSafeString(value);
                    break;
                case TR_TX:
                    this.tr_tax = decodeSafeString(value);
                    break;
                case TR_SH:
                    this.tr_shipping = decodeSafeString(value);
                    break;
                case TR_CI:
                    this.tr_city = decodeSafeString(value);
                    break;
                case TR_ST:
                    this.tr_state = decodeSafeString(value);
                    break;
                case TR_CO:
                    this.tr_country = decodeSafeString(value);
                    break;
                case TI_ID:
                    this.ti_orderid = decodeSafeString(value);
                    break;
                case TI_SK:
                    this.ti_sku = decodeSafeString(value);
                    break;
                case TI_NA:
                    this.ti_name = decodeSafeString(value);
                    break;
                case TI_CA:
                    this.ti_category = decodeSafeString(value);
                    break;
                case TI_PR:
                    this.ti_price = decodeSafeString(value);
                    break;
                case TI_QU:
                    this.ti_quantity = decodeSafeString(value);
                    break;

                // Page pings
                case PP_MIX:
                    this.pp_xoffset_min = Integer.parseInt(value);
                    break;
                case PP_MAX:
                    this.pp_xoffset_max = Integer.parseInt(value);
                    break;
                case PP_MIY:
                    this.pp_yoffset_min = Integer.parseInt(value);
                    break;
                case PP_MAY:
                    this.pp_yoffset_max = Integer.parseInt(value);
                    break;
                }
            } catch (Exception e) {
                getLog().warn(e.getClass().getSimpleName() + " on { " + name + ": " + value + " }");
            }
        }
    } catch (IllegalArgumentException e) {
        getLog().warn("Corrupted querystring { " + querystring + " }");
    }

    // 7. Choose the page_url
    final String cfUrl = m.group(10);
    if (!isNullField(cfUrl)) { // CloudFront didn't provide the URL as cs(Referer)
        this.page_url = cfUrl; // The CloudFront cs(Referer) URL
    } else {
        try {
            this.page_url = decodeSafeString(qsUrl); // Use the decoded querystring URL. Might be null (returned as null)
        } catch (Exception e) {
            getLog().warn(e.getClass().getSimpleName() + " on { qsUrl: " + qsUrl + " }");
        }
    }

    // 8. Now try to convert the page_url into a valid Java URI and store the 6 out of 9 components we are interested in:
    try {
        final URI pageUri = URI.create(this.page_url);
        this.page_urlscheme = pageUri.getScheme();
        this.page_urlhost = pageUri.getHost();
        final Integer port = pageUri.getPort();
        this.page_urlport = (port == -1) ? 80 : port;
        this.page_urlpath = pageUri.getPath();
        this.page_urlquery = pageUri.getQuery();
        this.page_urlfragment = pageUri.getFragment();
    } catch (Exception e) {
        getLog().warn("Could not parse page_url " + this.page_url + " }");
    }

    // 9. Finally handle the marketing fields in the page_url
    // Re-use params to avoid creating another object
    if (this.page_url != null) {
        params = null;
        try {
            params = URLEncodedUtils.parse(URI.create(this.page_url), "UTF-8");
        } catch (IllegalArgumentException e) {
            getLog().warn("Couldn't parse page_url: " + page_url);
        }
        if (params != null) {
            // For performance, don't convert to a map, just loop through and match to our variables as we go
            for (NameValuePair pair : params) {

                final String name = pair.getName();
                final String value = pair.getValue();

                final MarketingFields field;
                try {
                    field = MarketingFields.valueOf(name.toUpperCase()); // Java pre-7 can't switch on a string, so hash the string
                } catch (IllegalArgumentException e) {
                    // Do nothing: non-marketing related querystring fields are not an issue.
                    continue;
                }

                try {
                    switch (field) {
                    // Marketing fields
                    case UTM_MEDIUM:
                        this.mkt_medium = decodeSafeString(value);
                        break;
                    case UTM_SOURCE:
                        this.mkt_source = decodeSafeString(value);
                        break;
                    case UTM_TERM:
                        this.mkt_term = decodeSafeString(value);
                        break;
                    case UTM_CONTENT:
                        this.mkt_content = decodeSafeString(value);
                        break;
                    case UTM_CAMPAIGN:
                        this.mkt_campaign = decodeSafeString(value);
                        break;
                    }
                } catch (Exception e) {
                    getLog().warn(e.getClass().getSimpleName() + " on { " + name + ": " + value + " }");
                }
            }
        }
    }

    return true; // Successfully updated the row.
}