org.eclipse.jetty.util.StringUtil Java Examples

The following examples show how to use org.eclipse.jetty.util.StringUtil. 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 File: DBStoreBuilder.java    From hadoop-ozone with 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 #2
Source File: SecurityCheckFactory.java    From commafeed with 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 #3
Source File: ErrorResponseContentCreator.java    From vespa with 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 #4
Source File: SimTxnSession.java    From java-trader with 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 #5
Source File: Response.java    From onedev with 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 File: Response.java    From onedev with 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 #7
Source File: ColumnsInfoServlet.java    From clickhouse-jdbc-bridge with 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 #8
Source File: DBConfigFromFile.java    From hadoop-ozone with 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 #9
Source File: HttpFields.java    From IoTgo_Android_App with 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 #10
Source File: ByteArrayBuffer.java    From IoTgo_Android_App with 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 #11
Source File: HttpFields.java    From IoTgo_Android_App with 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 #12
Source File: ByteArrayBuffer.java    From IoTgo_Android_App with 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 #13
Source File: QueryHandlerServlet.java    From clickhouse-jdbc-bridge with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: ChannelEndPoint.java    From IoTgo_Android_App with 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 #15
Source File: ChannelEndPoint.java    From IoTgo_Android_App with 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 #16
Source File: WebSocketConnectionRFC6455.java    From IoTgo_Android_App with 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 #17
Source File: HttpFields.java    From IoTgo_Android_App with 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 #18
Source File: HttpFields.java    From IoTgo_Android_App with 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 #19
Source File: ByteArrayBuffer.java    From IoTgo_Android_App with 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 #20
Source File: ByteArrayBuffer.java    From IoTgo_Android_App with 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 #21
Source File: ChannelEndPoint.java    From IoTgo_Android_App with 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 #22
Source File: ChannelEndPoint.java    From IoTgo_Android_App with 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 #23
Source File: OAuthClientServiceImpl.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public AccessTokenResponse refreshToken() throws OAuthException, IOException, OAuthResponseException {

    if (isClosed()) {
        throw new OAuthException(EXCEPTION_MESSAGE_CLOSED);
    }

    AccessTokenResponse lastAccessToken;
    try {
        lastAccessToken = storeHandler.loadAccessTokenResponse(handle);
    } catch (GeneralSecurityException e) {
        throw new OAuthException("Cannot decrypt access token from store", e);
    }
    if (lastAccessToken == null) {
        throw new OAuthException(
                "Cannot refresh token because last access token is not available from handle: " + handle);
    }
    if (lastAccessToken.getRefreshToken() == null) {
        throw new OAuthException("Cannot refresh token because last access token did not have a refresh token");
    }
    String tokenUrl = persistedParams.tokenUrl;
    if (tokenUrl == null) {
        throw new OAuthException("tokenUrl is required but null");
    }

    OAuthConnector connector = new OAuthConnector(httpClientFactory);
    AccessTokenResponse accessTokenResponse = connector.grantTypeRefreshToken(tokenUrl,
            lastAccessToken.getRefreshToken(), persistedParams.clientId, persistedParams.clientSecret,
            persistedParams.scope, Boolean.TRUE.equals(persistedParams.supportsBasicAuth));

    // The service may not return the refresh token so use the last refresh token otherwise it's not stored.
    if (StringUtil.isBlank(accessTokenResponse.getRefreshToken())) {
        accessTokenResponse.setRefreshToken(lastAccessToken.getRefreshToken());
    }
    // store it
    storeHandler.saveAccessTokenResponse(handle, accessTokenResponse);
    accessTokenRefreshListeners.forEach(l -> l.onAccessTokenResponse(accessTokenResponse));
    return accessTokenResponse;
}
 
Example #24
Source File: ProxyServletService.java    From smarthome with 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 #25
Source File: ProxyServletServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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 #26
Source File: ProxyServletServiceTest.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@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 #27
Source File: Application.java    From rest-utils with Apache License 2.0 5 votes vote down vote up
/**
 * Register header filter to ServletContextHandler.
 * @param context The serverlet context handler
 */
protected void configureHttpResponsHeaderFilter(ServletContextHandler context) {
  String headerConfig = config.getString(RestConfig.RESPONSE_HTTP_HEADERS_CONFIG);
  log.debug("headerConfig : " + headerConfig);
  String[] configs = StringUtil.csvSplit(headerConfig);
  Arrays.stream(configs)
          .forEach(RestConfig::validateHttpResponseHeaderConfig);
  FilterHolder headerFilterHolder = new FilterHolder(HeaderFilter.class);
  headerFilterHolder.setInitParameter("headerConfig", headerConfig);
  context.addFilter(headerFilterHolder, "/*", EnumSet.of(DispatcherType.REQUEST));
}
 
Example #28
Source File: LogMessage.java    From nifi with Apache License 2.0 5 votes vote down vote up
private void processFlowFile(
        final ComponentLog logger,
        final MessageLogLevel logLevel,
        final FlowFile flowFile,
        final ProcessContext context) {

    String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();
    String logMessage = context.getProperty(LOG_MESSAGE).evaluateAttributeExpressions(flowFile).getValue();

    String messageToWrite;
    if (StringUtil.isBlank(logPrefix)) {
        messageToWrite = logMessage;
    } else {
        messageToWrite = String.format("%s%s", logPrefix, logMessage);
    }

    // Uses optional property to specify logging level
    switch (logLevel) {
        case info:
            logger.info(messageToWrite);
            break;
        case debug:
            logger.debug(messageToWrite);
            break;
        case warn:
            logger.warn(messageToWrite);
            break;
        case trace:
            logger.trace(messageToWrite);
            break;
        case error:
            logger.error(messageToWrite);
            break;
        default:
            logger.debug(messageToWrite);
    }
}
 
Example #29
Source File: WebSocketConnectionRFC6455.java    From IoTgo_Android_App with 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 #30
Source File: JdbcBridge.java    From clickhouse-jdbc-bridge with 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);
    }
}