Example usage for org.apache.http.util TextUtils isEmpty

List of usage examples for org.apache.http.util TextUtils isEmpty

Introduction

In this page you can find the example usage for org.apache.http.util TextUtils isEmpty.

Prototype

public static boolean isEmpty(CharSequence charSequence) 

Source Link

Usage

From source file:i5.las2peer.services.servicePackage.ExpertRecommenderService.java

/**
 * This method parses data from remote url or from the local file on the
 * server./*from  w w  w  .j  ava 2  s.co  m*/
 * 
 * @param id
 *            Id of the dataset corresponding to the database to update.
 *            This is obtained while preparing the database.
 * @param type
 *            Input format of the dataset (xml, csv, json)
 * @param urlObject
 *            A remote urls wrapped in json object to parse the data from.
 * 
 * @return A string representing if the update was success or failure.
 */
@POST
@Path("datasets/{datasetId}/parse")
@ApiResponses(value = { @ApiResponse(code = 200, message = "Success"),
        @ApiResponse(code = 400, message = "Invalid Input"),
        @ApiResponse(code = 500, message = "Connection or Query Failure") })
@ApiOperation(value = "Parse the Data.", notes = "Parses the data files and add it to database.")
public HttpResponse parse(@PathParam("datasetId") String id, @ContentParam String urlObject,
        @DefaultValue("xml") @QueryParam("format") String type) {

    // log.info("URL::" + urlObject);
    HttpResponse res = null;

    String datasetName = getDatasetName(id);
    if (datasetName == null) {
        try {
            throw new ERSException(ERSMessage.DATASET_NOT_CONFIGURED);
        } catch (ERSException e) {
            e.printStackTrace();
            res = new HttpResponse(e.getMessage());
            res.setStatus(400);
            return res;
        }
    }

    boolean isLocal = false;
    String postsPath = null;
    String usersPath = null;
    if (!TextUtils.isEmpty(urlObject)) {
        String[] urls = urlObject.split(",");
        postsPath = urls[0];
        usersPath = urls[1];
        if (!postsPath.startsWith("http") && !postsPath.startsWith("ftp")) {
            isLocal = true;
        }
    } else {
        isLocal = true;
        postsPath = "datasets/" + datasetName + "/posts.xml";
        usersPath = "datasets/" + datasetName + "/users.xml";
    }

    log.info(postsPath);
    log.info(usersPath);

    DatabaseHandler dbHandler = new DatabaseHandler();

    try {
        if (type.equalsIgnoreCase("xml")) {
            log.info("Executing XML Parser...");
            XMLParser xmlparser = new XMLParser();
            xmlparser.parseData(postsPath, isLocal);
            dbHandler.addPosts(datasetName, xmlparser.getPosts());

            xmlparser.parseUserData(usersPath, isLocal);
            dbHandler.addUsers(datasetName, xmlparser.getUsers());
        } else if (type.equalsIgnoreCase("csv")) {

            log.info("Executing CSV Parser...");
            // User details are extracted from posts data file itself.
            // (data.csv)

            postsPath = "datasets/" + datasetName + "/data.csv";
            ERSCSVParser csvparser = new ERSCSVParser(postsPath);
            dbHandler.addPosts(datasetName, csvparser.getPosts());
            List<UserCSV> users = csvparser.getUsers();

            if (users != null && users.size() > 0) {
                dbHandler.addUsers(datasetName, users);
            }
        } else if (type.equalsIgnoreCase("json")) {
            log.info("Executing Json Parser...");

            ERSJsonParser jsonparser = new ERSJsonParser(postsPath);
            dbHandler.addPosts(datasetName, jsonparser.getPosts());
            List<User> users = jsonparser.getUsers();
            if (users != null && users.size() > 0) {
                dbHandler.addUsers(datasetName, users);
            }
        } else {
            throw new ERSException(ERSMessage.UNSUPPORTED_TYPE);
        }
    } catch (SQLException e) {
        e.printStackTrace();
        res = new HttpResponse(ERSMessage.SQL_FAILURE);
        res.setStatus(500);
        return res;
    } catch (ERSException e) {
        e.printStackTrace();
        res = new HttpResponse(ERSMessage.UNSUPPORTED_TYPE);
        res.setStatus(400);
        return res;
    }

    res = new HttpResponse(ERSMessage.SUCCESS);
    res.setStatus(200);
    return res;
}

From source file:com.wareninja.opensource.dizlink.utils.MyWebClient.java

public String enrichMethodName(String methodName, String apptoken, String api_username) {

    Map<String, String> parameters = new HashMap<String, String>();
    if (!TextUtils.isEmpty(apptoken))
        parameters.put("apptoken", apptoken);
    if (!TextUtils.isEmpty(api_username))
        parameters.put("api_username", api_username);

    return enrichMethodName(methodName, parameters);
}

From source file:com.wareninja.opensource.discourse.utils.MyWebClient.java

public String enrichMethodName(String methodName, String api_key, String api_username) {

    Map<String, String> parameters = new HashMap<String, String>();
    if (!TextUtils.isEmpty(api_key))
        parameters.put("api_key", api_key);
    if (!TextUtils.isEmpty(api_username))
        parameters.put("api_username", api_username);

    return enrichMethodName(methodName, parameters);
}

From source file:org.asamk.signal.Manager.java

public void addDeviceLink(URI linkUri) throws IOException, InvalidKeyException {
    Map<String, String> query = getQueryMap(linkUri.getRawQuery());
    String deviceIdentifier = query.get("uuid");
    String publicKeyEncoded = query.get("pub_key");

    if (TextUtils.isEmpty(deviceIdentifier) || TextUtils.isEmpty(publicKeyEncoded)) {
        throw new RuntimeException("Invalid device link uri");
    }//  w  w w.j  a v a2s.c o m

    ECPublicKey deviceKey = Curve.decodePoint(Base64.decode(publicKeyEncoded), 0);

    addDevice(deviceIdentifier, deviceKey);
}

From source file:org.apache.http.client.protocol.RequestAddCookies.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    Args.notNull(request, "HTTP request");
    Args.notNull(context, "HTTP context");

    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase("CONNECT")) {
        return;/*from w w  w.j  a  v  a 2s.  com*/
    }

    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    // Obtain cookie store
    final CookieStore cookieStore = clientContext.getCookieStore();
    if (cookieStore == null) {
        this.log.debug("Cookie store not specified in HTTP context");
        return;
    }

    // Obtain the registry of cookie specs
    final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry();
    if (registry == null) {
        this.log.debug("CookieSpec registry not specified in HTTP context");
        return;
    }

    // Obtain the target host, possibly virtual (required)
    final HttpHost targetHost = clientContext.getTargetHost();
    if (targetHost == null) {
        this.log.debug("Target host not set in the context");
        return;
    }

    // Obtain the route (required)
    final RouteInfo route = clientContext.getHttpRoute();
    if (route == null) {
        this.log.debug("Connection route not set in the context");
        return;
    }

    final RequestConfig config = clientContext.getRequestConfig();
    String policy = config.getCookieSpec();
    if (policy == null) {
        policy = CookieSpecs.BEST_MATCH;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("CookieSpec selected: " + policy);
    }

    URI requestURI = null;
    if (request instanceof HttpUriRequest) {
        requestURI = ((HttpUriRequest) request).getURI();
    } else {
        try {
            requestURI = new URI(request.getRequestLine().getUri());
        } catch (final URISyntaxException ignore) {
        }
    }
    final String path = requestURI != null ? requestURI.getPath() : null;
    final String hostName = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port < 0) {
        port = route.getTargetHost().getPort();
    }

    final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port >= 0 ? port : 0,
            !TextUtils.isEmpty(path) ? path : "/", route.isSecure());

    // Get an instance of the selected cookie policy
    final CookieSpecProvider provider = registry.lookup(policy);
    if (provider == null) {
        throw new HttpException("Unsupported cookie policy: " + policy);
    }
    final CookieSpec cookieSpec = provider.create(clientContext);
    // Get all cookies available in the HTTP state
    final List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies());
    // Find cookies matching the given origin
    final List<Cookie> matchedCookies = new ArrayList<Cookie>();
    final Date now = new Date();
    for (final Cookie cookie : cookies) {
        if (!cookie.isExpired(now)) {
            if (cookieSpec.match(cookie, cookieOrigin)) {
                if (this.log.isDebugEnabled()) {
                    this.log.debug("Cookie " + cookie + " match " + cookieOrigin);
                }
                matchedCookies.add(cookie);
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Cookie " + cookie + " expired");
            }
        }
    }
    // Generate Cookie request headers
    if (!matchedCookies.isEmpty()) {
        final List<Header> headers = cookieSpec.formatCookies(matchedCookies);
        for (final Header header : headers) {
            request.addHeader(header);
        }
    }

    final int ver = cookieSpec.getVersion();
    if (ver > 0) {
        boolean needVersionHeader = false;
        for (final Cookie cookie : matchedCookies) {
            if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) {
                needVersionHeader = true;
            }
        }

        if (needVersionHeader) {
            final Header header = cookieSpec.getVersionHeader();
            if (header != null) {
                // Advertise cookie version support
                request.addHeader(header);
            }
        }
    }

    // Stick the CookieSpec and CookieOrigin instances to the HTTP context
    // so they could be obtained by the response interceptor
    context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec);
    context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin);
}

From source file:org.apache.http.impl.client.DefaultRedirectStrategy.java

/**
 * @since 4.1/*  w  w  w.ja  v  a 2  s  .  com*/
 */
protected URI createLocationURI(final String location) throws ProtocolException {
    try {
        final URIBuilder b = new URIBuilder(new URI(location).normalize());
        final String host = b.getHost();
        if (host != null) {
            b.setHost(host.toLowerCase(Locale.US));
        }
        final String path = b.getPath();
        if (TextUtils.isEmpty(path)) {
            b.setPath("/");
        }
        return b.build();
    } catch (final URISyntaxException ex) {
        throw new ProtocolException("Invalid redirect URI: " + location, ex);
    }
}