code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public String DsMakeSpn(String serviceClass, String serviceName, String instanceName,
short instancePort, String referrer) throws LastErrorException {
IntByReference spnLength = new IntByReference(2048);
char[] spn = new char[spnLength.getValue()];
final int ret =
NTDSAPI.instance.DsMakeSpnW(
new WString(serviceClass),
new WString(serviceName),
instanceName == null ? null : new WString(instanceName),
instancePort,
referrer == null ? null : new WString(referrer),
spnLength,
spn);
if (ret != NTDSAPI.ERROR_SUCCESS) {
/* Should've thrown LastErrorException, but just in case */
throw new RuntimeException("NTDSAPI DsMakeSpn call failed with " + ret);
}
return new String(spn, 0, spnLength.getValue());
} | java |
public static long int8(byte[] bytes, int idx) {
return
((long) (bytes[idx + 0] & 255) << 56)
+ ((long) (bytes[idx + 1] & 255) << 48)
+ ((long) (bytes[idx + 2] & 255) << 40)
+ ((long) (bytes[idx + 3] & 255) << 32)
+ ((long) (bytes[idx + 4] & 255) << 24)
+ ((long) (bytes[idx + 5] & 255) << 16)
+ ((long) (bytes[idx + 6] & 255) << 8)
+ (bytes[idx + 7] & 255);
} | java |
public static int int4(byte[] bytes, int idx) {
return
((bytes[idx] & 255) << 24)
+ ((bytes[idx + 1] & 255) << 16)
+ ((bytes[idx + 2] & 255) << 8)
+ ((bytes[idx + 3] & 255));
} | java |
public static void int8(byte[] target, int idx, long value) {
target[idx + 0] = (byte) (value >>> 56);
target[idx + 1] = (byte) (value >>> 48);
target[idx + 2] = (byte) (value >>> 40);
target[idx + 3] = (byte) (value >>> 32);
target[idx + 4] = (byte) (value >>> 24);
target[idx + 5] = (byte) (value >>> 16);
target[idx + 6] = (byte) (value >>> 8);
target[idx + 7] = (byte) value;
} | java |
public static Encoding getJVMEncoding(String jvmEncoding) {
if ("UTF-8".equals(jvmEncoding)) {
return new UTF8Encoding();
}
if (Charset.isSupported(jvmEncoding)) {
return new Encoding(jvmEncoding);
} else {
return DEFAULT_ENCODING;
}
} | java |
public static Encoding getDatabaseEncoding(String databaseEncoding) {
if ("UTF8".equals(databaseEncoding)) {
return UTF8_ENCODING;
}
// If the backend encoding is known and there is a suitable
// encoding in the JVM we use that. Otherwise we fall back
// to the default encoding of the JVM.
String[] candidates = encodings.get(databaseEncoding);
if (candidates != null) {
for (String candidate : candidates) {
LOGGER.log(Level.FINEST, "Search encoding candidate {0}", candidate);
if (Charset.isSupported(candidate)) {
return new Encoding(candidate);
}
}
}
// Try the encoding name directly -- maybe the charset has been
// provided by the user.
if (Charset.isSupported(databaseEncoding)) {
return new Encoding(databaseEncoding);
}
// Fall back to default JVM encoding.
LOGGER.log(Level.FINEST, "{0} encoding not found, returning default encoding", databaseEncoding);
return DEFAULT_ENCODING;
} | java |
public byte[] encode(String s) throws IOException {
if (s == null) {
return null;
}
return s.getBytes(encoding);
} | java |
public String decode(byte[] encodedString, int offset, int length) throws IOException {
return new String(encodedString, offset, length, encoding);
} | java |
public static Method getFunction(String functionName) {
return functionMap.get("sql" + functionName.toLowerCase(Locale.US));
} | java |
public static String sqlconcat(List<?> parsedArgs) {
StringBuilder buf = new StringBuilder();
buf.append('(');
for (int iArg = 0; iArg < parsedArgs.size(); iArg++) {
buf.append(parsedArgs.get(iArg));
if (iArg != (parsedArgs.size() - 1)) {
buf.append(" || ");
}
}
return buf.append(')').toString();
} | java |
public static String sqlinsert(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() != 4) {
throw new PSQLException(GT.tr("{0} function takes four and only four argument.", "insert"),
PSQLState.SYNTAX_ERROR);
}
StringBuilder buf = new StringBuilder();
buf.append("overlay(");
buf.append(parsedArgs.get(0)).append(" placing ").append(parsedArgs.get(3));
buf.append(" from ").append(parsedArgs.get(1)).append(" for ").append(parsedArgs.get(2));
return buf.append(')').toString();
} | java |
public static String sqllocate(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() == 2) {
return "position(" + parsedArgs.get(0) + " in " + parsedArgs.get(1) + ")";
} else if (parsedArgs.size() == 3) {
String tmp = "position(" + parsedArgs.get(0) + " in substring(" + parsedArgs.get(1) + " from "
+ parsedArgs.get(2) + "))";
return "(" + parsedArgs.get(2) + "*sign(" + tmp + ")+" + tmp + ")";
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "locate"),
PSQLState.SYNTAX_ERROR);
}
} | java |
public static String sqlsubstring(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() == 2) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + ")";
} else if (parsedArgs.size() == 3) {
return "substr(" + parsedArgs.get(0) + "," + parsedArgs.get(1) + "," + parsedArgs.get(2)
+ ")";
} else {
throw new PSQLException(GT.tr("{0} function takes two or three arguments.", "substring"),
PSQLState.SYNTAX_ERROR);
}
} | java |
public static String sqlcurdate(List<?> parsedArgs) throws SQLException {
if (!parsedArgs.isEmpty()) {
throw new PSQLException(GT.tr("{0} function doesn''t take any argument.", "curdate"),
PSQLState.SYNTAX_ERROR);
}
return "current_date";
} | java |
public static String sqlmonthname(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() != 1) {
throw new PSQLException(GT.tr("{0} function takes one and only one argument.", "monthname"),
PSQLState.SYNTAX_ERROR);
}
return "to_char(" + parsedArgs.get(0) + ",'Month')";
} | java |
public static String sqltimestampadd(List<?> parsedArgs) throws SQLException {
if (parsedArgs.size() != 3) {
throw new PSQLException(
GT.tr("{0} function takes three and only three arguments.", "timestampadd"),
PSQLState.SYNTAX_ERROR);
}
String interval = EscapedFunctions.constantToInterval(parsedArgs.get(0).toString(),
parsedArgs.get(1).toString());
StringBuilder buf = new StringBuilder();
buf.append("(").append(interval).append("+");
buf.append(parsedArgs.get(2)).append(")");
return buf.toString();
} | java |
public static Method getFunction(String functionName) {
Method method = FUNCTION_MAP.get(functionName);
if (method != null) {
return method;
}
String nameLower = functionName.toLowerCase(Locale.US);
if (nameLower == functionName) {
// Input name was in lower case, the function is not there
return null;
}
method = FUNCTION_MAP.get(nameLower);
if (method != null && FUNCTION_MAP.size() < 1000) {
// Avoid OutOfMemoryError in case input function names are randomized
// The number of methods is finite, however the number of upper-lower case combinations
// is quite a few (e.g. substr, Substr, sUbstr, SUbstr, etc).
FUNCTION_MAP.putIfAbsent(functionName, method);
}
return method;
} | java |
public static void sqlceiling(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "ceil(", "ceiling", parsedArgs);
} | java |
public static void sqllog(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "ln(", "log", parsedArgs);
} | java |
public static void sqllog10(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "log(", "log10", parsedArgs);
} | java |
public static void sqlpower(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
twoArgumentsFunctionCall(buf, "pow(", "power", parsedArgs);
} | java |
public static void sqltruncate(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
twoArgumentsFunctionCall(buf, "trunc(", "truncate", parsedArgs);
} | java |
public static void sqlchar(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "chr(", "char", parsedArgs);
} | java |
public static void sqllcase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "lower(", "lcase", parsedArgs);
} | java |
public static void sqlucase(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
singleArgumentFunctionCall(buf, "upper(", "ucase", parsedArgs);
} | java |
public static void sqlcurdate(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
zeroArgumentFunctionCall(buf, "current_date", "curdate", parsedArgs);
} | java |
public static void sqlcurtime(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
zeroArgumentFunctionCall(buf, "current_time", "curtime", parsedArgs);
} | java |
public static void sqltimestampadd(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
if (parsedArgs.size() != 3) {
throw new PSQLException(
GT.tr("{0} function takes three and only three arguments.", "timestampadd"),
PSQLState.SYNTAX_ERROR);
}
buf.append('(');
appendInterval(buf, parsedArgs.get(0).toString(), parsedArgs.get(1).toString());
buf.append('+').append(parsedArgs.get(2)).append(')');
} | java |
private static boolean areSameTsi(String a, String b) {
return a.length() == b.length() && b.length() > SQL_TSI_ROOT.length()
&& a.regionMatches(true, SQL_TSI_ROOT.length(), b, SQL_TSI_ROOT.length(), b.length() - SQL_TSI_ROOT.length());
} | java |
public static void sqltimestampdiff(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException {
if (parsedArgs.size() != 3) {
throw new PSQLException(
GT.tr("{0} function takes three and only three arguments.", "timestampdiff"),
PSQLState.SYNTAX_ERROR);
}
buf.append("extract( ")
.append(constantToDatePart(buf, parsedArgs.get(0).toString()))
.append(" from (")
.append(parsedArgs.get(2))
.append("-")
.append(parsedArgs.get(1))
.append("))");
} | java |
private void setPGobject(int parameterIndex, PGobject x) throws SQLException {
String typename = x.getType();
int oid = connection.getTypeInfo().getPGType(typename);
if (oid == Oid.UNSPECIFIED) {
throw new PSQLException(GT.tr("Unknown type {0}.", typename),
PSQLState.INVALID_PARAMETER_TYPE);
}
if ((x instanceof PGBinaryObject) && connection.binaryTransferSend(oid)) {
PGBinaryObject binObj = (PGBinaryObject) x;
byte[] data = new byte[binObj.lengthInBytes()];
binObj.toBytes(data, 0);
bindBytes(parameterIndex, data, oid);
} else {
setString(parameterIndex, x.getValue(), oid);
}
} | java |
protected synchronized int convertArrayToBaseOid(int oid) {
Integer i = pgArrayToPgType.get(oid);
if (i == null) {
return oid;
}
return i;
} | java |
public boolean requiresQuotingSqlType(int sqlType) throws SQLException {
switch (sqlType) {
case Types.BIGINT:
case Types.DOUBLE:
case Types.FLOAT:
case Types.INTEGER:
case Types.REAL:
case Types.SMALLINT:
case Types.TINYINT:
case Types.NUMERIC:
case Types.DECIMAL:
return false;
}
return true;
} | java |
public boolean hasMessagePending() throws IOException {
if (pgInput.available() > 0) {
return true;
}
// In certain cases, available returns 0, yet there are bytes
long now = System.currentTimeMillis();
if (now < nextStreamAvailableCheckTime && minStreamAvailableCheckDelay != 0) {
// Do not use ".peek" too often
return false;
}
nextStreamAvailableCheckTime = now + minStreamAvailableCheckDelay;
int soTimeout = getNetworkTimeout();
setNetworkTimeout(1);
try {
return pgInput.peek() != -1;
} catch (SocketTimeoutException e) {
return false;
} finally {
setNetworkTimeout(soTimeout);
}
} | java |
public void setEncoding(Encoding encoding) throws IOException {
if (this.encoding != null && this.encoding.name().equals(encoding.name())) {
return;
}
// Close down any old writer.
if (encodingWriter != null) {
encodingWriter.close();
}
this.encoding = encoding;
// Intercept flush() downcalls from the writer; our caller
// will call PGStream.flush() as needed.
OutputStream interceptor = new FilterOutputStream(pgOutput) {
public void flush() throws IOException {
}
public void close() throws IOException {
super.flush();
}
};
encodingWriter = encoding.getEncodingWriter(interceptor);
} | java |
public void sendInteger4(int val) throws IOException {
int4Buf[0] = (byte) (val >>> 24);
int4Buf[1] = (byte) (val >>> 16);
int4Buf[2] = (byte) (val >>> 8);
int4Buf[3] = (byte) (val);
pgOutput.write(int4Buf);
} | java |
public int receiveInteger4() throws IOException {
if (pgInput.read(int4Buf) != 4) {
throw new EOFException();
}
return (int4Buf[0] & 0xFF) << 24 | (int4Buf[1] & 0xFF) << 16 | (int4Buf[2] & 0xFF) << 8
| int4Buf[3] & 0xFF;
} | java |
public String receiveString(int len) throws IOException {
if (!pgInput.ensureBytes(len)) {
throw new EOFException();
}
String res = encoding.decode(pgInput.getBuffer(), pgInput.getIndex(), len);
pgInput.skip(len);
return res;
} | java |
public EncodingPredictor.DecodeResult receiveErrorString(int len) throws IOException {
if (!pgInput.ensureBytes(len)) {
throw new EOFException();
}
EncodingPredictor.DecodeResult res;
try {
String value = encoding.decode(pgInput.getBuffer(), pgInput.getIndex(), len);
// no autodetect warning as the message was converted on its own
res = new EncodingPredictor.DecodeResult(value, null);
} catch (IOException e) {
res = EncodingPredictor.decode(pgInput.getBuffer(), pgInput.getIndex(), len);
if (res == null) {
Encoding enc = Encoding.defaultEncoding();
String value = enc.decode(pgInput.getBuffer(), pgInput.getIndex(), len);
res = new EncodingPredictor.DecodeResult(value, enc.name());
}
}
pgInput.skip(len);
return res;
} | java |
public String receiveString() throws IOException {
int len = pgInput.scanCStringLength();
String res = encoding.decode(pgInput.getBuffer(), pgInput.getIndex(), len - 1);
pgInput.skip(len);
return res;
} | java |
public byte[][] receiveTupleV3() throws IOException, OutOfMemoryError {
// TODO: use msgSize
int msgSize = receiveInteger4();
int nf = receiveInteger2();
byte[][] answer = new byte[nf][];
OutOfMemoryError oom = null;
for (int i = 0; i < nf; ++i) {
int size = receiveInteger4();
if (size != -1) {
try {
answer[i] = new byte[size];
receive(answer[i], 0, size);
} catch (OutOfMemoryError oome) {
oom = oome;
skip(size);
}
}
}
if (oom != null) {
throw oom;
}
return answer;
} | java |
public void receive(byte[] buf, int off, int siz) throws IOException {
int s = 0;
while (s < siz) {
int w = pgInput.read(buf, off + s, siz - s);
if (w < 0) {
throw new EOFException();
}
s += w;
}
} | java |
public void sendStream(InputStream inStream, int remaining) throws IOException {
int expectedLength = remaining;
if (streamBuffer == null) {
streamBuffer = new byte[8192];
}
while (remaining > 0) {
int count = (remaining > streamBuffer.length ? streamBuffer.length : remaining);
int readCount;
try {
readCount = inStream.read(streamBuffer, 0, count);
if (readCount < 0) {
throw new EOFException(
GT.tr("Premature end of input stream, expected {0} bytes, but only read {1}.",
expectedLength, expectedLength - remaining));
}
} catch (IOException ioe) {
while (remaining > 0) {
send(streamBuffer, count);
remaining -= count;
count = (remaining > streamBuffer.length ? streamBuffer.length : remaining);
}
throw new PGBindException(ioe);
}
send(streamBuffer, readCount);
remaining -= readCount;
}
} | java |
public void receiveEOF() throws SQLException, IOException {
int c = pgInput.read();
if (c < 0) {
return;
}
throw new PSQLException(GT.tr("Expected an EOF from server, got: {0}", c),
PSQLState.COMMUNICATION_ERROR);
} | java |
public static void reportHostStatus(HostSpec hostSpec, HostStatus hostStatus) {
long now = currentTimeMillis();
synchronized (hostStatusMap) {
HostSpecStatus hostSpecStatus = hostStatusMap.get(hostSpec);
if (hostSpecStatus == null) {
hostSpecStatus = new HostSpecStatus(hostSpec);
hostStatusMap.put(hostSpec, hostSpecStatus);
}
hostSpecStatus.status = hostStatus;
hostSpecStatus.lastUpdated = now;
}
} | java |
static List<HostSpec> getCandidateHosts(HostSpec[] hostSpecs,
HostRequirement targetServerType, long hostRecheckMillis) {
List<HostSpec> candidates = new ArrayList<HostSpec>(hostSpecs.length);
long latestAllowedUpdate = currentTimeMillis() - hostRecheckMillis;
synchronized (hostStatusMap) {
for (HostSpec hostSpec : hostSpecs) {
HostSpecStatus hostInfo = hostStatusMap.get(hostSpec);
// candidates are nodes we do not know about and the nodes with correct type
if (hostInfo == null
|| hostInfo.lastUpdated < latestAllowedUpdate
|| targetServerType.allowConnectingTo(hostInfo.status)) {
candidates.add(hostSpec);
}
}
}
return candidates;
} | java |
@Override
public boolean isSSPISupported() {
try {
/*
* SSPI is windows-only. Attempt to use JNA to identify the platform. If Waffle is missing we
* won't have JNA and this will throw a NoClassDefFoundError.
*/
if (!Platform.isWindows()) {
LOGGER.log(Level.FINE, "SSPI not supported: non-Windows host");
return false;
}
/* Waffle must be on the CLASSPATH */
Class.forName("waffle.windows.auth.impl.WindowsSecurityContextImpl");
return true;
} catch (NoClassDefFoundError ex) {
LOGGER.log(Level.WARNING, "SSPI unavailable (no Waffle/JNA libraries?)", ex);
return false;
} catch (ClassNotFoundException ex) {
LOGGER.log(Level.WARNING, "SSPI unavailable (no Waffle/JNA libraries?)", ex);
return false;
}
} | java |
@Override
public void continueSSPI(int msgLength) throws SQLException, IOException {
if (sspiContext == null) {
throw new IllegalStateException("Cannot continue SSPI authentication that we didn't begin");
}
LOGGER.log(Level.FINEST, "Continuing SSPI negotiation");
/* Read the response token from the server */
byte[] receivedToken = pgStream.receive(msgLength);
SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, receivedToken);
sspiContext.initialize(sspiContext.getHandle(), continueToken, targetName);
/*
* Now send the response token. If negotiation is complete there may be zero bytes to send, in
* which case we shouldn't send a reply as the server is not expecting one; see fe-auth.c in
* libpq for details.
*/
byte[] responseToken = sspiContext.getToken();
if (responseToken.length > 0) {
sendSSPIResponse(responseToken);
LOGGER.log(Level.FINEST, "Sent SSPI negotiation continuation message");
} else {
LOGGER.log(Level.FINEST, "SSPI authentication complete, no reply required");
}
} | java |
@Override
public void dispose() {
if (sspiContext != null) {
sspiContext.dispose();
sspiContext = null;
}
if (clientCredentials != null) {
clientCredentials.dispose();
clientCredentials = null;
}
} | java |
public Connection getConnection(String user, String password) throws SQLException {
try {
Connection con = DriverManager.getConnection(getUrl(), user, password);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE, "Created a {0} for {1} at {2}",
new Object[] {getDescription(), user, getUrl()});
}
return con;
} catch (SQLException e) {
LOGGER.log(Level.FINE, "Failed to create a {0} for {1} at {2}: {3}",
new Object[] {getDescription(), user, getUrl(), e});
throw e;
}
} | java |
public void toBytes(byte[] b, int offset) {
ByteConverter.float8(b, offset, x);
ByteConverter.float8(b, offset + 8, y);
} | java |
@Deprecated
public static boolean verifyHostName(String hostname, String pattern) {
String canonicalHostname;
if (hostname.startsWith("[") && hostname.endsWith("]")) {
// IPv6 address like [2001:db8:0:1:1:1:1:1]
canonicalHostname = hostname.substring(1, hostname.length() - 1);
} else {
// This converts unicode domain name to ASCII
try {
canonicalHostname = IDN.toASCII(hostname);
} catch (IllegalArgumentException e) {
// e.g. hostname is invalid
return false;
}
}
return PGjdbcHostnameVerifier.INSTANCE.verifyHostName(canonicalHostname, pattern);
} | java |
public String getValue() {
StringBuilder b = new StringBuilder(open ? "[" : "(");
for (int p = 0; p < points.length; p++) {
if (p > 0) {
b.append(",");
}
b.append(points[p].toString());
}
b.append(open ? "]" : ")");
return b.toString();
} | java |
public static boolean parseDeleteKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'd'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'e'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | java |
public static boolean parseInsertKeyword(final char[] query, int offset) {
if (query.length < (offset + 7)) {
return false;
}
return (query[offset] | 32) == 'i'
&& (query[offset + 1] | 32) == 'n'
&& (query[offset + 2] | 32) == 's'
&& (query[offset + 3] | 32) == 'e'
&& (query[offset + 4] | 32) == 'r'
&& (query[offset + 5] | 32) == 't';
} | java |
public static boolean parseMoveKeyword(final char[] query, int offset) {
if (query.length < (offset + 4)) {
return false;
}
return (query[offset] | 32) == 'm'
&& (query[offset + 1] | 32) == 'o'
&& (query[offset + 2] | 32) == 'v'
&& (query[offset + 3] | 32) == 'e';
} | java |
public static boolean parseReturningKeyword(final char[] query, int offset) {
if (query.length < (offset + 9)) {
return false;
}
return (query[offset] | 32) == 'r'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'r'
&& (query[offset + 5] | 32) == 'n'
&& (query[offset + 6] | 32) == 'i'
&& (query[offset + 7] | 32) == 'n'
&& (query[offset + 8] | 32) == 'g';
} | java |
public static boolean parseSelectKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 's'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'e'
&& (query[offset + 4] | 32) == 'c'
&& (query[offset + 5] | 32) == 't';
} | java |
public static boolean parseUpdateKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'u'
&& (query[offset + 1] | 32) == 'p'
&& (query[offset + 2] | 32) == 'd'
&& (query[offset + 3] | 32) == 'a'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | java |
public static boolean parseValuesKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'v'
&& (query[offset + 1] | 32) == 'a'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'u'
&& (query[offset + 4] | 32) == 'e'
&& (query[offset + 5] | 32) == 's';
} | java |
public static boolean parseWithKeyword(final char[] query, int offset) {
if (query.length < (offset + 4)) {
return false;
}
return (query[offset] | 32) == 'w'
&& (query[offset + 1] | 32) == 'i'
&& (query[offset + 2] | 32) == 't'
&& (query[offset + 3] | 32) == 'h';
} | java |
public static boolean parseAsKeyword(final char[] query, int offset) {
if (query.length < (offset + 2)) {
return false;
}
return (query[offset] | 32) == 'a'
&& (query[offset + 1] | 32) == 's';
} | java |
private static boolean subArraysEqual(final char[] arr,
final int offA, final int offB,
final int len) {
if (offA < 0 || offB < 0
|| offA >= arr.length || offB >= arr.length
|| offA + len > arr.length || offB + len > arr.length) {
return false;
}
for (int i = 0; i < len; ++i) {
if (arr[offA + i] != arr[offB + i]) {
return false;
}
}
return true;
} | java |
private static int escapeFunctionArguments(StringBuilder newsql, String functionName, char[] sql, int i,
boolean stdStrings)
throws SQLException {
// Maximum arity of functions in EscapedFunctions is 3
List<CharSequence> parsedArgs = new ArrayList<CharSequence>(3);
while (true) {
StringBuilder arg = new StringBuilder();
int lastPos = i;
i = parseSql(sql, i, arg, true, stdStrings);
if (i != lastPos) {
parsedArgs.add(arg);
}
if (i >= sql.length // should not happen
|| sql[i] != ',') {
break;
}
i++;
}
Method method = EscapedFunctions2.getFunction(functionName);
if (method == null) {
newsql.append(functionName);
EscapedFunctions2.appendCall(newsql, "(", ",", ")", parsedArgs);
return i;
}
try {
method.invoke(null, newsql, parsedArgs);
} catch (InvocationTargetException e) {
Throwable targetException = e.getTargetException();
if (targetException instanceof SQLException) {
throw (SQLException) targetException;
} else {
throw new PSQLException(targetException.getMessage(), PSQLState.SYSTEM_ERROR);
}
} catch (IllegalAccessException e) {
throw new PSQLException(e.getMessage(), PSQLState.SYSTEM_ERROR);
}
return i;
} | java |
@Override
public Connection getConnection() throws SQLException {
Connection conn = super.getConnection();
// When we're outside an XA transaction, autocommit
// is supposed to be true, per usual JDBC convention.
// When an XA transaction is in progress, it should be
// false.
if (state == State.IDLE) {
conn.setAutoCommit(true);
}
/*
* Wrap the connection in a proxy to forbid application from fiddling with transaction state
* directly during an XA transaction
*/
ConnectionHandler handler = new ConnectionHandler(conn);
return (Connection) Proxy.newProxyInstance(getClass().getClassLoader(),
new Class[]{Connection.class, PGConnection.class}, handler);
} | java |
@Override
public void forget(Xid xid) throws XAException {
throw new PGXAException(GT.tr("Heuristic commit/rollback not supported. forget xid={0}", xid),
XAException.XAER_NOTA);
} | java |
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void detach(Activity activity, ViewTreeObserver.OnGlobalLayoutListener l) {
ViewGroup contentView = activity.findViewById(android.R.id.content);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
contentView.getViewTreeObserver().removeOnGlobalLayoutListener(l);
} else {
//noinspection deprecation
contentView.getViewTreeObserver().removeGlobalOnLayoutListener(l);
}
} | java |
public void onClickExtraThemeResolved(final View view) {
final boolean fullScreenTheme = mFullScreenRb.isChecked();
Intent i = new Intent(this, ChattingResolvedHandleByPlaceholderActivity.class);
i.putExtra(KEY_FULL_SCREEN_THEME, fullScreenTheme);
startActivity(i);
} | java |
public static void hidePanelAndKeyboard(final View panelLayout) {
final Activity activity = (Activity) panelLayout.getContext();
final View focusView = activity.getCurrentFocus();
if (focusView != null) {
KeyboardUtil.hideKeyboard(activity.getCurrentFocus());
focusView.clearFocus();
}
panelLayout.setVisibility(View.GONE);
} | java |
public static Typeface getTypeface(Context context, IconSet iconSet) {
String path = iconSet.fontPath().toString();
if (TYPEFACE_MAP.get(path) == null) {
final Typeface font = Typeface.createFromAsset(context.getAssets(), path);
TYPEFACE_MAP.put(path, font);
}
return TYPEFACE_MAP.get(path);
} | java |
public static void registerDefaultIconSets() {
final FontAwesome fontAwesome = new FontAwesome();
final Typicon typicon = new Typicon();
final MaterialIcons materialIcons = new MaterialIcons();
REGISTERED_ICON_SETS.put(fontAwesome.fontPath(), fontAwesome);
REGISTERED_ICON_SETS.put(typicon.fontPath(), typicon);
REGISTERED_ICON_SETS.put(materialIcons.fontPath(), materialIcons);
} | java |
public static IconSet retrieveRegisteredIconSet(String fontPath, boolean editMode) {
final IconSet iconSet = REGISTERED_ICON_SETS.get(fontPath);
if (iconSet == null && !editMode) {
throw new RuntimeException(String.format("Font '%s' not properly registered, please" +
" see the README at https://github.com/Bearded-Hen/Android-Bootstrap", fontPath));
}
return iconSet;
} | java |
void onRadioToggle(int index) {
for (int i = 0; i < getChildCount(); i++) {
if (i != index) {
BootstrapButton b = retrieveButtonChild(i);
b.setSelected(false);
}
}
} | java |
public void startFlashing(boolean forever, AnimationSpeed speed) {
Animation fadeIn = new AlphaAnimation(0, 1);
//set up extra variables
fadeIn.setDuration(50);
fadeIn.setRepeatMode(Animation.REVERSE);
//default repeat count is 0, however if user wants, set it up to be infinite
fadeIn.setRepeatCount(0);
if (forever) {
fadeIn.setRepeatCount(Animation.INFINITE);
}
fadeIn.setStartOffset(speed.getFlashDuration());
startAnimation(fadeIn);
} | java |
public void startRotate(boolean clockwise, AnimationSpeed speed) {
Animation rotate;
//set up the rotation animation
if (clockwise) {
rotate = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
}
else {
rotate = new RotateAnimation(360, 0, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
}
//set up some extra variables
rotate.setRepeatCount(Animation.INFINITE);
rotate.setInterpolator(new LinearInterpolator());
rotate.setStartOffset(0);
rotate.setRepeatMode(Animation.RESTART);
rotate.setDuration(speed.getRotateDuration());
startAnimation(rotate);
} | java |
private static IconSet resolveIconSet(String iconCode) {
CharSequence unicode;
for (IconSet set : getRegisteredIconSets()) {
if (set.fontPath().equals(FontAwesome.FONT_PATH) || set.fontPath().equals(Typicon.FONT_PATH) || set.fontPath().equals(MaterialIcons.FONT_PATH)) {
continue; // already checked previously, ignore
}
unicode = set.unicodeForKey(iconCode);
if (unicode != null) {
return set;
}
}
String message = String.format("Could not find FontIcon value for '%s', " +
"please ensure that it is mapped to a valid font", iconCode);
throw new IllegalArgumentException(message);
} | java |
private float measureStringWidth(String text) {
Paint mPaint = new Paint();
mPaint.setTextSize(baselineDropDownViewFontSize * bootstrapSize);
return (float) (DimenUtils.dpToPixels(mPaint.measureText(text)));
} | java |
private String getLongestString(String[] array) {
int maxLength = 0;
String longestString = null;
for (String s : array) {
if (s.length() > maxLength) {
maxLength = s.length();
longestString = s;
}
}
return longestString;
} | java |
private void addEmptyProgressBar(){
int whereIsEmpty = -1;
for (int i = 0; i < getChildCount(); i++) {
if (retrieveChild(i) != null && retrieveChild(i).equals(emptyProgressBar)) {
whereIsEmpty = i;
}
}
if (whereIsEmpty != getChildCount() - 1) {
if (whereIsEmpty != -1) {
//the flowing true/false is to stop empty progressbar being added more than once as removeView and addView indirectly call this method
isEmptyBeingAdded = true;
removeView(emptyProgressBar);
isEmptyBeingAdded = false;
}
if (!isEmptyBeingAdded) {
addView(emptyProgressBar);
}
}
} | java |
public int getCumulativeProgress(){
int numChildren = getChildCount();
int total = 0;
for (int i = 0; i < numChildren; i++) {
total += getChildProgress(i);
}
checkCumulativeSmallerThanMax(maxProgress, total);
return total;
} | java |
@Override
public void setStriped(boolean striped) {
this.striped = striped;
for (int i = 0; i < getChildCount(); i++) {
retrieveChild(i).setStriped(striped);
}
} | java |
static Drawable bootstrapButton(Context context,
BootstrapBrand brand,
int strokeWidth,
int cornerRadius,
ViewGroupPosition position,
boolean showOutline,
boolean rounded) {
GradientDrawable defaultGd = new GradientDrawable();
GradientDrawable activeGd = new GradientDrawable();
GradientDrawable disabledGd = new GradientDrawable();
defaultGd.setColor(showOutline ? Color.TRANSPARENT : brand.defaultFill(context));
activeGd.setColor(showOutline ? brand.activeFill(context) : brand.activeFill(context));
disabledGd.setColor(showOutline ? Color.TRANSPARENT : brand.disabledFill(context));
defaultGd.setStroke(strokeWidth, brand.defaultEdge(context));
activeGd.setStroke(strokeWidth, brand.activeEdge(context));
disabledGd.setStroke(strokeWidth, brand.disabledEdge(context));
if (showOutline && brand instanceof DefaultBootstrapBrand) {
DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand;
if (db == DefaultBootstrapBrand.SECONDARY) {
int color = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context);
defaultGd.setStroke(strokeWidth, color);
activeGd.setStroke(strokeWidth, color);
disabledGd.setStroke(strokeWidth, color);
}
}
setupDrawableCorners(position, rounded, cornerRadius, defaultGd, activeGd, disabledGd);
return setupStateDrawable(position, strokeWidth, defaultGd, activeGd, disabledGd);
} | java |
static Drawable bootstrapLabel(Context context,
BootstrapBrand bootstrapBrand,
boolean rounded,
float height) {
int cornerRadius = (int) DimenUtils.pixelsFromDpResource(context, R.dimen.bootstrap_default_corner_radius);
GradientDrawable drawable = new GradientDrawable();
drawable.setColor(bootstrapBrand.defaultFill(context));
// corner radius should be half height if rounded as a "Pill" label
drawable.setCornerRadius(rounded ? height / 2 : cornerRadius);
return drawable;
} | java |
static Drawable bootstrapEditText(Context context,
BootstrapBrand bootstrapBrand,
float strokeWidth,
float cornerRadius,
boolean rounded) {
StateListDrawable drawable = new StateListDrawable();
GradientDrawable activeDrawable = new GradientDrawable();
GradientDrawable disabledDrawable = new GradientDrawable();
GradientDrawable defaultDrawable = new GradientDrawable();
activeDrawable.setColor(ColorUtils.resolveColor(android.R.color.white, context));
disabledDrawable.setColor(ColorUtils.resolveColor(android.R.color.white, context));
defaultDrawable.setColor(ColorUtils.resolveColor(android.R.color.white, context));
if (rounded) {
activeDrawable.setCornerRadius(cornerRadius);
disabledDrawable.setCornerRadius(cornerRadius);
defaultDrawable.setCornerRadius(cornerRadius);
}
// stroke is larger when focused
int defaultBorder = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context);
int disabledBorder = ColorUtils.resolveColor(R.color.bootstrap_edittext_disabled, context);
activeDrawable.setStroke((int) strokeWidth, bootstrapBrand.defaultEdge(context));
disabledDrawable.setStroke((int) strokeWidth, disabledBorder);
defaultDrawable.setStroke((int) strokeWidth, defaultBorder);
drawable.addState(new int[]{android.R.attr.state_focused}, activeDrawable);
drawable.addState(new int[]{-android.R.attr.state_enabled}, disabledDrawable);
drawable.addState(new int[]{}, defaultDrawable);
return drawable;
} | java |
static ColorStateList bootstrapButtonText(Context context, boolean outline, BootstrapBrand brand) {
int defaultColor = outline ? brand.defaultFill(context) : brand.defaultTextColor(context);
int activeColor = outline ? ColorUtils.resolveColor(android.R.color.white, context) : brand.activeTextColor(context);
int disabledColor = outline ? brand.disabledFill(context) : brand.disabledTextColor(context);
if (outline && brand instanceof DefaultBootstrapBrand) { // special case
DefaultBootstrapBrand db = (DefaultBootstrapBrand) brand;
if (db == DefaultBootstrapBrand.SECONDARY) {
defaultColor = ColorUtils.resolveColor(R.color.bootstrap_brand_secondary_border, context);
disabledColor = defaultColor;
}
}
return new ColorStateList(getStateList(), getColorList(defaultColor, activeColor, disabledColor));
} | java |
private static Drawable createArrowIcon(Context context, int width, int height, int color, ExpandDirection expandDirection) {
Bitmap canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(1);
paint.setColor(color);
paint.setAntiAlias(true);
Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
switch (expandDirection) {
case UP:
path.moveTo(0, (height / 3) * 2);
path.lineTo(width, (height / 3) * 2);
path.lineTo(width / 2, height / 3);
path.lineTo(0, (height / 3) * 2);
break;
case DOWN:
path.moveTo(0, height / 3);
path.lineTo(width, height / 3);
path.lineTo(width / 2, (height / 3) * 2);
path.lineTo(0, height / 3);
break;
}
path.close();
canvas.drawPath(path, paint);
return new BitmapDrawable(context.getResources(), canvasBitmap);
} | java |
private void startStripedAnimationIfNeeded() {
if (!striped || !animated) {
return;
}
clearAnimation();
progressAnimator = ValueAnimator.ofFloat(0, 0);
progressAnimator.setDuration(UPDATE_ANIM_MS);
progressAnimator.setRepeatCount(ValueAnimator.INFINITE);
progressAnimator.setRepeatMode(ValueAnimator.RESTART);
progressAnimator.setInterpolator(new LinearInterpolator());
progressAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
invalidate();
}
});
progressAnimator.start();
} | java |
private static Bitmap createTile(float h, Paint stripePaint, Paint progressPaint) {
Bitmap bm = Bitmap.createBitmap((int) h * 2, (int) h, ARGB_8888);
Canvas tile = new Canvas(bm);
float x = 0;
Path path = new Path();
path.moveTo(x, 0);
path.lineTo(x, h);
path.lineTo(h, h);
tile.drawPath(path, stripePaint); // draw striped triangle
path.reset();
path.moveTo(x, 0);
path.lineTo(x + h, h);
path.lineTo(x + (h * 2), h);
path.lineTo(x + h, 0);
tile.drawPath(path, progressPaint); // draw progress parallelogram
x += h;
path.reset();
path.moveTo(x, 0);
path.lineTo(x + h, 0);
path.lineTo(x + h, h);
tile.drawPath(path, stripePaint); // draw striped triangle (completing tile)
return bm;
} | java |
public void setMaxProgress(int newMaxProgress) {
if (getProgress() <= newMaxProgress) {
maxProgress = newMaxProgress;
}
else {
throw new IllegalArgumentException(
String.format("MaxProgress cant be smaller than the current progress %d<%d", getProgress(), newMaxProgress));
}
invalidate();
BootstrapProgressBarGroup parent = (BootstrapProgressBarGroup) getParent();
} | java |
@Override
protected Class<?>[] getHandlerInterfaces(String serviceName) {
Class<?> remoteInterface = interfaceMap.get(serviceName);
if (remoteInterface != null) {
return new Class<?>[]{remoteInterface};
} else if (Proxy.isProxyClass(getHandler(serviceName).getClass())) {
return getHandler(serviceName).getClass().getInterfaces();
} else {
return new Class<?>[]{getHandler(serviceName).getClass()};
}
} | java |
@Override
protected String getServiceName(final String methodName) {
if (methodName != null) {
int ndx = methodName.indexOf(this.separator);
if (ndx > 0) {
return methodName.substring(0, ndx);
}
}
return methodName;
} | java |
public void handle(ResourceRequest request, ResourceResponse response) throws IOException {
logger.debug("Handing ResourceRequest {}", request.getMethod());
response.setContentType(contentType);
InputStream input = getRequestStream(request);
OutputStream output = response.getPortletOutputStream();
handleRequest(input, output);
// fix to not flush within handleRequest() but outside so http status code can be set
output.flush();
} | java |
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
logger.debug("Handling HttpServletRequest {}", request);
response.setContentType(contentType);
OutputStream output = response.getOutputStream();
InputStream input = getRequestStream(request);
int result = ErrorResolver.JsonError.PARSE_ERROR.code;
int contentLength = 0;
ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
try {
String acceptEncoding = request.getHeader(ACCEPT_ENCODING);
result = handleRequest0(input, output, acceptEncoding, response, byteOutput);
contentLength = byteOutput.size();
} catch (Throwable t) {
if (StreamEndedException.class.isInstance(t)) {
logger.debug("Bad request: empty contents!");
} else {
logger.error(t.getMessage(), t);
}
}
int httpStatusCode = httpStatusCodeProvider == null ? DefaultHttpStatusCodeProvider.INSTANCE.getHttpStatusCode(result)
: httpStatusCodeProvider.getHttpStatusCode(result);
response.setStatus(httpStatusCode);
response.setContentLength(contentLength);
byteOutput.writeTo(output);
output.flush();
} | java |
public void stop() throws InterruptedException {
if (!isStarted.get()) {
throw new IllegalStateException("The StreamServer is not started");
}
stopServer();
stopClients();
closeSocket();
try {
waitForServerToTerminate();
isStarted.set(false);
stopServer();
} catch (InterruptedException e) {
logger.error("InterruptedException while waiting for termination", e);
throw e;
}
} | java |
private void closeQuietly(Closeable c) {
if (c != null) {
try {
c.close();
} catch (Throwable t) {
logger.warn("Error closing, ignoring", t);
}
}
} | java |
protected Class<?>[] getHandlerInterfaces(final String serviceName) {
if (remoteInterface != null) {
return new Class<?>[]{remoteInterface};
} else if (Proxy.isProxyClass(handler.getClass())) {
return handler.getClass().getInterfaces();
} else {
return new Class<?>[]{handler.getClass()};
}
} | java |
private ErrorObjectWithJsonError createResponseError(String jsonRpc, Object id, JsonError errorObject) {
ObjectNode response = mapper.createObjectNode();
ObjectNode error = mapper.createObjectNode();
error.put(ERROR_CODE, errorObject.code);
error.put(ERROR_MESSAGE, errorObject.message);
if (errorObject.data != null) {
error.set(DATA, mapper.valueToTree(errorObject.data));
}
response.put(JSONRPC, jsonRpc);
if (Integer.class.isInstance(id)) {
response.put(ID, Integer.class.cast(id).intValue());
} else if (Long.class.isInstance(id)) {
response.put(ID, Long.class.cast(id).longValue());
} else if (Float.class.isInstance(id)) {
response.put(ID, Float.class.cast(id).floatValue());
} else if (Double.class.isInstance(id)) {
response.put(ID, Double.class.cast(id).doubleValue());
} else if (BigDecimal.class.isInstance(id)) {
response.put(ID, BigDecimal.class.cast(id));
} else {
response.put(ID, String.class.cast(id));
}
response.set(ERROR, error);
return new ErrorObjectWithJsonError(response, errorObject);
} | java |
private ObjectNode createResponseSuccess(String jsonRpc, Object id, JsonNode result) {
ObjectNode response = mapper.createObjectNode();
response.put(JSONRPC, jsonRpc);
if (Integer.class.isInstance(id)) {
response.put(ID, Integer.class.cast(id).intValue());
} else if (Long.class.isInstance(id)) {
response.put(ID, Long.class.cast(id).longValue());
} else if (Float.class.isInstance(id)) {
response.put(ID, Float.class.cast(id).floatValue());
} else if (Double.class.isInstance(id)) {
response.put(ID, Double.class.cast(id).doubleValue());
} else if (BigDecimal.class.isInstance(id)) {
response.put(ID, BigDecimal.class.cast(id));
} else {
response.put(ID, String.class.cast(id));
}
response.set(RESULT, result);
return response;
} | java |
private void initRestTemplate() {
boolean isContainsConverter = false;
for (HttpMessageConverter<?> httpMessageConverter : this.restTemplate.getMessageConverters()) {
if (MappingJacksonRPC2HttpMessageConverter.class.isAssignableFrom(httpMessageConverter.getClass())) {
isContainsConverter = true;
break;
}
}
if (!isContainsConverter) {
final MappingJacksonRPC2HttpMessageConverter messageConverter = new MappingJacksonRPC2HttpMessageConverter();
messageConverter.setObjectMapper(this.getObjectMapper());
final List<HttpMessageConverter<?>> restMessageConverters = new ArrayList<>();
restMessageConverters.addAll(this.restTemplate.getMessageConverters());
// Place JSON-RPC converter on the first place!
restMessageConverters.add(0, messageConverter);
this.restTemplate.setMessageConverters(restMessageConverters);
}
// use specific JSON-RPC error handler if it has not been changed to custom
if (restTemplate.getErrorHandler() instanceof org.springframework.web.client.DefaultResponseErrorHandler) {
restTemplate.setErrorHandler(JsonRpcResponseErrorHandler.INSTANCE);
}
} | java |
private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
// create URLConnection
HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
connection.setConnectTimeout(connectionTimeoutMillis);
connection.setReadTimeout(readTimeoutMillis);
connection.setAllowUserInteraction(false);
connection.setDefaultUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
setupSsl(connection);
addHeaders(extraHeaders, connection);
return connection;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.