code stringlengths 73 34.1k | label stringclasses 1
value |
|---|---|
public static String getPrefixedKeyString(Query query, Result result, List<String> typeNames) {
StringBuilder sb = new StringBuilder();
addTypeName(query, result, typeNames, sb);
addKeyString(query, result, sb);
return sb.toString();
} | java |
private static void addMBeanIdentifier(Query query, Result result, StringBuilder sb) {
if (result.getKeyAlias() != null) {
sb.append(result.getKeyAlias());
} else if (query.isUseObjDomainAsKey()) {
sb.append(StringUtils.cleanupStr(result.getObjDomain(), query.isAllowDottedKeys()));
} else {
sb.append(Str... | java |
@Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Determine the spoofed hostname
spoofedHostName = getSpoofedHostName(server.getHost(), server.getAlias());
log.debug("Validated Ganglia metric [" +
HOST + ": " + host + ", " +
PORT + ": " + port + ", " +
A... | java |
@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
for (final Result result : results) {
final String name = KeyUtils.getKeyString(query, result, getTypeNames());
Object transformedValue = valueTransformer.apply(result.getValue());
GMetricType... | java |
private static GMetricType getType(final Object obj) {
// FIXME This is far from covering all cases.
// FIXME Wasteful use of high capacity types (eg Short => INT32)
// Direct mapping when possible
if (obj instanceof Long || obj instanceof Integer || obj instanceof Byte || obj instanceof Short)
return GMet... | java |
public static Boolean getBooleanSetting(Map<String, Object> settings, String key, Boolean defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
if (value instanceof String) {
return Boolean.valueOf(... | java |
public static Integer getIntegerSetting(Map<String, Object> settings, String key, Integer defaultVal) {
final Object value = settings.get(key);
if (value == null) {
return defaultVal;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
if (value instanceof String) {
try {
re... | java |
public static String getStringSetting(Map<String, Object> settings, String key, String defaultVal) {
final Object value = settings.get(key);
return value != null ? value.toString() : defaultVal;
} | java |
protected static int getIntSetting(Map<String, Object> settings, String key, int defaultVal) throws IllegalArgumentException {
if (settings.containsKey(key)) {
final Object objectValue = settings.get(key);
if (objectValue == null) {
throw new IllegalArgumentException("Setting '" + key + " null");
}
fi... | java |
protected VelocityEngine getVelocityEngine(List<String> paths) {
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
ve.setProperty("cp.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
ve.setProperty("cp.resource.loader.ca... | java |
public JmxProcess parseProcess(File file) throws IOException {
String fileName = file.getName();
ObjectMapper mapper = fileName.endsWith(".yml") || fileName.endsWith(".yaml") ? yamlMapper : jsonMapper;
JsonNode jsonNode = mapper.readTree(file);
JmxProcess jmx = mapper.treeToValue(jsonNode, JmxProcess.class);
... | java |
void addTags(StringBuilder resultString, Server server) {
if (hostnameTag) {
addTag(resultString, "host", server.getLabel());
}
// Add the constant tag names and values.
for (Map.Entry<String, String> tagEntry : tags.entrySet()) {
addTag(resultString, tagEntry.getKey(), tagEntry.getValue());
}
} | java |
void addTag(StringBuilder resultString, String tagName, String tagValue) {
resultString.append(" ");
resultString.append(sanitizeString(tagName));
resultString.append("=");
resultString.append(sanitizeString(tagValue));
} | java |
private void formatResultString(StringBuilder resultString, String metricName, long epoch, Object value) {
resultString.append(sanitizeString(metricName));
resultString.append(" ");
resultString.append(Long.toString(epoch));
resultString.append(" ");
resultString.append(sanitizeString(value.toString()));
} | java |
protected void processOneMetric(List<String> resultStrings, Server server, Result result, Object value, String addTagName,
String addTagValue) {
String metricName = this.metricNameStrategy.formatName(result);
//
// Skip any non-numeric values since OpenTSDB only supports numeric metrics.
//
if (isNu... | java |
private String getGatewayMessage(final List<Result> results) throws IOException {
int valueCount = 0;
Writer writer = new StringWriter();
JsonGenerator g = jsonFactory.createGenerator(writer);
g.writeStartObject();
g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
g.writeNumberField("proto... | java |
private void doSend(final String gatewayMessage) {
HttpURLConnection urlConnection = null;
try {
if (proxy == null) {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection();
} else {
urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy);
}
urlConnection.setRequestMethod(... | java |
private void doMain() throws Exception {
// Start the process
this.start();
while (true) {
// look for some terminator
// attempt to read off queue
// process message
// TODO : Make something here, maybe watch for files?
try {
Thread.sleep(5);
} catch (Exception e) {
log.info("shutting ... | java |
private void stopWriterAndClearMasterServerList() {
for (Server server : this.masterServersList) {
for (OutputWriter writer : server.getOutputWriters()) {
try {
writer.close();
} catch (LifecycleException ex) {
log.error("Eror stopping writer: {}", writer);
}
}
for (Query query : server... | java |
private void startupWatchdir() throws Exception {
File dirToWatch;
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
dirToWatch = new File(FilenameUtils.getFullPath(this.configuration.getProcessConfigDirOrFile().getAbsolutePath()));
} else {
dirToWatch = this.configuration.getProcessConfigDirOr... | java |
public void executeStandalone(JmxProcess process) throws Exception {
this.masterServersList = process.getServers();
this.serverScheduler.start();
this.processServersIntoJobs();
// Sleep for 10 seconds to wait for jobs to complete.
// There should be a better way, but it seems that way isn't working
// ri... | java |
private void processFilesIntoServers() throws LifecycleException {
// Shutdown the outputwriters and clear the current server list - this gives us a clean
// start when re-reading the json config files
try {
this.stopWriterAndClearMasterServerList();
} catch (Exception e) {
log.error("Error while clearing... | java |
private boolean isProcessConfigFile(File file) {
if (this.configuration.getProcessConfigDirOrFile().isFile()) {
return file.equals(this.configuration.getProcessConfigDirOrFile());
}
// If the file doesn't exist anymore, treat it as a regular file (to handle file deletion events)
if(file.exists() && !file.is... | java |
@Override
@JsonIgnore
public JMXConnector getServerConnection() throws IOException {
JMXServiceURL url = getJmxServiceURL();
return JMXConnectorFactory.connect(url, this.getEnvironment());
} | java |
@Override
public void validateSetup(Server server, Query query) throws ValidationException {
// Check if we've already created a logger for this file. If so, use it.
Logger logger;
if (loggers.containsKey(outputFile)) {
logger = getLogger(outputFile);
}else{
// need to create a logger
try {
logger... | java |
@Override
public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
graphiteWriter.write(logwriter, server, query, results);
} | java |
private AmazonCloudWatchClient createCloudWatchClient() {
AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(new InstanceProfileCredentialsProvider());
cloudWatchClient.setRegion(checkNotNull(Regions.getCurrentRegion(), "Problems getting AWS metadata"));
return cloudWatchClient;
} | java |
@Override
public String formatName(Result result) {
String formatted;
JexlContext context = new MapContext();
this.populateContext(context, result);
try {
formatted = (String) this.parsedExpr.evaluate(context);
} catch (JexlException jexlExc) {
LOG.error("error applying JEXL expression to query result... | java |
protected void populateContext(JexlContext context, Result result) {
context.set(VAR_CLASSNAME, result.getClassName());
context.set(VAR_ATTRIBUTE_NAME, result.getAttributeName());
context.set(VAR_CLASSNAME_ALIAS, result.getKeyAlias());
Map<String, String> typeNameMap = TypeNameValue.extractMap(result.getTypeNa... | java |
public String getDataSourceName(String typeName, String attributeName, List<String> valuePath) {
String result;
String entry = StringUtils.join(valuePath, '.');
if (typeName != null) {
result = typeName + attributeName + entry;
} else {
result = attributeName + entry;
}
if (attributeName.length() > 1... | java |
protected void rrdToolUpdate(String template, String data) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(binaryPath + "/rrdtool");
commands.add("update");
commands.add(outputFile.getCanonicalPath());
commands.add("-t");
commands.add(template);
commands.add("N:" + data);
Pro... | java |
protected void rrdToolCreateDatabase(RrdDef def) throws Exception {
List<String> commands = new ArrayList<>();
commands.add(this.binaryPath + "/rrdtool");
commands.add("create");
commands.add(this.outputFile.getCanonicalPath());
commands.add("-s");
commands.add(String.valueOf(def.getStep()));
for (DsDef ... | java |
private void checkErrorStream(Process process) throws Exception {
// rrdtool should use platform encoding (unless you did something
// very strange with your installation of rrdtool). So let's be
// explicit and use the presumed correct encoding to read errors.
try (
InputStream is = process.getErrorStream(... | java |
private String getRraStr(ArcDef def) {
return "RRA:" + def.getConsolFun() + ":" + def.getXff() + ":" + def.getSteps() + ":" + def.getRows();
} | java |
private List<String> getDsNames(DsDef[] defs) {
List<String> names = new ArrayList<>();
for (DsDef def : defs) {
names.add(def.getDsName());
}
return names;
} | java |
public void add(URL url) {
URLClassLoader sysLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
Class sysClass = URLClassLoader.class;
try {
Method method = sysClass.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(sysLoader, new Object[]{ url });
} catch (I... | java |
private static void describeClassTree(Class<?> inputClass, Set<Class<?>> setOfClasses) {
// can't map null class
if(inputClass == null) {
return;
}
// don't further analyze a class that has been analyzed already
if(Object.class.equals(inputClass) || setOfClasses.contains(inputClass)) {
... | java |
private static Set<Class<?>> describeClassTree(Class<?> inputClass) {
if(inputClass == null) {
return Collections.emptySet();
}
// create result collector
Set<Class<?>> classes = Sets.newLinkedHashSet();
// describe tree
describeClassTree(inputClass, classes);
return classes;
} | java |
public void usage(StringBuilder out, String indent) {
if (commander.getDescriptions() == null) {
commander.createDescriptions();
}
boolean hasCommands = !commander.getCommands().isEmpty();
boolean hasOptions = !commander.getDescriptions().isEmpty();
// Indentation co... | java |
@SuppressWarnings("deprecation")
private ResourceBundle findResourceBundle(Object o) {
ResourceBundle result = null;
Parameters p = o.getClass().getAnnotation(Parameters.class);
if (p != null && ! isEmpty(p.resourceBundle())) {
result = ResourceBundle.getBundle(p.resourceBundle(), Locale.getDefault... | java |
public final void addObject(Object object) {
if (object instanceof Iterable) {
// Iterable
for (Object o : (Iterable<?>) object) {
objects.add(o);
}
} else if (object.getClass().isArray()) {
// Array
for (Object o : (Object[]) o... | java |
public void parse(String... args) {
try {
parse(true /* validate */, args);
} catch(ParameterException ex) {
ex.setJCommander(this);
throw ex;
}
} | java |
private void validateOptions() {
// No validation if we found a help parameter
if (helpWasSpecified) {
return;
}
if (!requiredFields.isEmpty()) {
List<String> missingFields = new ArrayList<>();
for (ParameterDescription pd : requiredFields.values()) {... | java |
private List<String> readFile(String fileName) {
List<String> result = Lists.newArrayList();
try (BufferedReader bufRead = Files.newBufferedReader(Paths.get(fileName), options.atFileCharset)) {
String line;
// Read through file one line at time. Print line # and line
... | java |
private static String trim(String string) {
String result = string.trim();
if (result.startsWith("\"") && result.endsWith("\"") && result.length() > 1) {
result = result.substring(1, result.length() - 1);
}
return result;
} | java |
private char[] readPassword(String description, boolean echoInput) {
getConsole().print(description + ": ");
return getConsole().readPassword(echoInput);
} | java |
public void setProgramName(String name, String... aliases) {
programName = new ProgramName(name, Arrays.asList(aliases));
} | java |
public void addConverterFactory(final IStringConverterFactory converterFactory) {
addConverterInstanceFactory(new IStringConverterInstanceFactory() {
@SuppressWarnings("unchecked")
@Override
public IStringConverter<?> getConverterInstance(Parameter parameter, Class<?> forType... | java |
public void addCommand(String name, Object object, String... aliases) {
JCommander jc = new JCommander(options);
jc.addObject(object);
jc.createDescriptions();
jc.setProgramName(name, aliases);
ProgramName progName = jc.programName;
commands.put(progName, jc);
/*
... | java |
private boolean itemIsObscuredByHeader(RecyclerView parent, View item, View header, int orientation) {
RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) item.getLayoutParams();
mDimensionCalculator.initMargins(mTempRect1, header);
int adapterPosition = parent.getChildAdapterPosition(item... | java |
public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
canvas.save();
if (recyclerView.getLayoutManager().getClipToPadding()) {
// Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
initClipRectForHeader(mTempRect, recycle... | java |
public static boolean isIanaRel(String relation) {
Assert.notNull(relation, "Link relation must not be null!");
return LINK_RELATIONS.stream() //
.anyMatch(it -> it.value().equalsIgnoreCase(relation));
} | java |
public List<MethodParameter> getParametersOfType(Class<?> type) {
Assert.notNull(type, "Type must not be null!");
return getParameters().stream() //
.filter(it -> it.getParameterType().equals(type)) //
.collect(Collectors.toList());
} | java |
public static boolean isTemplate(String candidate) {
return StringUtils.hasText(candidate) //
? VARIABLE_REGEX.matcher(candidate).find()
: false;
} | java |
public List<String> getVariableNames() {
return variables.asList().stream() //
.map(TemplateVariable::getName) //
.collect(Collectors.toList());
} | java |
private static String join(String typeMapping, String mapping) {
return MULTIPLE_SLASHES.matcher(typeMapping.concat("/").concat(mapping)).replaceAll("/");
} | java |
public static String encodePath(Object source) {
Assert.notNull(source, "Path value must not be null!");
try {
return UriUtils.encodePath(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | java |
public static String encodeParameter(Object source) {
Assert.notNull(source, "Request parameter value must not be null!");
try {
return UriUtils.encodeQueryParam(source.toString(), ENCODING);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
} | java |
protected D createModelWithId(Object id, T entity) {
return createModelWithId(id, entity, new Object[0]);
} | java |
private static void validate(RepresentationModel<?> resource, HalFormsAffordanceModel model) {
String affordanceUri = model.getURI();
String selfLinkUri = resource.getRequiredLink(IanaLinkRelations.SELF.value()).expand().getHref();
if (!affordanceUri.equals(selfLinkUri)) {
throw new IllegalStateException("Af... | java |
public Hop withParameter(String name, Object value) {
Assert.hasText(name, "Name must not be null or empty!");
HashMap<String, Object> parameters = new HashMap<>(this.parameters);
parameters.put(name, value);
return new Hop(this.rel, parameters, this.headers);
} | java |
public Hop header(String headerName, String headerValue) {
Assert.hasText(headerName, "headerName must not be null or empty!");
if (this.headers == HttpHeaders.EMPTY) {
HttpHeaders newHeaders = new HttpHeaders();
newHeaders.add(headerName, headerValue);
return new Hop(this.rel, this.parameters, newHead... | java |
private static List<UberData> doExtractLinksAndContent(Object item) {
if (item instanceof EntityModel) {
return extractLinksAndContent((EntityModel<?>) item);
}
if (item instanceof RepresentationModel) {
return extractLinksAndContent((RepresentationModel<?>) item);
}
return extractLinksAndContent(new... | java |
@JsonIgnore
public HalFormsTemplate getTemplate(String key) {
Assert.notNull(key, "Template key must not be null!");
return this.templates.get(key);
} | java |
public HalFormsDocument<T> andEmbedded(HalLinkRelation key, Object value) {
Assert.notNull(key, "Embedded key must not be null!");
Assert.notNull(value, "Embedded value must not be null!");
Map<HalLinkRelation, Object> embedded = new HashMap<>(this.embedded);
embedded.put(key, value);
return new HalFormsDo... | java |
@Nullable
public Object toRawData(JavaType javaType) {
if (this.data.isEmpty()) {
return null;
}
if (PRIMITIVE_TYPES.contains(javaType.getRawClass())) {
return this.data.get(0).getValue();
}
return PropertyUtils.createObjectFromProperties(javaType.getRawClass(), //
this.data.stream().collect(Col... | java |
@SuppressWarnings("unchecked")
public T add(Link link) {
Assert.notNull(link, "Link must not be null!");
this.links.add(link);
return (T) this;
} | java |
private static void insertJsonColumn(CqlSession session) {
User alice = new User("alice", 30);
User bob = new User("bob", 35);
// Build and execute a simple statement
Statement stmt =
insertInto("examples", "json_jackson_column")
.value("id", literal(1))
// the User ob... | java |
private static void selectJsonColumn(CqlSession session) {
Statement stmt =
selectFrom("examples", "json_jackson_column")
.all()
.whereColumn("id")
.in(literal(1), literal(2))
.build();
ResultSet rows = session.execute(stmt);
for (Row row : rows) {
... | java |
public static String opcodeString(int opcode) {
switch (opcode) {
case ProtocolConstants.Opcode.ERROR:
return "ERROR";
case ProtocolConstants.Opcode.STARTUP:
return "STARTUP";
case ProtocolConstants.Opcode.READY:
return "READY";
case ProtocolConstants.Opcode.AUTHENTIC... | java |
public static String errorCodeString(int errorCode) {
switch (errorCode) {
case ProtocolConstants.ErrorCode.SERVER_ERROR:
return "SERVER_ERROR";
case ProtocolConstants.ErrorCode.PROTOCOL_ERROR:
return "PROTOCOL_ERROR";
case ProtocolConstants.ErrorCode.AUTH_ERROR:
return "AU... | java |
public void reconnectNow(boolean forceIfStopped) {
assert executor.inEventLoop();
if (state == State.ATTEMPT_IN_PROGRESS || state == State.STOP_AFTER_CURRENT) {
LOG.debug(
"[{}] reconnectNow and current attempt was still running, letting it complete",
logPrefix);
if (state == Sta... | java |
private void onNextAttemptStarted(CompletionStage<Boolean> futureOutcome) {
assert executor.inEventLoop();
state = State.ATTEMPT_IN_PROGRESS;
futureOutcome
.whenCompleteAsync(this::onNextAttemptCompleted, executor)
.exceptionally(UncaughtExceptions::log);
} | java |
public static <T> T getCompleted(CompletionStage<T> stage) {
CompletableFuture<T> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isDone() && !future.isCompletedExceptionally());
try {
return future.get();
} catch (InterruptedException | ExecutionException e) {
// Ne... | java |
public static Throwable getFailed(CompletionStage<?> stage) {
CompletableFuture<?> future = stage.toCompletableFuture();
Preconditions.checkArgument(future.isCompletedExceptionally());
try {
future.get();
throw new AssertionError("future should be failed");
} catch (InterruptedException e) {... | java |
private CompletionStage<Void> prepareOnOtherNode(Node node) {
LOG.trace("[{}] Repreparing on {}", logPrefix, node);
DriverChannel channel = session.getChannel(node, logPrefix);
if (channel == null) {
LOG.trace("[{}] Could not get a channel to reprepare on {}, skipping", logPrefix, node);
return ... | java |
private static void insertJsonColumn(CqlSession session) {
JsonObject alice = Json.createObjectBuilder().add("name", "alice").add("age", 30).build();
JsonObject bob = Json.createObjectBuilder().add("name", "bob").add("age", 35).build();
// Build and execute a simple statement
Statement stmt =
... | java |
public static void warnWithException(Logger logger, String format, Object... arguments) {
if (logger.isDebugEnabled()) {
logger.warn(format, arguments);
} else {
Object last = arguments[arguments.length - 1];
if (last instanceof Throwable) {
Throwable t = (Throwable) last;
argu... | java |
private void savePort(DriverChannel channel) {
if (port < 0) {
SocketAddress address = channel.getEndPoint().resolve();
if (address instanceof InetSocketAddress) {
port = ((InetSocketAddress) address).getPort();
}
}
} | java |
@NonNull
@Override
public Iterator<AdminRow> iterator() {
return new AbstractIterator<AdminRow>() {
@Override
protected AdminRow computeNext() {
List<ByteBuffer> rowData = data.poll();
return (rowData == null)
? endOfData()
: new AdminRow(columnSpecs, rowData,... | java |
protected TypeCodec<?> createCodec(GenericType<?> javaType, boolean isJavaCovariant) {
TypeToken<?> token = javaType.__getToken();
if (List.class.isAssignableFrom(token.getRawType())
&& token.getType() instanceof ParameterizedType) {
Type[] typeArguments = ((ParameterizedType) token.getType()).get... | java |
protected TypeCodec<?> createCodec(DataType cqlType) {
if (cqlType instanceof ListType) {
DataType elementType = ((ListType) cqlType).getElementType();
TypeCodec<Object> elementCodec = codecFor(elementType);
return TypeCodecs.listOf(elementCodec);
} else if (cqlType instanceof SetType) {
... | java |
private static <DeclaredT, RuntimeT> TypeCodec<DeclaredT> uncheckedCast(
TypeCodec<RuntimeT> codec) {
@SuppressWarnings("unchecked")
TypeCodec<DeclaredT> result = (TypeCodec<DeclaredT>) codec;
return result;
} | java |
protected long computeNext(long last) {
long currentTick = clock.currentTimeMicros();
if (last >= currentTick) {
maybeLog(currentTick, last);
return last + 1;
}
return currentTick;
} | java |
public static int skipSpaces(String toParse, int idx) {
while (isBlank(toParse.charAt(idx)) && idx < toParse.length()) ++idx;
return idx;
} | java |
public static int skipCQLValue(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
if (isBlank(toParse.charAt(idx))) throw new IllegalArgumentException();
int cbrackets = 0;
int sbrackets = 0;
int parens = 0;
boolean inString = false;
do {
c... | java |
public static int skipCQLId(String toParse, int idx) {
if (idx >= toParse.length()) throw new IllegalArgumentException();
char c = toParse.charAt(idx);
if (isCqlIdentifierChar(c)) {
while (idx < toParse.length() && isCqlIdentifierChar(toParse.charAt(idx))) idx++;
return idx;
}
if (c !=... | java |
public <EventT> Object register(Class<EventT> eventClass, Consumer<EventT> listener) {
LOG.debug("[{}] Registering {} for {}", logPrefix, listener, eventClass);
listeners.put(eventClass, listener);
// The reason for the key mechanism is that this will often be used with method references,
// and you get... | java |
public <EventT> boolean unregister(Object key, Class<EventT> eventClass) {
LOG.debug("[{}] Unregistering {} for {}", logPrefix, key, eventClass);
return listeners.remove(eventClass, key);
} | java |
public void fire(Object event) {
LOG.debug("[{}] Firing an instance of {}: {}", logPrefix, event.getClass(), event);
// if the exact match thing gets too cumbersome, we can reconsider, but I'd like to avoid
// scanning all the keys with instanceof checks.
Class<?> eventClass = event.getClass();
for ... | java |
public static boolean needsDoubleQuotes(String s) {
// this method should only be called for C*-provided identifiers,
// so we expect it to be non-null and non-empty.
assert s != null && !s.isEmpty();
char c = s.charAt(0);
if (!(c >= 97 && c <= 122)) // a-z
return true;
for (int i = 1; i < s... | java |
public static boolean isLongLiteral(String str) {
if (str == null || str.isEmpty()) return false;
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((c < '0' && (i != 0 || c != '-')) || c > '9') return false;
}
return true;
} | java |
@NonNull
public String asCql(boolean pretty) {
if (pretty) {
return Strings.needsDoubleQuotes(internal) ? Strings.doubleQuote(internal) : internal;
} else {
return Strings.doubleQuote(internal);
}
} | java |
public Map<String, String> build() {
NullAllowingImmutableMap.Builder<String, String> builder = NullAllowingImmutableMap.builder(3);
// add compression (if configured) and driver name and version
String compressionAlgorithm = context.getCompressor().algorithm();
if (compressionAlgorithm != null && !comp... | java |
private void connect() {
session = CqlSession.builder().build();
System.out.printf("Connected to session: %s%n", session.getName());
} | java |
private void write(ConsistencyLevel cl, int retryCount) {
System.out.printf("Writing at %s (retry count: %d)%n", cl, retryCount);
BatchStatement batch =
BatchStatement.newInstance(UNLOGGED)
.add(
SimpleStatement.newInstance(
"INSERT INTO downgrading.sens... | java |
private ResultSet read(ConsistencyLevel cl, int retryCount) {
System.out.printf("Reading at %s (retry count: %d)%n", cl, retryCount);
Statement stmt =
SimpleStatement.newInstance(
"SELECT sensor_id, date, timestamp, value "
+ "FROM downgrading.sensor_data "
... | java |
private void display(ResultSet rows) {
final int width1 = 38;
final int width2 = 12;
final int width3 = 30;
final int width4 = 21;
String format = "%-" + width1 + "s%-" + width2 + "s%-" + width3 + "s%-" + width4 + "s%n";
// headings
System.out.printf(format, "sensor_id", "date", "timestam... | java |
private static ConsistencyLevel downgrade(
ConsistencyLevel current, int acknowledgements, DriverException original) {
if (acknowledgements >= 3) {
return DefaultConsistencyLevel.THREE;
}
if (acknowledgements == 2) {
return DefaultConsistencyLevel.TWO;
}
if (acknowledgements == 1) ... | java |
private static void drawLine(int... widths) {
for (int width : widths) {
for (int i = 1; i < width; i++) {
System.out.print('-');
}
System.out.print('+');
}
System.out.println();
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.