提交 8ce86e66 编写于 作者: S serge-rider

#2502 Move all nls bundles/features in nls folder. Move modules (legacy name) into bundles

上级 1a9bf0ce
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.jkiss.utils</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.pde.PluginNature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %Bundle-Name
Bundle-SymbolicName: org.jkiss.utils
Bundle-Version: 2.1.51
Bundle-Release-Date: 20171030
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Export-Package: org.jkiss.code,
org.jkiss.utils,
org.jkiss.utils.time,
org.jkiss.utils.xml
Bundle-Vendor: %Bundle-Vendor
#Properties file for org.jkiss.utils
Bundle-Vendor = JKISS
Bundle-Name = JKISS Utils
source.. = src/
output.. = bin/
bin.includes = META-INF/,\
.,\
OSGI-INF/
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jkiss.dbeaver</groupId>
<artifactId>dbeaver</artifactId>
<version>1.0.0</version>
<relativePath>../../</relativePath>
</parent>
<artifactId>org.jkiss.utils</artifactId>
<version>2.1.51</version>
<packaging>eclipse-plugin</packaging>
</project>
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.code;
/**
* NotNull annotation
*/
public @interface NotNull {
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.code;
/**
* Nullable annotation
*/
public @interface Nullable {
}
/*
* Copyright (c) 2001-2010, JavaPLT group at Rice University (drjava@rice.edu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of DrJava, the JavaPLT group, Rice University, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software is Open Source Initiative approved Open Source Software.
* Open Source Initative Approved is a trademark of the Open Source Initiative.
*
* This file is part of DrJava. Download the current version of this project
* from http://www.drjava.org/ or http://sourceforge.net/projects/drjava/
*/
package org.jkiss.utils;
import java.util.LinkedList;
import java.util.List;
/**
* Utility class which can tokenize a String into a list of String arguments,
* with behavior similar to parsing command line arguments to a program.
* Quoted Strings are treated as single arguments, and escaped characters
* are translated so that the tokenized arguments have the same meaning.
* Since all methods are static, the class is declared abstract to prevent
* instantiation.
*
* @version $Id$
*/
public abstract class ArgumentTokenizer {
private static final int NO_TOKEN_STATE = 0;
private static final int NORMAL_TOKEN_STATE = 1;
private static final int SINGLE_QUOTE_STATE = 2;
private static final int DOUBLE_QUOTE_STATE = 3;
/**
* Tokenizes the given String into String tokens
*
* @param arguments A String containing one or more command-line style arguments to be tokenized.
* @return A list of parsed and properly escaped arguments.
*/
public static List<String> tokenize(String arguments) {
return tokenize(arguments, false);
}
/**
* Tokenizes the given String into String tokens.
*
* @param arguments A String containing one or more command-line style arguments to be tokenized.
* @param stringify whether or not to include escape special characters
* @return A list of parsed and properly escaped arguments.
*/
public static List<String> tokenize(String arguments, boolean stringify) {
LinkedList<String> argList = new LinkedList<String>();
StringBuilder currArg = new StringBuilder();
boolean escaped = false;
int state = NO_TOKEN_STATE; // start in the NO_TOKEN_STATE
int len = arguments.length();
// Loop over each character in the string
for (int i = 0; i < len; i++) {
char c = arguments.charAt(i);
if (escaped) {
// Escaped state: just append the next character to the current arg.
escaped = false;
if (c != 'n' && c != 't' && c != '\\') {
// This was just a regular slash
currArg.append('\\');
}
currArg.append(c);
} else {
switch (state) {
case SINGLE_QUOTE_STATE:
if (c == '\'') {
// Seen the close quote; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE;
} else {
currArg.append(c);
}
break;
case DOUBLE_QUOTE_STATE:
if (c == '"') {
// Seen the close quote; continue this arg until whitespace is seen
state = NORMAL_TOKEN_STATE;
} else if (c == '\\') {
// Look ahead, and only escape quotes or backslashes
i++;
char next = arguments.charAt(i);
if (next == '"' || next == '\\') {
currArg.append(next);
} else {
currArg.append(c);
currArg.append(next);
}
} else {
currArg.append(c);
}
break;
// case NORMAL_TOKEN_STATE:
// if (Character.isWhitespace(c)) {
// // Whitespace ends the token; start a new one
// argList.add(currArg.toString());
// currArg = new StringBuffer();
// state = NO_TOKEN_STATE;
// }
// else if (c == '\\') {
// // Backslash in a normal token: escape the next character
// escaped = true;
// }
// else if (c == '\'') {
// state = SINGLE_QUOTE_STATE;
// }
// else if (c == '"') {
// state = DOUBLE_QUOTE_STATE;
// }
// else {
// currArg.append(c);
// }
// break;
case NO_TOKEN_STATE:
case NORMAL_TOKEN_STATE:
switch (c) {
case '\\':
escaped = true;
state = NORMAL_TOKEN_STATE;
break;
case '\'':
state = SINGLE_QUOTE_STATE;
break;
case '"':
state = DOUBLE_QUOTE_STATE;
break;
default:
if (!Character.isWhitespace(c)) {
currArg.append(c);
state = NORMAL_TOKEN_STATE;
} else if (state == NORMAL_TOKEN_STATE) {
// Whitespace ends the token; start a new one
argList.add(currArg.toString());
currArg = new StringBuilder();
state = NO_TOKEN_STATE;
}
}
break;
default:
throw new IllegalStateException("ArgumentTokenizer state " + state + " is invalid!");
}
}
}
// If we're still escaped, put in the backslash
if (escaped) {
currArg.append('\\');
argList.add(currArg.toString());
}
// Close the last argument if we haven't yet
else if (state != NO_TOKEN_STATE) {
argList.add(currArg.toString());
}
// Format each argument if we've been told to stringify them
if (stringify) {
for (int i = 0; i < argList.size(); i++) {
argList.set(i, "\"" + _escapeQuotesAndBackslashes(argList.get(i)) + "\"");
}
}
return argList;
}
/**
* Inserts backslashes before any occurrences of a backslash or
* quote in the given string. Also converts any special characters
* appropriately.
*/
protected static String _escapeQuotesAndBackslashes(String s) {
final StringBuilder buf = new StringBuilder(s);
// Walk backwards, looking for quotes or backslashes.
// If we see any, insert an extra backslash into the buffer at
// the same index. (By walking backwards, the index into the buffer
// will remain correct as we change the buffer.)
for (int i = s.length() - 1; i >= 0; i--) {
char c = s.charAt(i);
if ((c == '\\') || (c == '"')) {
buf.insert(i, '\\');
}
// Replace any special characters with escaped versions
else if (c == '\n') {
buf.deleteCharAt(i);
buf.insert(i, "\\n");
} else if (c == '\t') {
buf.deleteCharAt(i);
buf.insert(i, "\\t");
} else if (c == '\r') {
buf.deleteCharAt(i);
buf.insert(i, "\\r");
} else if (c == '\b') {
buf.deleteCharAt(i);
buf.insert(i, "\\b");
} else if (c == '\f') {
buf.deleteCharAt(i);
buf.insert(i, "\\f");
}
}
return buf.toString();
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import java.lang.reflect.Array;
import java.util.*;
/**
* Common utils
*/
public class ArrayUtils {
public static boolean isEmpty(@Nullable Object[] arr)
{
return arr == null || arr.length == 0;
}
public static boolean isEmpty(@Nullable short[] array)
{
return array == null || array.length == 0;
}
public static boolean contains(@Nullable short[] array, short value)
{
if (array == null)
return false;
for (int i = 0, arrayLength = array.length; i < arrayLength; i++) {
if (array[i] == value)
return true;
}
return false;
}
public static boolean contains(@Nullable char[] array, char value)
{
if (array == null || array.length == 0)
return false;
for (int i = 0, arrayLength = array.length; i < arrayLength; i++) {
if (array[i] == value)
return true;
}
return false;
}
public static boolean isEmpty(@Nullable int[] array)
{
return array == null || array.length == 0;
}
public static boolean contains(@Nullable int[] array, int value)
{
if (array == null)
return false;
for (int v : array) {
if (v == value)
return true;
}
return false;
}
public static boolean isEmpty(@Nullable long[] array)
{
return array == null || array.length == 0;
}
public static boolean contains(@Nullable long[] array, long value)
{
if (array == null)
return false;
for (long v : array) {
if (v == value)
return true;
}
return false;
}
public static <OBJECT_TYPE> boolean contains(OBJECT_TYPE[] array, OBJECT_TYPE value)
{
if (isEmpty(array))
return false;
for (int i = 0; i < array.length; i++) {
if (CommonUtils.equalObjects(value, array[i]))
return true;
}
return false;
}
public static boolean containsIgnoreCase(String[] array, String value)
{
if (isEmpty(array) || value == null)
return false;
for (int i = 0; i < array.length; i++) {
if (value.equalsIgnoreCase(array[i]))
return true;
}
return false;
}
public static <OBJECT_TYPE> boolean containsRef(@NotNull OBJECT_TYPE[] array, @Nullable OBJECT_TYPE value)
{
final int length = array.length;
for (int i = 0; i < length; i++) {
if (value == array[i])
return true;
}
return false;
}
@SafeVarargs
public static <OBJECT_TYPE> boolean contains(OBJECT_TYPE[] array, OBJECT_TYPE... values)
{
if (isEmpty(array))
return false;
for (int i = 0; i < array.length; i++) {
for (int k = 0; k < values.length; k++) {
if (CommonUtils.equalObjects(array[i], values[k]))
return true;
}
}
return false;
}
@NotNull
public static <T> T[] concatArrays(@NotNull T[] first, @NotNull T[] second)
{
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
@NotNull
public static <T> List<T> safeArray(@Nullable T[] array)
{
if (array == null) {
return Collections.emptyList();
} else {
return Arrays.asList(array);
}
}
public static <T> int indexOf(T[] array, T element) {
for (int i = 0; i < array.length; i++) {
if (CommonUtils.equalObjects(array[i], element)) {
return i;
}
}
return -1;
}
public static int indexOf(byte[] array, int offset, byte element) {
for (int i = offset; i < array.length; i++) {
if (array[i] == element) {
return i;
}
}
return -1;
}
@SuppressWarnings("unchecked")
public static <T> T[] deleteArea(Class<T> type, T[] elements, int from, int to) {
int delCount = to - from + 1;
T[] newArray = (T[]) Array.newInstance(type, elements.length - delCount);
System.arraycopy(elements, 0, newArray, 0, from);
if (to < elements.length - 1) {
System.arraycopy(elements, to + 1, newArray, from, elements.length - from - delCount);
}
return newArray;
}
@SuppressWarnings("unchecked")
public static <T> T[] insertArea(Class<T> type, Object[] elements, int pos, Object[] add) {
T[] newArray = (T[]) Array.newInstance(type, elements.length + add.length);
System.arraycopy(elements, 0, newArray, 0, pos);
System.arraycopy(add, 0, newArray, pos, add.length);
System.arraycopy(elements, pos, newArray, pos + add.length, elements.length - pos);
return newArray;
}
@SuppressWarnings("unchecked")
public static <T> T[] add(Class<T> type, T[] elements, T add) {
T[] newArray = (T[]) Array.newInstance(type, elements.length + 1);
System.arraycopy(elements, 0, newArray, 0, elements.length);
newArray[elements.length] = add;
return newArray;
}
@SuppressWarnings("unchecked")
public static <T> T[] remove(Class<T> type, T[] elements, int index) {
T[] newArray = (T[]) Array.newInstance(type, elements.length - 1);
System.arraycopy(elements, 0, newArray, 0, index);
if (index < elements.length - 1) {
System.arraycopy(elements, index + 1, newArray, index, elements.length - index - 1);
}
return newArray;
}
public static <T> T[] remove(Class<T> type, T[] elements, T element) {
for (int i = 0; i < elements.length; i++) {
if (elements[i] == element) {
return remove(type, elements, i);
}
}
return elements;
}
public static void main(String[] args) {
String[] arr = new String[0];
for (int i = 0; i < 100; i++) {
arr = add(String.class, arr, String.valueOf(i));
}
System.out.println(Arrays.toString(arr));
for (int i = 0; i < 100; i++) {
arr = remove(String.class, arr, 0);
}
System.out.println(Arrays.toString(arr));
}
@SuppressWarnings("unchecked")
public static <T> T[] toArray(Class<T> type, Collection<? extends T> list) {
return list.toArray((T[]) Array.newInstance(type, list.size()));
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
public final class Base64 {
private static final char[] S_BASE64CHAR = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', '+', '/'
};
private static final char S_BASE64PAD = '=';
private static final byte[] S_DECODETABLE = new byte[128];
static {
for (int i = 0; i < S_DECODETABLE.length; i ++)
S_DECODETABLE[i] = Byte.MAX_VALUE; // 127
for (int i = 0; i < S_BASE64CHAR.length; i ++) // 0 to 63
S_DECODETABLE[S_BASE64CHAR[i]] = (byte)i;
}
private static int decode0(char[] ibuf, byte[] obuf, int wp) {
int outlen = 3;
if (ibuf[3] == S_BASE64PAD) outlen = 2;
if (ibuf[2] == S_BASE64PAD) outlen = 1;
int b0 = S_DECODETABLE[ibuf[0]];
int b1 = S_DECODETABLE[ibuf[1]];
int b2 = S_DECODETABLE[ibuf[2]];
int b3 = S_DECODETABLE[ibuf[3]];
switch (outlen) {
case 1:
obuf[wp] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
return 1;
case 2:
obuf[wp++] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
obuf[wp] = (byte)(b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
return 2;
case 3:
default:
obuf[wp++] = (byte)(b0 << 2 & 0xfc | b1 >> 4 & 0x3);
obuf[wp++] = (byte)(b1 << 4 & 0xf0 | b2 >> 2 & 0xf);
obuf[wp] = (byte)(b2 << 6 & 0xc0 | b3 & 0x3f);
return 3;
}
}
/**
*
*/
public static byte[] decode(char[] data, int off, int len) {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[len/4*3+3];
int obufcount = 0;
for (int i = off; i < off+len; i ++) {
char ch = data[i];
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
obufcount += decode0(ibuf, obuf, obufcount);
}
}
}
if (obufcount == obuf.length)
return obuf;
byte[] ret = new byte[obufcount];
System.arraycopy(obuf, 0, ret, 0, obufcount);
return ret;
}
/**
*
*/
public static byte[] decode(String data) {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[data.length()/4*3+3];
int obufcount = 0;
for (int i = 0; i < data.length(); i ++) {
char ch = data.charAt(i);
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
obufcount += decode0(ibuf, obuf, obufcount);
}
}
}
if (obufcount == obuf.length)
return obuf;
byte[] ret = new byte[obufcount];
System.arraycopy(obuf, 0, ret, 0, obufcount);
return ret;
}
/**
*
*/
public static void decode(char[] data, int off, int len, OutputStream ostream) throws IOException {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[3];
for (int i = off; i < off+len; i ++) {
char ch = data[i];
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
int obufcount = decode0(ibuf, obuf, 0);
ostream.write(obuf, 0, obufcount);
}
}
}
}
/**
*
*/
public static void decode(String data, OutputStream ostream) throws IOException {
char[] ibuf = new char[4];
int ibufcount = 0;
byte[] obuf = new byte[3];
for (int i = 0; i < data.length(); i ++) {
char ch = data.charAt(i);
if (ch == S_BASE64PAD
|| ch < S_DECODETABLE.length && S_DECODETABLE[ch] != Byte.MAX_VALUE) {
ibuf[ibufcount++] = ch;
if (ibufcount == ibuf.length) {
ibufcount = 0;
int obufcount = decode0(ibuf, obuf, 0);
ostream.write(obuf, 0, obufcount);
}
}
}
}
/**
* Returns base64 representation of specified byte array.
*/
public static String encode(byte[] data) {
return encode(data, 0, data.length);
}
public static String splitLines(String bigString, int lineLength) {
return bigString.replaceAll("(.{" + lineLength + "})", "$1\n");
}
/**
* Returns base64 representation of specified byte array.
*/
public static String encode(byte[] data, int off, int len)
{
if (len <= 0) return "";
char[] out = new char[len/3*4+4];
int rindex = off;
int windex = 0;
int rest = len-off;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[windex++] = S_BASE64CHAR[i>>18];
out[windex++] = S_BASE64CHAR[(i>>12)&0x3f];
out[windex++] = S_BASE64CHAR[(i>>6)&0x3f];
out[windex++] = S_BASE64CHAR[i&0x3f];
rindex += 3;
rest -= 3;
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[windex++] = S_BASE64CHAR[i>>2];
out[windex++] = S_BASE64CHAR[(i<<4)&0x3f];
out[windex++] = S_BASE64PAD;
out[windex++] = S_BASE64PAD;
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[windex++] = S_BASE64CHAR[i>>10];
out[windex++] = S_BASE64CHAR[(i>>4)&0x3f];
out[windex++] = S_BASE64CHAR[(i<<2)&0x3f];
out[windex++] = S_BASE64PAD;
}
return new String(out, 0, windex);
}
/**
* Outputs base64 representation of the specified byte array to a byte stream.
*/
public static void encode(byte[] data, int off, int len, OutputStream ostream) throws IOException {
if (len <= 0) return;
byte[] out = new byte[4];
int rindex = off;
int rest = len-off;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[0] = (byte)S_BASE64CHAR[i>>18];
out[1] = (byte)S_BASE64CHAR[(i>>12)&0x3f];
out[2] = (byte)S_BASE64CHAR[(i>>6)&0x3f];
out[3] = (byte)S_BASE64CHAR[i&0x3f];
ostream.write(out, 0, 4);
rindex += 3;
rest -= 3;
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[0] = (byte)S_BASE64CHAR[i>>2];
out[1] = (byte)S_BASE64CHAR[(i<<4)&0x3f];
out[2] = (byte)S_BASE64PAD;
out[3] = (byte)S_BASE64PAD;
ostream.write(out, 0, 4);
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[0] = (byte)S_BASE64CHAR[i>>10];
out[1] = (byte)S_BASE64CHAR[(i>>4)&0x3f];
out[2] = (byte)S_BASE64CHAR[(i<<2)&0x3f];
out[3] = (byte)S_BASE64PAD;
ostream.write(out, 0, 4);
}
}
/**
* Outputs base64 representation of the specified byte array to a character stream.
*/
public static void encode(byte[] data, int off, int len, Writer writer) throws IOException {
if (len <= 0) return;
char[] out = new char[4];
int rindex = off;
int rest = len-off;
while (rest >= 3) {
int i = ((data[rindex]&0xff)<<16)
+((data[rindex+1]&0xff)<<8)
+(data[rindex+2]&0xff);
out[0] = S_BASE64CHAR[i>>18];
out[1] = S_BASE64CHAR[(i>>12)&0x3f];
out[2] = S_BASE64CHAR[(i>>6)&0x3f];
out[3] = S_BASE64CHAR[i&0x3f];
writer.write(out, 0, 4);
rindex += 3;
rest -= 3;
/*
if (output % 76 == 0)
writer.write("\n");
*/
}
if (rest == 1) {
int i = data[rindex]&0xff;
out[0] = S_BASE64CHAR[i>>2];
out[1] = S_BASE64CHAR[(i<<4)&0x3f];
out[2] = S_BASE64PAD;
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
} else if (rest == 2) {
int i = ((data[rindex]&0xff)<<8)+(data[rindex+1]&0xff);
out[0] = S_BASE64CHAR[i>>10];
out[1] = S_BASE64CHAR[(i>>4)&0x3f];
out[2] = S_BASE64CHAR[(i<<2)&0x3f];
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
}
}
/**
* Outputs base64 representation of the specified input stream to a character stream.
*/
public static void encode(InputStream stream, long len, Writer writer)
throws IOException
{
if (len <= 0) return;
char[] out = new char[4];
long rest = len;
while (rest >= 3) {
int i = ((stream.read()&0xff)<<16)
+((stream.read()&0xff)<<8)
+(stream.read()&0xff);
out[0] = S_BASE64CHAR[i>>18];
out[1] = S_BASE64CHAR[(i>>12)&0x3f];
out[2] = S_BASE64CHAR[(i>>6)&0x3f];
out[3] = S_BASE64CHAR[i&0x3f];
writer.write(out, 0, 4);
rest -= 3;
}
if (rest == 1) {
int i = stream.read()&0xff;
out[0] = S_BASE64CHAR[i>>2];
out[1] = S_BASE64CHAR[(i<<4)&0x3f];
out[2] = S_BASE64PAD;
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
} else if (rest == 2) {
int i = ((stream.read()&0xff)<<8)+(stream.read()&0xff);
out[0] = S_BASE64CHAR[i>>10];
out[1] = S_BASE64CHAR[(i>>4)&0x3f];
out[2] = S_BASE64CHAR[(i<<2)&0x3f];
out[3] = S_BASE64PAD;
writer.write(out, 0, 4);
}
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import java.lang.reflect.*;
import java.util.Collection;
import java.util.StringTokenizer;
/**
* BeanUtils
*/
public class BeanUtils {
public static boolean isGetterName(String name) {
return name.startsWith("get") || name.startsWith("is") || name.startsWith("has");
}
public static String getPropertyNameFromGetter(String getterName) {
if (getterName.startsWith("get")) {
return
Character.toLowerCase(getterName.charAt(3)) +
getterName.substring(4);
} else if (getterName.startsWith("is")) {
return
Character.toLowerCase(getterName.charAt(2)) +
getterName.substring(3);
} else if (getterName.startsWith("has")) {
return
Character.toLowerCase(getterName.charAt(3)) +
getterName.substring(4);
} else {
// Unrecognized getter name
return null;
}
}
public static String getSetterName(String getterName) {
if (getterName.startsWith("get")) {
return "set" + getterName.substring(3);
} else if (getterName.startsWith("is")) {
return "set" + getterName.substring(2);
} else if (getterName.startsWith("has")) {
return "set" + getterName.substring(3);
} else {
// Unrecognized getter name
return null;
}
}
/**
* Returns a set method matching the property name.
*/
public static Method getSetMethod(Class<?> cl, String propertyName) {
Method method = getSetMethod(cl, propertyName, false);
if (method != null) {
return method;
}
return getSetMethod(cl, propertyName, true);
}
/**
* Returns a set method matching the property name.
*/
public static Method getSetMethod(
Class<?> cl,
String propertyName,
boolean ignoreCase) {
String setName = "set" + propertyNameToMethodName(propertyName);
return getSetMethod(
cl.getMethods(),
setName,
ignoreCase);
}
/**
* Returns a get method matching the property name.
*/
public static Method getGetMethod(Class<?> cl, String propertyName) {
Method method = getGetMethod(cl, propertyName, false);
return method != null ?
method :
getGetMethod(cl, propertyName, true);
}
/**
* Returns a get method matching the property name.
*/
public static Method getGetMethod(
Class<?> cl,
String propertyName,
boolean ignoreCase) {
String methodName = propertyNameToMethodName(propertyName);
return getGetMethod(
cl.getMethods(),
"get" + methodName,
"is" + methodName,
ignoreCase);
}
/**
* Converts a user's property name to a bean method name.
*
* @param propertyName the user property name
* @return the equivalent bean method name
*/
public static String propertyNameToMethodName(String propertyName) {
char ch = propertyName.charAt(0);
if (Character.isLowerCase(ch))
propertyName = Character.toUpperCase(ch) + propertyName.substring(1);
return propertyName;
}
/**
* Converts a user's property name to a bean method name.
*
* @param methodName the method name
* @return the equivalent property name
*/
public static String methodNameToPropertyName(String methodName) {
if (methodName.startsWith("get"))
methodName = methodName.substring(3);
else if (methodName.startsWith("set"))
methodName = methodName.substring(3);
else if (methodName.startsWith("is"))
methodName = methodName.substring(2);
if (methodName.length() == 0)
return null;
char ch = methodName.charAt(0);
if (Character.isUpperCase(ch) && (methodName.length() == 1 || !Character.isUpperCase(methodName.charAt(1)))) {
methodName = Character.toLowerCase(ch) + methodName.substring(1);
}
return methodName;
}
public static boolean isArrayType(Type type) {
return (type instanceof Class && ((Class<?>) type).isArray());
}
public static boolean isCollectionType(Type type) {
if (type instanceof Class && Collection.class.isAssignableFrom((Class<?>) type)) {
/*
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType)type;
if (pt.getActualTypeArguments().length == 1) {
return true;
}
}
*/
return true;
}
return isArrayType(type);
}
public static Class<?> getCollectionType(Type type) {
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
if (pt.getActualTypeArguments().length == 1) {
final Type argType = pt.getActualTypeArguments()[0];
if (argType instanceof Class) {
return (Class<?>) argType;
} else if (argType instanceof WildcardType) {
final Type[] upperBounds = ((WildcardType) argType).getUpperBounds();
if (upperBounds.length > 0 && upperBounds[0] instanceof Class) {
return (Class<?>) upperBounds[0];
}
final Type[] lowerBounds = ((WildcardType) argType).getLowerBounds();
if (lowerBounds.length > 0 && lowerBounds[0] instanceof Class) {
return (Class<?>) lowerBounds[0];
}
}
}
}
return null;
}
public static Object readObjectProperty(Object object, String propName)
throws IllegalAccessException, InvocationTargetException {
if (propName.indexOf('.') == -1) {
Method getter = getGetMethod(object.getClass(), propName);
return getter == null ? null : getter.invoke(object);
}
// Parse property path
StringTokenizer st = new StringTokenizer(propName, ".");
Object value = object;
while (value != null && st.hasMoreTokens()) {
String pathItem = st.nextToken();
Method getter = getGetMethod(value.getClass(), pathItem);
if (getter == null) {
return null;
}
value = getter.invoke(value);
}
return value;
}
/**
* Finds the matching set method
*/
private static Method getGetMethod(
Method[] methods,
String getName,
String isName,
boolean ignoreCase) {
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// The method must be public
if (
(!Modifier.isPublic(method.getModifiers())) ||
(!Modifier.isPublic(method.getDeclaringClass().getModifiers())) ||
(method.getParameterTypes().length != 0) ||
(method.getReturnType().equals(void.class))) {
continue;
} else if (!ignoreCase && method.getName().equals(getName)) {
// If it matches the get name, it's the right method
return method;
} else if (ignoreCase && method.getName().equalsIgnoreCase(getName)) {
// If it matches the get name, it's the right method
return method;
} else if (!method.getReturnType().equals(boolean.class)) {
// The is methods must return boolean
continue;
} else if (!ignoreCase && method.getName().equals(isName)) {
// If it matches the is name, it must return boolean
return method;
} else if (ignoreCase && method.getName().equalsIgnoreCase(isName)) {
// If it matches the is name, it must return boolean
return method;
}
}
return null;
}
/**
* Finds the matching set method
*
* @param setName the method name
*/
private static Method getSetMethod(
Method[] methods,
String setName,
boolean ignoreCase) {
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
// The method name must match
if (
!(ignoreCase ? method.getName().equalsIgnoreCase(setName) : method.getName().equals(setName)) ||
!Modifier.isPublic(method.getModifiers()) ||
!Modifier.isPublic(method.getDeclaringClass().getModifiers()) ||
method.getParameterTypes().length != 1
)
continue;
return method;
}
return null;
}
public static final Short DEFAULT_SHORT = (short) 0;
public static final Integer DEFAULT_INTEGER = 0;
public static final Long DEFAULT_LONG = 0l;
public static final Float DEFAULT_FLOAT = new Float(0.0);
public static final Double DEFAULT_DOUBLE = 0.0;
public static final Byte DEFAULT_BYTE = (byte) 0;
public static final Character DEFAULT_CHAR = (char) 0;
public static boolean isBooleanType(Type paramClass) {
return paramClass == Boolean.class || paramClass == Boolean.TYPE;
}
public static Object getDefaultPrimitiveValue(Class<?> paramClass) {
if (paramClass == Boolean.TYPE) {
return Boolean.FALSE;
} else if (paramClass == Short.TYPE) {
return DEFAULT_SHORT;
} else if (paramClass == Integer.TYPE) {
return DEFAULT_INTEGER;
} else if (paramClass == Long.TYPE) {
return DEFAULT_LONG;
} else if (paramClass == Float.TYPE) {
return DEFAULT_FLOAT;
} else if (paramClass == Double.TYPE) {
return DEFAULT_DOUBLE;
} else if (paramClass == Byte.TYPE) {
return DEFAULT_BYTE;
} else if (paramClass == Character.TYPE) {
return DEFAULT_CHAR;
} else {
throw new IllegalArgumentException("Class " + paramClass.getName() + " is not primitive type");
}
}
public static boolean isNumericType(Class<?> paramClass) {
return
Number.class.isAssignableFrom(paramClass) ||
paramClass == Short.TYPE ||
paramClass == Integer.TYPE ||
paramClass == Long.TYPE ||
paramClass == Double.TYPE ||
paramClass == Float.TYPE ||
paramClass == Byte.TYPE;
}
public static Object invokeObjectMethod(Object object, String name, Class<?> paramTypes[], Object args[])
throws Throwable {
Method method = object.getClass().getMethod(name, paramTypes);
if (!method.isAccessible()) {
method.setAccessible(true);
}
try {
return method.invoke(object, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
public static Object invokeObjectMethod(Object object, String name)
throws Throwable {
Method method = object.getClass().getMethod(name);
if (!method.isAccessible()) {
method.setAccessible(true);
}
try {
return method.invoke(object);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
public static Object invokeStaticMethod(Class<?> objectType, String name, Class<?> paramTypes[], Object args[])
throws Throwable {
Method method = objectType.getMethod(name, paramTypes);
if (!method.isAccessible()) {
method.setAccessible(true);
}
try {
return method.invoke(null, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* Common utils
*/
public class CommonUtils {
public static boolean isJavaIdentifier(@NotNull CharSequence str) {
for (int i = 0; i < str.length(); i++) {
if (!Character.isJavaIdentifierPart(str.charAt(i))) {
return false;
}
}
return true;
}
@NotNull
public static String escapeJavaString(@NotNull String str) {
StringBuilder res = new StringBuilder(str.length() + 5);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '"':
res.append("\\\"");
break;
case '\n':
res.append("\\n");
break;
case '\r':
res.append("\\r");
break;
case '\t':
res.append("\\t");
break;
default:
res.append(c);
break;
}
}
return res.toString();
}
@Nullable
public static String escapeIdentifier(@Nullable String str) {
if (str == null) {
return null;
}
StringBuilder res = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isJavaIdentifierPart(c)) {
res.append(c);
} else {
if (res.length() == 0 || res.charAt(res.length() - 1) != '_') {
res.append('_');
}
}
}
return res.toString();
}
@Nullable
public static String escapeFileName(@Nullable String str) {
if (str == null) {
return null;
}
StringBuilder res = new StringBuilder(str.length());
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (Character.isISOControl(c) || c == '\\' || c == '/' || c == '<' || c == '>' || c == '|' || c == '"' || c == ':'
|| c == '*' || c == '?') {
res.append('_');
} else {
res.append(c);
}
}
return res.toString();
}
public static String makeDirectoryName(@NotNull String str) {
if (!str.endsWith("/")) {
str += "/";
}
return str;
}
@NotNull
public static String removeTrailingSlash(@NotNull String str) {
while (str.endsWith("/") || str.endsWith("\\")) {
str = str.substring(0, str.length() - 1);
}
return str;
}
public static String capitalizeWord(String str) {
if (isEmpty(str) || Character.isUpperCase(str.charAt(0))) {
return str;
}
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
@NotNull
public static <T> T notNull(@Nullable T value, @NotNull T defaultValue) {
return value != null ? value : defaultValue;
}
public static boolean isEmpty(@Nullable CharSequence value) {
return value == null || value.length() == 0;
}
public static boolean isEmpty(@Nullable String value) {
return value == null || value.length() == 0;
}
public static boolean isNotEmpty(@Nullable String value) {
return !isEmpty(value);
}
public static boolean isEmpty(@Nullable Collection<?> value) {
return value == null || value.isEmpty();
}
public static boolean isEmpty(@Nullable Map<?, ?> value) {
return value == null || value.isEmpty();
}
@NotNull
public static <T> Collection<T> safeCollection(@Nullable Collection<T> theList) {
if (theList == null) {
theList = Collections.emptyList();
}
return theList;
}
@NotNull
public static <T> List<T> safeList(@Nullable List<T> theList) {
if (theList == null) {
theList = Collections.emptyList();
}
return theList;
}
@NotNull
public static <T> List<T> copyList(@Nullable Collection<T> theList) {
if (theList == null) {
return new ArrayList<>();
} else {
return new ArrayList<>(theList);
}
}
@NotNull
public static String notEmpty(@Nullable String value) {
return value == null ? "" : value;
}
public static boolean isTrue(Boolean value) {
return value != null && value;
}
public static boolean getBoolean(String value) {
return Boolean.parseBoolean(value);
}
public static boolean getBoolean(@Nullable String value, boolean defaultValue) {
return isEmpty(value) ? defaultValue : Boolean.parseBoolean(value);
}
public static boolean getBoolean(@Nullable Object value, boolean defaultValue) {
if (value == null) {
return defaultValue;
} else if (value instanceof Boolean) {
return (Boolean) value;
} else {
return getBoolean(value.toString(), defaultValue);
}
}
@NotNull
public static String getLineSeparator() {
String lineSeparator = System.getProperty(StandardConstants.ENV_LINE_SEPARATOR);
return lineSeparator == null ? "\n" : lineSeparator;
}
@NotNull
public static Throwable getRootCause(@NotNull Throwable ex) {
Throwable rootCause = ex;
for (; ; ) {
if (rootCause.getCause() != null) {
rootCause = rootCause.getCause();
} else if (rootCause instanceof InvocationTargetException
&& ((InvocationTargetException) rootCause).getTargetException() != null) {
rootCause = ((InvocationTargetException) rootCause).getTargetException();
} else {
break;
}
}
return rootCause;
}
public static boolean equalObjects(@Nullable Object o1, @Nullable Object o2) {
if (o1 == o2) {
return true;
}
if (o1 == null || o2 == null) {
return false;
}
// if (o1.getClass() != o2.getClass()) {
// return false;
// }
return o1.equals(o2);
}
@NotNull
public static String toString(@Nullable Object object) {
if (object == null) {
return "";
} else if (object instanceof String) {
return (String) object;
} else {
return object.toString();
}
}
public static String toString(@Nullable Object object, String def) {
if (object == null) {
return def;
} else if (object instanceof String) {
return (String) object;
} else {
return object.toString();
}
}
public static boolean toBoolean(@Nullable Object object) {
return object != null && getBoolean(object.toString());
}
public static int toInt(@Nullable Object object, int def) {
if (object == null) {
return def;
} else if (object instanceof Number) {
return ((Number) object).intValue();
} else {
try {
return Integer.parseInt(toString(object));
} catch (NumberFormatException e) {
return def;
}
}
}
public static int toInt(@Nullable Object object) {
return toInt(object, 0);
}
public static boolean isInt(@Nullable Object object) {
if (object == null) {
return false;
} else if (object instanceof Number) {
return true;
} else {
try {
Integer.parseInt(toString(object));
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
public static long toLong(@Nullable Object object) {
if (object == null) {
return 0;
} else if (object instanceof Number) {
return ((Number) object).longValue();
} else {
try {
return Long.parseLong(toString(object));
} catch (NumberFormatException e) {
return -1;
}
}
}
public static boolean isLong(@Nullable Object object) {
if (object == null) {
return false;
} else if (object instanceof Number) {
return true;
} else {
try {
Long.parseLong(toString(object));
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
@NotNull
public static String toHexString(@Nullable byte[] bytes) {
return bytes == null ? "" : toHexString(bytes, 0, bytes.length);
}
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
@NotNull
public static String toHexString(@Nullable byte[] bytes, int offset, int length) {
if (bytes == null || bytes.length == 0) {
return "";
}
char[] hexChars = new char[length * 2];
for (int i = 0; i < length; i++) {
int v = bytes[offset + i] & 0xFF;
hexChars[i * 2] = hexArray[v >>> 4];
hexChars[i * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static String toBinaryString(long longValue, int bitCount) {
String strValue = Long.toString(longValue, 2);
if (strValue.length() < bitCount) {
char[] headZeroes = new char[bitCount - strValue.length()];
Arrays.fill(headZeroes, '0');
strValue = String.valueOf(headZeroes) + strValue;
}
return strValue;
}
@NotNull
public static List<String> splitString(@Nullable String str, char delimiter) {
if (CommonUtils.isEmpty(str)) {
return Collections.emptyList();
} else {
List<String> result = new ArrayList<>();
StringTokenizer st = new StringTokenizer(str, String.valueOf(delimiter));
while (st.hasMoreTokens()) {
result.add(st.nextToken());
}
return result;
}
}
@NotNull
public static String makeString(@Nullable List<String> tokens, char delimiter) {
if (tokens == null) {
return "";
} else if (tokens.size() == 1) {
return tokens.get(0);
} else {
StringBuilder buf = new StringBuilder();
for (String token : tokens) {
if (buf.length() > 0) {
buf.append(delimiter);
}
buf.append(token);
}
return buf.toString();
}
}
@Nullable
public static String truncateString(@Nullable String str, int maxLength) {
if (str != null && str.length() > maxLength) {
return str.substring(0, maxLength);
}
return str;
}
public static String joinStrings(String divider, String ... array) {
if (array == null) return "";
StringBuilder str = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0) str.append(divider);
str.append(array[i]);
}
return str.toString();
}
public static String joinStrings(String divider, Collection<String> col) {
if (col == null) return "";
StringBuilder str = new StringBuilder();
for (String item : col) {
if (str.length() > 0) str.append(divider);
str.append(item);
}
return str.toString();
}
public static boolean isEmptyTrimmed(@Nullable String str) {
return str == null || str.length() == 0 || str.trim().length() == 0;
}
public static boolean isBitSet(int value, int mask) {
return (value & mask) == mask;
}
@Nullable
public static <T extends Enum<T>> T valueOf(@NotNull Class<T> type, @Nullable String name) {
return valueOf(type, name, false);
}
@Nullable
public static <T extends Enum<T>> T valueOf(@Nullable Class<T> type, @Nullable String name, boolean underscoreSpaces) {
if (name == null) {
return null;
}
name = name.trim();
if (name.length() == 0) {
return null;
}
if (underscoreSpaces) {
name = name.replace(' ', '_');
}
try {
return Enum.valueOf(type, name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@NotNull
public static <T> T getItem(@NotNull Collection<T> collection, int index) {
if (collection instanceof List) {
return ((List<T>) collection).get(index);
} else {
Iterator<T> iter = collection.iterator();
for (int i = 0; i < index; i++) {
iter.next();
}
return iter.next();
}
}
@NotNull
public static <T extends Enum<T>> T fromOrdinal(Class<T> enumClass, int ordinal) {
T[] enumConstants = enumClass.getEnumConstants();
for (T value : enumConstants) {
if (value.ordinal() == ordinal) {
return value;
}
}
IllegalArgumentException error = new IllegalArgumentException("Invalid ordinal " + ordinal + " for type " + enumClass.getName());
if (enumConstants.length == 0) {
throw error;
} else {
error.printStackTrace(System.err);
return enumConstants[0];
}
}
@NotNull
public static <T> List<T> filterCollection(@NotNull Collection<?> collection, @NotNull Class<T> type) {
List<T> result = new ArrayList<>();
for (Object item : collection) {
if (type.isInstance(item)) {
result.add(type.cast(item));
}
}
return result;
}
@NotNull
public static String escapeDisplayString(@NotNull final String delim) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < delim.length(); i++) {
char c = delim.charAt(i);
if (c == '\n') {
str.append("\\n");
} else if (c == '\r') {
str.append("\\r");
} else if (c == '\t') {
str.append("\\t");
} else {
str.append(c);
}
}
return str.toString();
}
@NotNull
public static String unescapeDisplayString(@NotNull final String delim) {
return delim.replace("\\t", "\t").replace("\\n", "\n").replace("\\r", "\r");
}
public static int hashCode(@Nullable Object obj) {
return obj == null ? 0 : obj.hashCode();
}
public static <T> T getOption(Map<String, ?> options, String name, T defValue) {
Object optionValue = options.get(name);
if (optionValue == null) {
return defValue;
}
return (T)optionValue;
}
public static boolean getOption(Map<String, ?> options, String name) {
return getOption(options, name, false);
}
public static boolean getOption(Map<String, ?> options, String name, boolean defValue) {
if (options == null) {
return false;
}
Object optionValue = options.get(name);
if (optionValue == null) {
return defValue;
}
return Boolean.TRUE.equals(optionValue);
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import java.io.*;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
* Some IO helper functions
*/
public final class IOUtils {
public static final int DEFAULT_BUFFER_SIZE = 16384;
public static void close(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void fastCopy(final InputStream src, final OutputStream dest) throws IOException {
fastCopy(src, dest, DEFAULT_BUFFER_SIZE);
}
public static void fastCopy(final InputStream src, final OutputStream dest, int bufferSize) throws IOException {
final ReadableByteChannel inputChannel = Channels.newChannel(src);
final WritableByteChannel outputChannel = Channels.newChannel(dest);
fastCopy(inputChannel, outputChannel, bufferSize);
}
public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest, int bufferSize) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
while (src.read(buffer) != -1) {
buffer.flip();
dest.write(buffer);
buffer.compact();
}
buffer.flip();
while (buffer.hasRemaining()) {
dest.write(buffer);
}
}
public static void copyStream(
java.io.InputStream inputStream,
java.io.OutputStream outputStream)
throws IOException {
copyStream(inputStream, outputStream, DEFAULT_BUFFER_SIZE);
}
/**
* Read entire input stream and writes all data to output stream
* then closes input and flushed output
*/
public static void copyStream(
java.io.InputStream inputStream,
java.io.OutputStream outputStream,
int bufferSize)
throws IOException {
try {
byte[] writeBuffer = new byte[bufferSize];
for (int br = inputStream.read(writeBuffer); br != -1; br = inputStream.read(writeBuffer)) {
outputStream.write(writeBuffer, 0, br);
}
outputStream.flush();
} finally {
// Close input stream
inputStream.close();
}
}
/**
* Read entire input stream portion and writes it data to output stream
*/
public static void copyStreamPortion(
java.io.InputStream inputStream,
java.io.OutputStream outputStream,
int portionSize,
int bufferSize)
throws IOException {
if (bufferSize > portionSize) {
bufferSize = portionSize;
}
byte[] writeBuffer = new byte[bufferSize];
int totalRead = 0;
while (totalRead < portionSize) {
int bytesToRead = bufferSize;
if (bytesToRead > portionSize - totalRead) {
bytesToRead = portionSize - totalRead;
}
int bytesRead = inputStream.read(writeBuffer, 0, bytesToRead);
outputStream.write(writeBuffer, 0, bytesRead);
totalRead += bytesRead;
}
// Close input stream
outputStream.flush();
}
public static String toString(File file, String encoding) throws IOException {
try (InputStream is = new FileInputStream(file)) {
try (Reader reader = new InputStreamReader(is, encoding)) {
StringWriter writer = new StringWriter();
copyText(reader, writer, DEFAULT_BUFFER_SIZE);
return writer.toString();
}
}
}
/**
* Read entire reader content and writes it to writer
* then closes reader and flushed output.
*/
public static void copyText(
java.io.Reader reader,
java.io.Writer writer,
int bufferSize)
throws IOException {
char[] writeBuffer = new char[bufferSize];
for (int br = reader.read(writeBuffer); br != -1; br = reader.read(writeBuffer)) {
writer.write(writeBuffer, 0, br);
}
writer.flush();
}
public static void copyText(
java.io.Reader reader,
java.io.Writer writer)
throws IOException {
copyText(reader, writer, DEFAULT_BUFFER_SIZE);
}
public static byte[] readFileToBuffer(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
try (InputStream is = new FileInputStream(file)) {
readStreamToBuffer(is, buffer);
}
return buffer;
}
public static int readStreamToBuffer(
java.io.InputStream inputStream,
byte[] buffer)
throws IOException {
int totalRead = 0;
while (totalRead != buffer.length) {
int br = inputStream.read(buffer, totalRead, buffer.length - totalRead);
if (br == -1) {
break;
}
totalRead += br;
}
return totalRead;
}
public static String readLine(java.io.InputStream input)
throws IOException {
StringBuilder linebuf = new StringBuilder();
for (int b = input.read(); b != '\n'; b = input.read()) {
if (b == -1) {
if (linebuf.length() == 0) {
return null;
} else {
break;
}
}
if (b != '\r') {
linebuf.append((char) b);
}
}
return linebuf.toString();
}
public static String readFullLine(java.io.InputStream input)
throws IOException {
StringBuilder linebuf = new StringBuilder();
for (int b = input.read(); ; b = input.read()) {
if (b == -1) {
if (linebuf.length() == 0) {
return null;
} else {
break;
}
}
linebuf.append((char) b);
if (b == '\n') {
break;
}
}
return linebuf.toString();
}
public static int findFreePort(int minPort, int maxPort) {
int portRange = Math.abs(maxPort - minPort);
while (true) {
int portNum = minPort + SecurityUtils.getRandom().nextInt(portRange);
try {
ServerSocket socket = new ServerSocket(portNum);
try {
socket.close();
} catch (IOException e) {
// just skip
}
return portNum;
} catch (IOException e) {
// Port is busy
}
}
}
public static String readToString(Reader is) throws IOException {
StringBuilder result = new StringBuilder(4000);
char[] buffer = new char[4000];
for (; ; ) {
int count = is.read(buffer);
if (count <= 0) {
break;
}
result.append(buffer, 0, count);
}
return result.toString();
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import java.util.Locale;
/**
* MIME type parser
*/
public class MimeType {
private String primaryType;
private String subType;
public MimeType() {
primaryType = "application";
subType = "*";
}
public MimeType(String rawdata) throws IllegalArgumentException {
parse(rawdata);
}
public MimeType(String primary, String sub) {
primaryType = primary.toLowerCase(Locale.ENGLISH);
subType = sub.toLowerCase(Locale.ENGLISH);
}
private void parse(String rawdata) throws IllegalArgumentException {
int slashIndex = rawdata.indexOf('/');
int semIndex = rawdata.indexOf(';');
if ((slashIndex < 0) && (semIndex < 0)) {
primaryType = rawdata;
subType = "*";
} else if ((slashIndex < 0) && (semIndex >= 0)) {
primaryType = rawdata.substring(0, semIndex);
subType = "*";
} else if ((slashIndex >= 0) && (semIndex < 0)) {
primaryType = rawdata.substring(0, slashIndex).trim().toLowerCase(Locale.ENGLISH);
subType = rawdata.substring(slashIndex + 1).trim().toLowerCase(Locale.ENGLISH);
} else if (slashIndex < semIndex) {
primaryType = rawdata.substring(0, slashIndex).trim().toLowerCase(Locale.ENGLISH);
subType = rawdata.substring(slashIndex + 1, semIndex).trim().toLowerCase(Locale.ENGLISH);
} else {
// we have a ';' lexically before a '/' which means we
// have a primary type and a parameter list but no sub type
throw new IllegalArgumentException("Unable to find a sub type.");
}
}
public String getPrimaryType() {
return primaryType;
}
public String getSubType() {
return subType;
}
public String toString() {
return getBaseType();
}
public String getBaseType() {
return primaryType + "/" + subType;
}
public boolean match(MimeType type) {
return primaryType.equals(type.getPrimaryType()) &&
(subType.equals("*") || type.getSubType().equals("*") || (subType.equals(type.getSubType())));
}
public boolean match(String rawdata) throws IllegalArgumentException {
return match(new MimeType(rawdata));
}
}
\ No newline at end of file
package org.jkiss.utils;
/**
* Pair
*/
public class Pair<T1, T2> {
private T1 first;
private T2 second;
public Pair(T1 first, T2 second)
{
this.first = first;
this.second = second;
}
public T1 getFirst()
{
return first;
}
public void setFirst(T1 first) {
this.first = first;
}
public T2 getSecond()
{
return second;
}
public void setSecond(T2 second) {
this.second = second;
}
@Override
public String toString() {
return first + "=" + second;
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
/**
* Come security-related functions.
*/
public class SecurityUtils {
public static String ECRYPTION_ALGORYTHM = "MD5";
private static java.util.Random random;
private static java.util.Random secureRand;
static {
secureRand = new java.util.Random(System.currentTimeMillis());
long secureInitializer = secureRand.nextLong();
random = new java.util.Random(secureInitializer);
}
/**
* Generate the random GUID
*/
public static String generateGUID(boolean secure) {
String localHostAddr;
{
java.net.InetAddress id;
try {
id = java.net.InetAddress.getLocalHost();
localHostAddr = id.toString();
} catch (java.net.UnknownHostException e) {
localHostAddr = "localhost";
}
}
long time = System.currentTimeMillis();
long rand;
if (secure) {
rand = secureRand.nextLong();
} else {
rand = SecurityUtils.random.nextLong();
}
// This StringBuilder can be a long as you need; the MD5
// hash will always return 128 bits. You can change
// the seed to include anything you want here.
// You could even stream a file through the MD5 making
// the odds of guessing it at least as great as that
// of guessing the contents of the file!
StringBuilder sb = new StringBuilder(32);
sb.append(localHostAddr)
.append(":")
.append(Long.toString(time))
.append(":")
.append(Long.toString(rand));
byte[] array;
try {
MessageDigest md5 = MessageDigest.getInstance(ECRYPTION_ALGORYTHM);
md5.update(sb.toString().getBytes());
array = md5.digest();
} catch (NoSuchAlgorithmException e) {
// Too bad. Lets get simple random numbers
array = new byte[16];
random.nextBytes(array);
}
sb.setLength(0);
for (int j = 0; j < array.length; ++j) {
int b = array[j] & 0xFF;
if (b < 0x10) {
sb.append('0');
}
sb.append(Integer.toHexString(b));
}
String raw = sb.toString().toUpperCase();
sb.setLength(0);
sb.append(raw.substring(0, 8));
sb.append("-");
sb.append(raw.substring(8, 12));
sb.append("-");
sb.append(raw.substring(12, 16));
sb.append("-");
sb.append(raw.substring(16, 20));
sb.append("-");
sb.append(raw.substring(20));
return sb.toString();
}
public static String generateUniqueId() {
long curTime = System.currentTimeMillis();
int random = secureRand.nextInt();
if (random < 0) {
random = -random;
}
return
Long.toString(curTime, Character.MAX_RADIX) +
Integer.toString(random, Character.MAX_RADIX);
}
public static String makeDigest(
String userAlias,
String userPassword) {
try {
if (userPassword == null) {
userPassword = "";
}
MessageDigest md5 =
MessageDigest.getInstance(ECRYPTION_ALGORYTHM);
md5.update(userAlias.getBytes());
return Base64.encode(md5.digest(userPassword.getBytes()));
} catch (NoSuchAlgorithmException toCatch) {
return "*";
}
}
public static String makeDigest(
String userPassword) {
try {
MessageDigest md5 =
MessageDigest.getInstance(ECRYPTION_ALGORYTHM);
return Base64.encode(md5.digest(userPassword.getBytes()));
} catch (NoSuchAlgorithmException toCatch) {
return "*";
}
}
/**
* Generate a random password of the given length.
*/
public static String generatePassword(int length) {
SecureRandom random = new SecureRandom();
StringBuilder pass = new StringBuilder(length);
for (int i = 0; i < length; i++) {
pass.append(
PASSWORD_ALPHABET[random.nextInt(PASSWORD_ALPHABET.length)]
);
}
return (pass.toString());
}
/**
* Generate a random password of the default length (8).
*/
public static String generatePassword() {
return generatePassword(DEFAULT_PASSWORD_LENGTH);
}
public static Random getRandom() {
return random;
}
/**
* Default length for passwords
*/
public static final int DEFAULT_PASSWORD_LENGTH = 8;
/**
* Alphabet consisting of upper and lowercase letters A-Z and
* the digits 0-9.
*/
public static final char[] PASSWORD_ALPHABET = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9',
};
}
/*
* Copyright (c) 2001-2010, JavaPLT group at Rice University (drjava@rice.edu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the names of DrJava, the JavaPLT group, Rice University, nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This software is Open Source Initiative approved Open Source Software.
* Open Source Initative Approved is a trademark of the Open Source Initiative.
*
* This file is part of DrJava. Download the current version of this project
* from http://www.drjava.org/ or http://sourceforge.net/projects/drjava/
*/
package org.jkiss.utils;
/**
* Standard Java constants
*/
public abstract class StandardConstants {
public static final String ENV_LINE_SEPARATOR = "line.separator";
public static final String ENV_PATH_SEPARATOR = "path.separator";
public static final String ENV_TMP_DIR = "java.io.tmpdir";
public static final String ENV_FILE_ENCODING = "file.encoding";
public static final String ENV_CONSOLE_ENCODING = "console.encoding";
public static final String ENV_USER_HOME = "user.home";
public static final String ENV_USER_NAME = "user.name";
public static final String ENV_OS_NAME = "os.name";
public static final String ENV_JAVA_VERSION = "java.version";
public static final String ENV_JAVA_CLASSPATH = "java.class.path";
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils.time;
import java.sql.Timestamp;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Formatter adapted to support nanoseconds from java.sql.Timestanp.
*/
public class ExtendedDateFormat extends SimpleDateFormat {
private static final String NINE_ZEROES = "000000000";
public static final int MAX_NANO_LENGTH = 8;
int nanoStart = -1, nanoLength;
boolean nanoOptional;
String nanoPrefix, nanoPostfix;
public ExtendedDateFormat(String pattern)
{
this(pattern, Locale.getDefault());
}
public ExtendedDateFormat(String pattern, Locale locale)
{
super(stripNanos(pattern), locale);
int quoteCount = 0;
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (c == '\'') {
quoteCount++;
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) == '\'') {
if (k != i + 1) {
quoteCount++;
}
i = k;
break;
}
}
} else if (c == '[') {
nanoStart = i;
nanoOptional = true;
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) == 'f') {
nanoLength++;
if (nanoPrefix == null) {
nanoPrefix = pattern.substring(i + 1, k);
}
}
if (pattern.charAt(k) == ']') {
nanoPostfix = pattern.substring(i + 1 + nanoPrefix.length() + nanoLength, k);
i = k + 1;
break;
}
}
} else if (c == 'f') {
nanoStart = i - quoteCount;
nanoOptional = false;
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) != 'f') {
break;
}
nanoLength++;
}
nanoLength++;
i = i + nanoLength;
}
}
}
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos)
{
StringBuffer result = super.format(date, toAppendTo, pos);
if (nanoStart >= 0) {
long nanos = 0;
if (date instanceof Timestamp) {
nanos = ((Timestamp) date).getNanos();
}
if (!nanoOptional || nanos > 0) {
StringBuilder nanosRes = new StringBuilder(nanoLength);
// Append nanos value in the end
if (nanoPrefix != null) {
nanosRes.append(nanoPrefix);
}
String nanoStr = String.valueOf(nanos);
// nanoStr must be a string of exactly 9 chars in length. Pad with leading "0" if not
int nbZeroesToPad = 9 - nanoStr.length();
if (nbZeroesToPad > 0) {
nanoStr = NINE_ZEROES.substring(0, nbZeroesToPad) + nanoStr;
}
if (nanoLength < nanoStr.length()) {
// Truncate nanos string to fit in the pattern
nanoStr = nanoStr.substring(0, nanoLength);
} else {
// Pad with 0s
for (int i = 0; i < nanoLength - nanoStr.length(); i++) {
nanosRes.append("0");
}
}
nanosRes.append(nanoStr);
if (nanoPostfix != null) {
nanosRes.append(nanoPostfix);
}
result.insert(nanoStart, nanosRes.toString());
}
}
return result;
}
@Override
public Date parse(String text, ParsePosition pos)
{
Date date = super.parse(text, pos);
int index = pos.getIndex();
if (index < text.length() && nanoStart > 0) {
long nanos = 0;
for (int i = 0; i < nanoLength; i++) {
int digitPos = index + i;
if (digitPos == text.length()) {
break;
}
char c = text.charAt(digitPos);
if (!Character.isDigit(c)) {
pos.setErrorIndex(index);
pos.setIndex(index);
//throw new ParseException("Invalid nanosecond character at pos " + digitPos + ": " + c, index);
return null;
}
long digit = ((int)c - (int)'0');
for (int k = MAX_NANO_LENGTH - i; k > 0; k--) {
digit *= 10;
}
nanos += digit;
}
if (nanos > 0) {
Timestamp ts = new Timestamp(date.getTime());
ts.setNanos((int)nanos);
return ts;
}
}
return date;
}
private static String stripNanos(String pattern)
{
for (int i = 0; i < pattern.length(); i++) {
char c = pattern.charAt(i);
if (c == '\'') {
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) == '\'') {
i = k;
break;
}
}
} else if (c == '[') {
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) == ']') {
return pattern.substring(0, i) + pattern.substring(k + 1);
}
}
} else if (c == 'f') {
for (int k = i + 1; k < pattern.length(); k++) {
if (pattern.charAt(k) != 'f') {
return pattern.substring(0, i) + pattern.substring(k);
}
}
return pattern.substring(0, i);
}
}
return pattern;
}
public static void main(String[] args)
{
test("'TIMESTAMP '''yyyy-MM-dd HH:mm:ss.ffffff''");
test("yyyy-MM-dd Z hh:mm:ss[.fffffffff]");
test("yyyy-MM-dd Z hh:mm:ss.fffffffff");
test("yyyy-MM-dd Z hh:mm:ss");
test("yyyy-MM-dd Z hh:mm:ss[.fffffffff nanos]");
test("yyyy-MM-dd Z hh:mm:ss[.ffffff micros]");
test("yyyy-MM-dd Z hh:mm:ss.ffffff");
test("yyyy-MM-dd Z hh:mm:ss.f"); // 1/10 secs = 'S'
}
private static void test(String pattern)
{
ExtendedDateFormat edf = new ExtendedDateFormat(pattern);
Timestamp date = new Timestamp(System.currentTimeMillis());
System.out.println(edf.format(date));
date.setNanos(0);
System.out.println(edf.format(date));
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils.xml;
import org.xml.sax.Attributes;
/**
SAX document listener
*/
public interface SAXListener {
void saxStartElement(
SAXReader reader,
String namespaceURI,
String localName,
org.xml.sax.Attributes atts)
throws XMLException;
void saxText(
SAXReader reader,
String data)
throws XMLException;
void saxEndElement(
SAXReader reader,
String namespaceURI,
String localName)
throws XMLException;
/**
* Empty listener supposed to skip element subtrees
*/
class BaseListener implements SAXListener {
@Override
public void saxStartElement(SAXReader reader, String namespaceURI, String localName, Attributes atts) throws XMLException {
}
@Override
public void saxText(SAXReader reader, String data) throws XMLException {
}
@Override
public void saxEndElement(SAXReader reader, String namespaceURI, String localName) throws XMLException {
}
}
SAXListener EMPTY_LISTENER = new BaseListener();
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils.xml;
import org.xml.sax.*;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* SAX document reader
*/
public final class SAXReader implements ContentHandler, EntityResolver, DTDHandler {
public static final int DEFAULT_POOL_SIZE = 10;
private static javax.xml.parsers.SAXParserFactory saxParserFactory = null;
private static List<Parser> parsersPool = new ArrayList<>();
private org.xml.sax.InputSource inputSource;
private Locator locator;
private Map<String, Object> attributes = new HashMap<>();
private List<SAXListener> elementLayers = new ArrayList<>();
private SAXListener curListener;
private StringBuilder textValue = new StringBuilder();
private int depth = 0;
private boolean handleWhiteSpaces = false;
/**
* Private constructor.
* Initialize parser.
*/
private SAXReader() {
}
/**
* Standard constructor.
* Initialize parser and prepare input stream for reading.
*/
public SAXReader(InputStream stream) {
this();
inputSource = new org.xml.sax.InputSource(stream);
}
/**
* Standard constructor.
* Initialize parser and prepare input stream for reading.
*/
public SAXReader(Reader reader) {
this();
inputSource = new org.xml.sax.InputSource(reader);
}
public boolean isHandleWhiteSpaces() {
return handleWhiteSpaces;
}
public void setHandleWhiteSpaces(
boolean flag) {
handleWhiteSpaces = flag;
}
public Locator getLocator() {
return locator;
}
/**
* Parse input stream and handle XML tags.
*/
public void parse(SAXListener listener)
throws IOException, XMLException {
// Initialize SAX parser
Parser parser = acquireParser();
// Get reader and parse using SAX2 API
try {
XMLReader saxReader = parser.getSAXParser().getXMLReader();
saxReader.setErrorHandler(new ParseErrorHandler());
saxReader.setContentHandler(this);
saxReader.setEntityResolver(this);
saxReader.setDTDHandler(this);
curListener = listener;
elementLayers.add(listener);
saxReader.parse(inputSource);
} catch (SAXParseException toCatch) {
throw new XMLException(
"Document parse error (line " + toCatch.getLineNumber() + ", pos " + toCatch.getColumnNumber(),
toCatch);
} catch (SAXException toCatch) {
throw new XMLException(
"Document reading SAX exception",
XMLUtils.adaptSAXException(toCatch));
} finally {
parser.close();
}
}
public synchronized static Parser acquireParser() throws XMLException {
try {
if (saxParserFactory == null) {
try {
saxParserFactory = javax.xml.parsers.SAXParserFactory.newInstance();
saxParserFactory.setNamespaceAware(true);
saxParserFactory.setValidating(false);
} catch (FactoryConfigurationError toCatch) {
throw new XMLException(
"SAX factory configuration error",
toCatch);
}
}
for (int i = 0; i < parsersPool.size(); i++) {
Parser parser = parsersPool.get(i);
if (parser != null) {
if (!parser.isAcquired()) {
parser.acquire();
return parser;
}
} else {
parsersPool.remove(i);
parser = new Parser(saxParserFactory.newSAXParser(), true);
parsersPool.add(parser);
return parser;
}
}
if (parsersPool.size() == DEFAULT_POOL_SIZE) {
throw new XMLException(
"Maximum SAX Parsers Number Exceeded (" + DEFAULT_POOL_SIZE + ")");
}
Parser parser = new Parser(saxParserFactory.newSAXParser(), true);
parsersPool.add(parser);
return parser;
} catch (ParserConfigurationException toCatch) {
throw new XMLException(
"SAX Parser Configuration error",
toCatch);
} catch (SAXException toCatch) {
throw new XMLException(
"SAX Parser error",
toCatch);
}
}
/**
* Closes parser and frees all resources.
*/
public void close() {
if (elementLayers != null) {
elementLayers.clear();
elementLayers = null;
}
inputSource = null;
curListener = null;
}
/**
* Set listener for next event.
*/
public void setListener(
SAXListener listener) {
curListener = listener;
}
public boolean hasAttribute(
String name) {
return attributes.get(name) != null;
}
public Object getAttribute(
String name) {
return attributes.get(name);
}
public void setAttribute(
String name,
Object value) {
attributes.put(name, value);
}
public Object removeAttribute(
String name) {
return attributes.remove(name);
}
private void handleText()
throws SAXException {
curListener = elementLayers.get(elementLayers.size() - 1);
try {
String value = textValue.toString();
curListener.saxText(this, value);
} catch (Exception toCatch) {
throw new SAXException(toCatch);
} finally {
textValue.setLength(0);
}
}
///////////////////////////////////////////////////////////////
// SAX Context Handler overrides
///////////////////////////////////////////////////////////////
@Override
public void startDocument() {
// just do-nothing
}
@Override
public void endDocument() {
this.close();
}
@Override
public void startElement(
String namespaceURI,
String localName,
String qName,
org.xml.sax.Attributes attributes)
throws SAXException {
if (depth++ > 0) {
this.handleText();
}
curListener = elementLayers.get(elementLayers.size() - 1);
try {
curListener.saxStartElement(this, namespaceURI, localName, attributes);
} catch (XMLException toCatch) {
throw new SAXException(toCatch);
}
elementLayers.add(curListener);
}
@Override
public void endElement(
String namespaceURI,
String localName,
String qName)
throws SAXException {
this.handleText();
elementLayers.remove(elementLayers.size() - 1);
curListener = elementLayers.get(elementLayers.size() - 1);
try {
curListener.saxEndElement(this, namespaceURI, localName);
} catch (XMLException toCatch) {
throw new SAXException(toCatch);
}
depth--;
}
@Override
public void startPrefixMapping(String prefix, String uri) {
// just do-nothing
}
@Override
public void endPrefixMapping(String prefix) {
// just do-nothing
}
@Override
public void characters(char[] ch, int start, int length) {
textValue.append(ch, start, length);
}
@Override
public void ignorableWhitespace(char[] ch, int start, int length) {
if (handleWhiteSpaces) {
textValue.append(ch, start, length);
}
}
@Override
public void processingInstruction(String target, String data) {
// just do-nothing
}
@Override
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
@Override
public void skippedEntity(String name) {
// just do-nothing
}
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
// Return empty stream - we don't need entities by default
return new InputSource(new StringReader(""));
}
@Override
public void notationDecl(String name, String publicId, String systemId) throws SAXException {
// do nothing
}
@Override
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException {
// do nothing
}
static public class Parser {
private javax.xml.parsers.SAXParser saxParser;
private boolean isAcquired;
public Parser(javax.xml.parsers.SAXParser saxParser, boolean isAcquired) {
this.saxParser = saxParser;
this.isAcquired = isAcquired;
}
public void setSAXParser(javax.xml.parsers.SAXParser saxParser) {
this.saxParser = saxParser;
}
public void acquire() {
isAcquired = true;
}
public void close() {
isAcquired = false;
}
public javax.xml.parsers.SAXParser getSAXParser() {
return saxParser;
}
public boolean isAcquired() {
return isAcquired;
}
}
static class ParseErrorHandler implements org.xml.sax.ErrorHandler {
@Override
public void error(SAXParseException exception) {
}
@Override
public void fatalError(SAXParseException exception) {
}
@Override
public void warning(SAXParseException exception) {
}
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils.xml;
/**
XML Constants
*/
public class XMLConstants {
public static final String XMLNS = "xmlns";
public static final String NS_XML = "http://www.w3.org/TR/REC-xml";
public static final String PREFIX_XML = "xml";
public static final String ATTR_LANG = "lang";
public static String XML_HEADER()
{
return "<?xml version=\"1.0\"?>";
}
public static String XML_HEADER(String encoding)
{
return "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>";
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.utils.xml;
/**
* XMLException
*/
public class XMLException extends Exception
{
public XMLException(String message)
{
super(message);
}
public XMLException(String message, Throwable cause)
{
super(message, cause);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
<classpathentry kind="src" path="src/java"/>
<classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
<classpathentry kind="output" path="bin"/>
</classpath>
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>org.jkiss.wmi</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.ManifestBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.pde.SchemaBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.pde.PluginNature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>
#Fri Dec 30 22:00:36 MSK 2011
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: %Bundle-Name
Bundle-SymbolicName: org.jkiss.wmi
Bundle-Version: 2.0.61
Bundle-Release-Date: 20171030
Bundle-RequiredExecutionEnvironment: JavaSE-1.8
Bundle-Vendor: %Bundle-Vendor
Export-Package: org.jkiss.wmi.service
#Properties file for org.jkiss.wmi
Bundle-Vendor = JKISS
Bundle-Name = JKISS WMI native interface
source.. = src/java
output.. = bin/
bin.includes = META-INF/,\
.,\
native/,\
OSGI-INF/
copy .\lib\jkiss_wmi_x86.dll ..\..\contrib\drivers\wmi\x86\jkiss_wmi.dll
copy .\lib\jkiss_wmi_x64.dll ..\..\contrib\drivers\wmi\x64\jkiss_wmi.dll
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jkiss.dbeaver</groupId>
<artifactId>dbeaver</artifactId>
<version>1.0.0</version>
<relativePath>../../</relativePath>
</parent>
<artifactId>org.jkiss.wmi</artifactId>
<version>2.0.61</version>
<packaging>eclipse-plugin</packaging>
</project>
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.wmi.service;
/**
* WMI data type
*/
public enum WMIDataType {
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.wmi.service;
/**
* WMIException
*/
public class WMIException extends Exception {
public WMIException(String message) {
super(message);
}
}
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.wmi.service;
/**
* Object sink
*/
public interface WMIObjectSink {
void indicate(WMIObject[] objects);
void setStatus(WMIObjectSinkStatus status, int result, String param, WMIObject errorObject);
}
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
set JAVA_HOME=D:\Java\jdk1.6.0_06
set PATH=%JAVA_HOME%/bin;%PATH%
javah -classpath ../../bin;../../../../plugins/org.jkiss.dbeaver.core/bin -o WMIServiceJNI.h org.jkiss.wmi.service.WMIService
javah -classpath ../../bin;../../../../plugins/org.jkiss.dbeaver.core/bin -o WMIObjectJNI.h org.jkiss.wmi.service.WMIObject
\ No newline at end of file
set JAVA_HOME=D:\Java\jdk1.6.0_06
set PATH=%JAVA_HOME%/bin;%PATH%
javap -classpath ../../bin;../../../../plugins/org.jkiss.dbeaver.core/bin -s org.jkiss.wmi.service.WMIService
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册