Java Code Examples for org.eclipse.jetty.util.StringUtil

The following examples show how to use org.eclipse.jetty.util.StringUtil. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: hadoop-ozone   Source File: DBConfigFromFile.java    License: Apache License 2.0 6 votes vote down vote up
public static File getConfigLocation() throws IOException {
  String path = System.getenv(CONFIG_DIR);

  // Make testing easy.
  // If there is No Env. defined, let us try to read the JVM property
  if (StringUtil.isBlank(path)) {
    path = System.getProperty(CONFIG_DIR);
  }

  if (StringUtil.isBlank(path)) {
    LOG.debug("Unable to find the configuration directory. "
        + "Please make sure that HADOOP_CONF_DIR is setup correctly.");
  }
  if(StringUtil.isBlank(path)){
    return null;
  }
  return new File(path);

}
 
Example 2
Source Project: hadoop-ozone   Source File: DBStoreBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Builds a DBStore instance and returns that.
 *
 * @return DBStore
 */
public DBStore build() throws IOException {
  if(StringUtil.isBlank(dbname) || (dbPath == null)) {
    LOG.error("Required Parameter missing.");
    throw new IOException("Required parameter is missing. Please make sure "
        + "sure Path and DB name is provided.");
  }
  processDBProfile();
  processTables();
  DBOptions options = getDbProfile();

  WriteOptions writeOptions = new WriteOptions();
  writeOptions.setSync(rocksDBConfiguration.getSyncOption());


  File dbFile = getDBFile();
  if (!dbFile.getParentFile().exists()) {
    throw new IOException("The DB destination directory should exist.");
  }
  return new RDBStore(dbFile, options, writeOptions, tables, registry);
}
 
Example 3
Source Project: clickhouse-jdbc-bridge   Source File: ColumnsInfoServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try (Connection connection = manager.get(req.getParameter("connection_string")); Statement sth = connection.createStatement()) {
        String schema = req.getParameter("schema");
        String table = req.getParameter("table");

        String quote = connection.getMetaData().getIdentifierQuoteString();
        String schemaAndTable = Stream.of(schema, table)
                .filter(s -> !StringUtil.isBlank(s))
                .map(s -> quote + s + quote)
                .collect(Collectors.joining("."));

        String queryRewrite = "SELECT * FROM " + schemaAndTable + " WHERE 1 = 0";
        log.info("Inferring schema by query {}", queryRewrite);

        ResultSet resultset = sth.executeQuery(queryRewrite);
        String ddl = converter.getColumnsDDL(resultset.getMetaData());
        resp.setContentType("application/octet-stream");
        ClickHouseRowBinaryStream stream = new ClickHouseRowBinaryStream(resp.getOutputStream(), null, new ClickHouseProperties());
        stream.writeString(ddl);
    } catch (Exception err) {
        log.error(err.getMessage(), err);
        resp.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, err.getMessage());
    }
}
 
Example 4
Source Project: onedev   Source File: Response.java    License: MIT License 6 votes vote down vote up
@Override
public void addCookie(Cookie cookie)
{
    if (StringUtil.isBlank(cookie.getName()))
        throw new IllegalArgumentException("Cookie.name cannot be blank/null");

    String comment = cookie.getComment();
    // HttpOnly was supported as a comment in cookie flags before the java.net.HttpCookie implementation so need to check that
    boolean httpOnly = cookie.isHttpOnly() || HttpCookie.isHttpOnlyInComment(comment);
    SameSite sameSite = HttpCookie.getSameSiteFromComment(comment);
    comment = HttpCookie.getCommentWithoutAttributes(comment);

    addCookie(new HttpCookie(
        cookie.getName(),
        cookie.getValue(),
        cookie.getDomain(),
        cookie.getPath(),
        (long)cookie.getMaxAge(),
        httpOnly,
        cookie.getSecure(),
        comment,
        cookie.getVersion(),
        sameSite));
}
 
Example 5
Source Project: onedev   Source File: Response.java    License: MIT License 6 votes vote down vote up
@Override
public void setLocale(Locale locale)
{
    if (locale == null || isCommitted() || !isMutable())
        return;

    _locale = locale;
    _fields.put(HttpHeader.CONTENT_LANGUAGE, StringUtil.replace(locale.toString(), '_', '-'));

    if (_outputType != OutputType.NONE)
        return;

    if (_channel.getRequest().getContext() == null)
        return;

    String charset = _channel.getRequest().getContext().getContextHandler().getLocaleEncoding(locale);

    if (charset != null && charset.length() > 0 && __localeOverride.contains(_encodingFrom))
        setCharacterEncoding(charset, EncodingFrom.SET_LOCALE);
}
 
Example 6
Source Project: java-trader   Source File: SimTxnSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 加载数据
 */
private boolean loadData() {
    String jsonText = kvStore.getAsString("simTxn");
    if ( StringUtil.isEmpty(jsonText)) {
        return false;
    }
    JsonObject json = (new JsonParser()).parse(jsonText).getAsJsonObject();

    long balance = PriceUtil.str2long(json.get("balance").getAsString());
    setMoney(AccMoney.Balance, balance);
    setMoney(AccMoney.BalanceBefore, balance);
    JsonArray jsonPos = json.get("positions").getAsJsonArray();
    long margin = 0, posprofit=0;
    for(int i=0;i<jsonPos.size();i++) {
        SimPosition pos = SimPosition.loadFromJson(this, jsonPos.get(i).getAsJsonObject());
        positions.put(pos.getInstrument(), pos);
        margin += pos.getMoney(PosMoney.UseMargin);
        posprofit += pos.getMoney(PosMoney.PositionProfit);
    }
    setMoney(AccMoney.CurrMargin, margin);
    setMoney(AccMoney.PositionProfit, posprofit);
    setMoney(AccMoney.Available, balance-margin);

    return true;
}
 
Example 7
Source Project: vespa   Source File: ErrorResponseContentCreator.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] createErrorContent(String requestUri, int statusCode, Optional<String> message) {
    String sanitizedString = message.map(StringUtil::sanitizeXmlString).orElse("");
    String statusCodeString = Integer.toString(statusCode);
    writer.resetWriter();
    try {
        writer.write("<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n<title>Error ");
        writer.write(statusCodeString);
        writer.write("</title>\n</head>\n<body>\n<h2>HTTP ERROR: ");
        writer.write(statusCodeString);
        writer.write("</h2>\n<p>Problem accessing ");
        writer.write(StringUtil.sanitizeXmlString(requestUri));
        writer.write(". Reason:\n<pre>    ");
        writer.write(sanitizedString);
        writer.write("</pre></p>\n<hr/>\n</body>\n</html>\n");
    } catch (IOException e) {
        // IOException should not be thrown unless writer is constructed using byte[] parameter
        throw new RuntimeException(e);
    }
    return writer.getByteArray();
}
 
Example 8
Source Project: commafeed   Source File: SecurityCheckFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<User> basicAuthenticationLogin() {
	String header = request.getHeader(HttpHeaders.AUTHORIZATION);
	if (header != null) {
		int space = header.indexOf(' ');
		if (space > 0) {
			String method = header.substring(0, space);
			if (PREFIX.equalsIgnoreCase(method)) {
				String decoded = B64Code.decode(header.substring(space + 1), StringUtil.__ISO_8859_1);
				int i = decoded.indexOf(':');
				if (i > 0) {
					String username = decoded.substring(0, i);
					String password = decoded.substring(i + 1);
					return userService.login(username, password);
				}
			}
		}
	}
	return Optional.empty();
}
 
Example 9
Source Project: hadoop-ozone   Source File: DBStoreBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private File getDBFile() throws IOException {
  if (dbPath == null) {
    LOG.error("DB path is required.");
    throw new IOException("A Path to for DB file is needed.");
  }

  if (StringUtil.isBlank(dbname)) {
    LOG.error("DBName is a required.");
    throw new IOException("A valid DB name is required.");
  }
  return Paths.get(dbPath.toString(), dbname).toFile();
}
 
Example 10
Source Project: hadoop-ozone   Source File: OmMetadataManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getOzoneKey(String volume, String bucket, String key) {
  StringBuilder builder = new StringBuilder()
      .append(OM_KEY_PREFIX).append(volume);
  // TODO : Throw if the Bucket is null?
  builder.append(OM_KEY_PREFIX).append(bucket);
  if (StringUtil.isNotBlank(key)) {
    builder.append(OM_KEY_PREFIX);
    if (!key.equals(OM_KEY_PREFIX)) {
      builder.append(key);
    }
  }
  return builder.toString();
}
 
Example 11
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {
        String query = req.getParameter("query");
        if (StringUtil.isBlank(query)) {
            // a hack for wrong input from CH
            String requestBody = StreamUtils.toString(req.getInputStream());
            String[] parts = requestBody.split("query=", 2);
            if (parts.length == 2) {
                query = parts[1];
            }
        }

        if (StringUtil.isBlank(query)) {
            throw new IllegalArgumentException("Query is blank or empty");
        }

        try (Connection connection = manager.get(req.getParameter("connection_string")); Statement sth = connection.createStatement()) {
            ResultSet resultset = sth.executeQuery(query);
            ResultSetMetaData meta = resultset.getMetaData();

            ClickHouseRowSerializer serializer = ClickHouseRowSerializer.create(meta);
            ClickHouseRowBinaryStream stream = new ClickHouseRowBinaryStream(resp.getOutputStream(), null, new ClickHouseProperties());

            resp.setContentType("application/octet-stream");
            while (resultset.next()) {
                serializer.serialize(resultset, stream);
            }
        }
    } catch (Exception err) {
        log.error(err.getMessage(), err);
        resp.sendError(HttpStatus.INTERNAL_SERVER_ERROR_500, err.getMessage());
    }
}
 
Example 12
Source Project: clickhouse-jdbc-bridge   Source File: JdbcBridge.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If a path to log file given, then redirect logs there
 */
private void configureLogging() throws Exception {
    final boolean isLogFileBlank = StringUtil.isBlank(config.getLogPath());

    if (config.isDaemon() && isLogFileBlank) {
        throw new IllegalArgumentException("You can not run as daemon, and without specifying log path");
    }

    if (!isLogFileBlank) {
        Map<String, String> pocoToJavaLogMap = new HashMap<>();
        pocoToJavaLogMap.put("critical", "error");
        pocoToJavaLogMap.put("warning", "warn");
        pocoToJavaLogMap.put("notice", "warn");
        pocoToJavaLogMap.put("information", "info");
        String givenLogLevel = pocoToJavaLogMap.getOrDefault(config.getLogLevel(), "trace").toUpperCase();

        URL url = Resources.getResource("log4j-redirect.properties");
        String text = Resources.toString(url, Charsets.UTF_8);
        text = text
                .replaceAll("#LOGLEVEL#", givenLogLevel)
                .replaceAll("#LOGFILE#", config.getLogPath());

        Properties properties = new Properties();
        properties.load(new StringReader(text));
        PropertyConfigurator.configure(properties);
    }
}
 
Example 13
Source Project: gsc-core   Source File: Util.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean getVisible(final HttpServletRequest request) {
    boolean visible = false;
    if (StringUtil.isNotBlank(request.getParameter(VISIBLE))) {
        visible = Boolean.valueOf(request.getParameter(VISIBLE));
    }
    return visible;
}
 
Example 14
Source Project: onedev   Source File: Response.java    License: MIT License 5 votes vote down vote up
public void addCookie(HttpCookie cookie)
{
    if (StringUtil.isBlank(cookie.getName()))
        throw new IllegalArgumentException("Cookie.name cannot be blank/null");

    // add the set cookie
    _fields.add(new SetCookieHttpField(cookie, getHttpChannel().getHttpConfiguration().getResponseCookieCompliance()));

    // Expire responses with set-cookie headers so they do not get cached.
    _fields.put(__EXPIRES_01JAN1970);
}
 
Example 15
Source Project: onedev   Source File: Response.java    License: MIT License 5 votes vote down vote up
@Override
public String getCharacterEncoding()
{
    if (_characterEncoding == null)
    {
        String encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);
        if (encoding != null)
            return encoding;
        encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);
        if (encoding != null)
            return encoding;
        return StringUtil.__ISO_8859_1;
    }
    return _characterEncoding;
}
 
Example 16
Source Project: athenz   Source File: ZTSClientNotificationSenderImpl.java    License: Apache License 2.0 5 votes vote down vote up
public boolean init(NotificationManager notificationManager, RolesProvider rolesProvider, String serverName) {
    this.isInit = false;
    this.notificationManager = notificationManager;
    this.rolesProvider = rolesProvider;
    this.serverName = serverName;

    if (this.notificationManager != null && this.rolesProvider != null && !StringUtil.isEmpty(serverName)) {
        this.isInit = true;
    } else {
        LOGGER.warn("ZTSClientNotificationSenderImpl must be initiated with all arguments before it can be used");
    }

    return this.isInit;
}
 
Example 17
Source Project: openhab-core   Source File: ProxyServletService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * If the URI contains user info in the form <code>user[:pass]@</code>, attempt to preempt the server
 * returning a 401 by providing Basic Authentication support in the initial request to the server.
 *
 * @param uri the URI which may contain user info
 * @param request the outgoing request to which an authorization header may be added
 */
void maybeAppendAuthHeader(URI uri, Request request) {
    if (uri != null && uri.getUserInfo() != null) {
        String[] userInfo = uri.getUserInfo().split(":");

        if (userInfo.length >= 1) {
            String user = userInfo[0];
            String password = userInfo.length >= 2 ? userInfo[1] : null;
            String authString = password != null ? user + ":" + password : user + ":";

            String basicAuthentication = "Basic " + B64Code.encode(authString, StringUtil.__ISO_8859_1);
            request.header(HttpHeader.AUTHORIZATION, basicAuthentication);
        }
    }
}
 
Example 18
@Test
public void testMaybeAppendAuthHeaderWithFullCredentials() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://testuser:[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:testpassword", StringUtil.__ISO_8859_1));
}
 
Example 19
@Test
public void testMaybeAppendAuthHeaderWithoutPassword() throws URISyntaxException {
    Request request = mock(Request.class);
    URI uri = new URI("http://[email protected]:8080/content");
    service.maybeAppendAuthHeader(uri, request);
    verify(request).header(HttpHeader.AUTHORIZATION,
            "Basic " + B64Code.encode("testuser:", StringUtil.__ISO_8859_1));
}
 
Example 20
Source Project: IoTgo_Android_App   Source File: WebSocketConnectionRFC6455.java    License: MIT License 5 votes vote down vote up
public void sendMessage(String content) throws IOException
{
    if (_closedOut)
        throw new IOException("closedOut "+_closeCode+":"+_closeMessage);
    byte[] data = content.getBytes(StringUtil.__UTF8);
    _outbound.addFrame((byte)FLAG_FIN,WebSocketConnectionRFC6455.OP_TEXT,data,0,data.length);
    checkWriteable();
}
 
Example 21
Source Project: IoTgo_Android_App   Source File: HttpFields.java    License: MIT License 5 votes vote down vote up
/**
 * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'" 
 */
public String formatDate(long date)
{
    buf.setLength(0);
    gc.setTimeInMillis(date);
    
    int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
    int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
    int month = gc.get(Calendar.MONTH);
    int year = gc.get(Calendar.YEAR);
    int century = year / 100;
    year = year % 100;
    
    int hours = gc.get(Calendar.HOUR_OF_DAY);
    int minutes = gc.get(Calendar.MINUTE);
    int seconds = gc.get(Calendar.SECOND);

    buf.append(DAYS[day_of_week]);
    buf.append(',');
    buf.append(' ');
    StringUtil.append2digits(buf, day_of_month);

    buf.append(' ');
    buf.append(MONTHS[month]);
    buf.append(' ');
    StringUtil.append2digits(buf, century);
    StringUtil.append2digits(buf, year);
    
    buf.append(' ');
    StringUtil.append2digits(buf, hours);
    buf.append(':');
    StringUtil.append2digits(buf, minutes);
    buf.append(':');
    StringUtil.append2digits(buf, seconds);
    buf.append(" GMT");
    return buf.toString();
}
 
Example 22
Source Project: IoTgo_Android_App   Source File: HttpFields.java    License: MIT License 5 votes vote down vote up
/**
 * Format "EEE, dd-MMM-yy HH:mm:ss 'GMT'" for cookies
 */
public void formatCookieDate(StringBuilder buf, long date)
{
    gc.setTimeInMillis(date);
    
    int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
    int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
    int month = gc.get(Calendar.MONTH);
    int year = gc.get(Calendar.YEAR);
    year = year % 10000;

    int epoch = (int) ((date / 1000) % (60 * 60 * 24));
    int seconds = epoch % 60;
    epoch = epoch / 60;
    int minutes = epoch % 60;
    int hours = epoch / 60;

    buf.append(DAYS[day_of_week]);
    buf.append(',');
    buf.append(' ');
    StringUtil.append2digits(buf, day_of_month);

    buf.append('-');
    buf.append(MONTHS[month]);
    buf.append('-');
    StringUtil.append2digits(buf, year/100);
    StringUtil.append2digits(buf, year%100);
    
    buf.append(' ');
    StringUtil.append2digits(buf, hours);
    buf.append(':');
    StringUtil.append2digits(buf, minutes);
    buf.append(':');
    StringUtil.append2digits(buf, seconds);
    buf.append(" GMT");
}
 
Example 23
Source Project: IoTgo_Android_App   Source File: ByteArrayBuffer.java    License: MIT License 5 votes vote down vote up
public ByteArrayBuffer(String value)
{
    super(READWRITE,NON_VOLATILE);
    _bytes = StringUtil.getBytes(value);
    setGetIndex(0);
    setPutIndex(_bytes.length);
    _access=IMMUTABLE;
    _string = value;
}
 
Example 24
Source Project: IoTgo_Android_App   Source File: ByteArrayBuffer.java    License: MIT License 5 votes vote down vote up
public ByteArrayBuffer(String value,boolean immutable)
{
    super(READWRITE,NON_VOLATILE);
    _bytes = StringUtil.getBytes(value);
    setGetIndex(0);
    setPutIndex(_bytes.length);
    if (immutable)
    {
        _access=IMMUTABLE;
        _string = value;
    }
}
 
Example 25
Source Project: IoTgo_Android_App   Source File: ChannelEndPoint.java    License: MIT License 5 votes vote down vote up
public String getLocalAddr()
{
    if (_socket==null)
        return null;
   if (_local==null || _local.getAddress()==null || _local.getAddress().isAnyLocalAddress())
       return StringUtil.ALL_INTERFACES;
    return _local.getAddress().getHostAddress();
}
 
Example 26
Source Project: IoTgo_Android_App   Source File: ChannelEndPoint.java    License: MIT License 5 votes vote down vote up
public String getLocalHost()
{
    if (_socket==null)
        return null;
   if (_local==null || _local.getAddress()==null || _local.getAddress().isAnyLocalAddress())
       return StringUtil.ALL_INTERFACES;
    return _local.getAddress().getCanonicalHostName();
}
 
Example 27
Source Project: IoTgo_Android_App   Source File: WebSocketConnectionRFC6455.java    License: MIT License 5 votes vote down vote up
public void sendMessage(String content) throws IOException
{
    if (_closedOut)
        throw new IOException("closedOut "+_closeCode+":"+_closeMessage);
    byte[] data = content.getBytes(StringUtil.__UTF8);
    _outbound.addFrame((byte)FLAG_FIN,WebSocketConnectionRFC6455.OP_TEXT,data,0,data.length);
    checkWriteable();
}
 
Example 28
Source Project: IoTgo_Android_App   Source File: HttpFields.java    License: MIT License 5 votes vote down vote up
/**
 * Format HTTP date "EEE, dd MMM yyyy HH:mm:ss 'GMT'" 
 */
public String formatDate(long date)
{
    buf.setLength(0);
    gc.setTimeInMillis(date);
    
    int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
    int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
    int month = gc.get(Calendar.MONTH);
    int year = gc.get(Calendar.YEAR);
    int century = year / 100;
    year = year % 100;
    
    int hours = gc.get(Calendar.HOUR_OF_DAY);
    int minutes = gc.get(Calendar.MINUTE);
    int seconds = gc.get(Calendar.SECOND);

    buf.append(DAYS[day_of_week]);
    buf.append(',');
    buf.append(' ');
    StringUtil.append2digits(buf, day_of_month);

    buf.append(' ');
    buf.append(MONTHS[month]);
    buf.append(' ');
    StringUtil.append2digits(buf, century);
    StringUtil.append2digits(buf, year);
    
    buf.append(' ');
    StringUtil.append2digits(buf, hours);
    buf.append(':');
    StringUtil.append2digits(buf, minutes);
    buf.append(':');
    StringUtil.append2digits(buf, seconds);
    buf.append(" GMT");
    return buf.toString();
}
 
Example 29
Source Project: IoTgo_Android_App   Source File: HttpFields.java    License: MIT License 5 votes vote down vote up
/**
 * Format "EEE, dd-MMM-yy HH:mm:ss 'GMT'" for cookies
 */
public void formatCookieDate(StringBuilder buf, long date)
{
    gc.setTimeInMillis(date);
    
    int day_of_week = gc.get(Calendar.DAY_OF_WEEK);
    int day_of_month = gc.get(Calendar.DAY_OF_MONTH);
    int month = gc.get(Calendar.MONTH);
    int year = gc.get(Calendar.YEAR);
    year = year % 10000;

    int epoch = (int) ((date / 1000) % (60 * 60 * 24));
    int seconds = epoch % 60;
    epoch = epoch / 60;
    int minutes = epoch % 60;
    int hours = epoch / 60;

    buf.append(DAYS[day_of_week]);
    buf.append(',');
    buf.append(' ');
    StringUtil.append2digits(buf, day_of_month);

    buf.append('-');
    buf.append(MONTHS[month]);
    buf.append('-');
    StringUtil.append2digits(buf, year/100);
    StringUtil.append2digits(buf, year%100);
    
    buf.append(' ');
    StringUtil.append2digits(buf, hours);
    buf.append(':');
    StringUtil.append2digits(buf, minutes);
    buf.append(':');
    StringUtil.append2digits(buf, seconds);
    buf.append(" GMT");
}
 
Example 30
Source Project: IoTgo_Android_App   Source File: ByteArrayBuffer.java    License: MIT License 5 votes vote down vote up
public ByteArrayBuffer(String value)
{
    super(READWRITE,NON_VOLATILE);
    _bytes = StringUtil.getBytes(value);
    setGetIndex(0);
    setPutIndex(_bytes.length);
    _access=IMMUTABLE;
    _string = value;
}