code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
public OIdentifiableIterator<REC> setReuseSameRecord(final boolean reuseSameRecord) {
reusedRecord = (ORecordInternal<?>) (reuseSameRecord ? database.newInstance() : null);
return this;
} | java |
protected ORecordInternal<?> getRecord() {
final ORecordInternal<?> record;
if (reusedRecord != null) {
// REUSE THE SAME RECORD AFTER HAVING RESETTED IT
record = reusedRecord;
record.reset();
} else
record = null;
return record;
} | java |
protected ORecordInternal<?> readCurrentRecord(ORecordInternal<?> iRecord, final int iMovement) {
if (limit > -1 && browsedRecords >= limit)
// LIMIT REACHED
return null;
current.clusterPosition += iMovement;
if (iRecord != null) {
iRecord.setIdentity(current);
iRecord = lowLevelDatabase.load(iRecord, fetchPlan);
} else
iRecord = lowLevelDatabase.load(current, fetchPlan);
if (iRecord != null)
browsedRecords++;
return iRecord;
} | java |
public void bindParameters(final Map<Object, Object> iArgs) {
if (parameterItems == null || iArgs == null || iArgs.size() == 0)
return;
for (Entry<Object, Object> entry : iArgs.entrySet()) {
if (entry.getKey() instanceof Integer)
parameterItems.get(((Integer) entry.getKey())).setValue(entry.setValue(entry.getValue()));
else {
String paramName = entry.getKey().toString();
for (OSQLFilterItemParameter value : parameterItems) {
if (value.getName().equalsIgnoreCase(paramName)) {
value.setValue(entry.getValue());
break;
}
}
}
}
} | java |
@Override
public boolean send(Context context, Report report) {
if (url != null) {
String reportStr = report.asJSON()
.toString();
try {
postReport(url, reportStr);
return true;
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} | java |
public static void post(URL url, String params) throws IOException {
URLConnection conn = url.openConnection();
if (conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).setRequestMethod("POST");
conn.setRequestProperty("Content-Type" , "application/json");
}
OutputStreamWriter writer = null;
try {
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream(),
Charset.forName("UTF-8"));
// write parameters
writer.write(params);
writer.flush();
} finally {
if (writer != null) {
writer.close();
}
}
} | java |
public static String read(InputStream in) throws IOException {
InputStreamReader isReader = new InputStreamReader(in, "UTF-8");
BufferedReader reader = new BufferedReader(isReader);
StringBuffer out = new StringBuffer();
char[] c = new char[4096];
for (int n; (n = reader.read(c)) != -1;) {
out.append(new String(c, 0, n));
}
reader.close();
return out.toString();
} | java |
public Object joinGame(long id, String password) {
return client.sendRpcAndWait(SERVICE, "joinGame", id, password);
} | java |
public Object observeGame(long id, String password) {
return client.sendRpcAndWait(SERVICE, "observeGame", id, password);
} | java |
public boolean switchToPlayer(long id, PlayerSide team) {
return client.sendRpcAndWait(SERVICE, "switchObserverToPlayer", id, team.id);
} | java |
protected byte[] serializeStreamValue(final int iIndex) throws IOException {
if (serializedValues[iIndex] <= 0) {
// NEW OR MODIFIED: MARSHALL CONTENT
OProfiler.getInstance().updateCounter("OMVRBTreeMapEntry.serializeValue", 1);
return ((OMVRBTreeMapProvider<K, V>) treeDataProvider).valueSerializer.toStream(values[iIndex]);
}
// RETURN ORIGINAL CONTENT
return stream.getAsByteArray(serializedValues[iIndex]);
} | java |
public MigrationJob[] retrieveJobs(int batchSize, int startIndex, JobType jobType)
throws IOException, LightblueException {
LOGGER.debug("Retrieving jobs: batchSize={}, startIndex={}", batchSize, startIndex);
DataFindRequest findRequest = new DataFindRequest("migrationJob", null);
List<Query> conditions = new ArrayList<>(Arrays.asList(new Query[] {
// get jobs for this configuration
Query.withValue("configurationName", Query.eq, migrationConfiguration.getConfigurationName()),
// get jobs whose state ara available
Query.withValue("status", Query.eq, "available"),
// only get jobs that are
Query.withValue("scheduledDate", Query.lte, new Date())
}));
if (jobType == JobType.GENERATED) {
LOGGER.debug("Looking for generated job");
conditions.add(Query.withValue("generated", Query.eq, true));
} else if (jobType == JobType.NONGENERATED) {
LOGGER.debug("Looking for non generated job");
conditions.add(Query.withValue("generated", Query.eq, false));
}
findRequest.where(Query.and(conditions));
findRequest.select(Projection.includeField("*"));
findRequest.range(startIndex, startIndex + batchSize - 1);
LOGGER.debug("Finding Jobs to execute: {}", findRequest.getBody());
return lbClient.data(findRequest, MigrationJob[].class);
} | java |
public ActiveExecution lock(String id)
throws Exception {
LOGGER.debug("locking {}", id);
if (!myLocks.contains(id)) {
if (locking.acquire(id, null)) {
myLocks.add(id);
ActiveExecution ae = new ActiveExecution();
ae.setMigrationJobId(id);
ae.set_id(id);
ae.setStartTime(new Date());
return ae;
}
}
return null;
} | java |
public <H extends EventHandler> H getHandler(GwtEvent.Type<H> type, int index) {
return this.eventBus.superGetHandler(type, index);
} | java |
public <H extends EventHandler> void removeHandler(GwtEvent.Type<H> type, final H handler) {
this.eventBus.superDoRemove(type, null, handler);
} | java |
@Override
public void sendFailure(String message) {
System.out.print("Warning: " + message);
System.exit(1);
} | java |
@Override
public void sendError(String message) {
System.out.print("Critical: " + message);
System.exit(2);
} | java |
public Object execute(final Map<Object, Object> iArgs) {
if (className == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseRecord database = getDatabase();
if (database.getMetadata().getSchema().existsClass(className))
throw new OCommandExecutionException("Class " + className + " already exists");
final OClassImpl sourceClass = (OClassImpl) ((OSchemaProxy) database.getMetadata().getSchema()).createClassInternal(className,
superClass, clusterIds);
sourceClass.saveInternal();
if (superClass != null) {
int[] clustersToIndex = superClass.getPolymorphicClusterIds();
String[] clusterNames = new String[clustersToIndex.length];
for (int i = 0; i < clustersToIndex.length; i++) {
clusterNames[i] = database.getClusterNameById(clustersToIndex[i]);
}
for (OIndex<?> index : superClass.getIndexes())
for (String clusterName : clusterNames)
index.getInternal().addCluster(clusterName);
}
return database.getMetadata().getSchema().getClasses().size();
} | java |
public boolean callbackHooks(final TYPE iType, final OIdentifiable id) {
if (!OHookThreadLocal.INSTANCE.push(id))
return false;
try {
final ORecord<?> rec = id.getRecord();
if (rec == null)
return false;
boolean recordChanged = false;
for (ORecordHook hook : hooks)
if (hook.onTrigger(iType, rec))
recordChanged = true;
return recordChanged;
} finally {
OHookThreadLocal.INSTANCE.pop(id);
}
} | java |
public String execute(String url, String urlParameters, String clientId, String secret, String method) throws
Exception {
HttpURLConnection connection;
String credentials = clientId + ":" + secret;
String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
if ("POST".equalsIgnoreCase(method)) {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoInput(true);
connection.setDoOutput(true);
if (null != urlParameters) {
try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
out.print(urlParameters);
}
}
} else {
connection = (HttpURLConnection) new URL(url + "?" + urlParameters).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", authorizationHeader);
}
int timeout = Integer.parseInt(System.getProperty("org.hawkular.accounts.http.timeout", "5000"));
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
StringBuilder response = new StringBuilder();
int statusCode;
try {
statusCode = connection.getResponseCode();
} catch (SocketTimeoutException timeoutException) {
throw new UsernamePasswordConversionException("Timed out when trying to contact the Keycloak server.");
}
InputStream inputStream;
if (statusCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
for (String line; (line = reader.readLine()) != null; ) {
response.append(line);
}
}
return response.toString();
} | java |
private void buildReport(Context context) {
try {
buildBaseReport();
buildApplicationData(context);
buildDeviceData(context);
buildLog();
report.put("application", app);
report.put("device", device);
report.put("log", logs);
} catch (JSONException e) {
e.printStackTrace();
}
} | java |
private void buildLog() throws JSONException {
logs = new JSONObject();
List<String> list = Log.getReportedEntries();
if (list != null) {
logs.put("numberOfEntry", list.size());
JSONArray array = new JSONArray();
for (String s : list) {
array.put(s);
}
logs.put("log", array);
}
} | java |
private void buildDeviceData(Context context) throws JSONException {
device = new JSONObject();
device.put("device", Build.DEVICE);
device.put("brand", Build.BRAND);
Object windowService = context.getSystemService(Context.WINDOW_SERVICE);
if (windowService instanceof WindowManager) {
Display display = ((WindowManager)windowService).getDefaultDisplay();
device.put("resolution", display.getWidth() + "x" + display.getHeight());
device.put("orientation", display.getOrientation());
}
device.put("display", Build.DISPLAY);
device.put("manufacturer", Build.MANUFACTURER);
device.put("model", Build.MODEL);
device.put("product", Build.PRODUCT);
device.put("build.type", Build.TYPE);
device.put("android.version", Build.VERSION.SDK_INT);
} | java |
private void buildApplicationData(Context context) throws JSONException {
app = new JSONObject();
app.put("package", context.getPackageName());
try {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
app.put("versionCode", info.versionCode);
app.put("versionName", info.versionName);
// TODO firstInstallTime and lastUpdate
} catch (NameNotFoundException e) {
// Cannot happen as we're checking a know package.
}
} | java |
public Set<ODocument> getEdgesBetweenVertexes(final ODocument iVertex1, final ODocument iVertex2) {
return getEdgesBetweenVertexes(iVertex1, iVertex2, null, null);
} | java |
public Set<ODocument> getEdgesBetweenVertexes(final ODocument iVertex1, final ODocument iVertex2, final String[] iLabels) {
return getEdgesBetweenVertexes(iVertex1, iVertex2, iLabels, null);
} | java |
public Set<ODocument> getEdgesBetweenVertexes(final ODocument iVertex1, final ODocument iVertex2, final String[] iLabels,
final String[] iClassNames) {
final Set<ODocument> result = new HashSet<ODocument>();
if (iVertex1 != null && iVertex2 != null) {
// CHECK OUT EDGES
for (OIdentifiable e : getOutEdges(iVertex1)) {
final ODocument edge = (ODocument) e;
if (checkEdge(edge, iLabels, iClassNames)) {
if (edge.<ODocument> field("in").equals(iVertex2))
result.add(edge);
}
}
// CHECK IN EDGES
for (OIdentifiable e : getInEdges(iVertex1)) {
final ODocument edge = (ODocument) e;
if (checkEdge(edge, iLabels, iClassNames)) {
if (edge.<ODocument> field("out").equals(iVertex2))
result.add(edge);
}
}
}
return result;
} | java |
public Set<OIdentifiable> getOutEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) {
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
return filterEdgesByProperties((OMVRBTreeRIDSet) vertex.field(VERTEX_FIELD_OUT), iProperties);
} | java |
public Set<OIdentifiable> getInEdgesHavingProperties(final OIdentifiable iVertex, Iterable<String> iProperties) {
final ODocument vertex = iVertex.getRecord();
checkVertexClass(vertex);
return filterEdgesByProperties((OMVRBTreeRIDSet) vertex.field(VERTEX_FIELD_IN), iProperties);
} | java |
public Set<OIdentifiable> getInEdgesHavingProperties(final ODocument iVertex, final Map<String, Object> iProperties) {
checkVertexClass(iVertex);
return filterEdgesByProperties((OMVRBTreeRIDSet) iVertex.field(VERTEX_FIELD_IN), iProperties);
} | java |
public synchronized OServerAdmin connect(final String iUserName, final String iUserPassword) throws IOException {
storage.createConnectionPool();
storage.setSessionId(-1);
try {
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_CONNECT);
storage.sendClientInfo(network);
try {
network.writeString(iUserName);
network.writeString(iUserPassword);
} finally {
storage.endRequest(network);
}
try {
storage.beginResponse(network);
sessionId = network.readInt();
storage.setSessionId(sessionId);
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot connect to the remote server: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
} | java |
@SuppressWarnings("unchecked")
public synchronized Map<String, String> listDatabases() throws IOException {
storage.checkConnection();
final ODocument result = new ODocument();
try {
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_LIST);
storage.endRequest(network);
try {
storage.beginResponse(network);
result.fromStream(network.readBytes());
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Cannot retrieve the configuration list", e, OStorageException.class);
storage.close(true);
}
return (Map<String, String>) result.field("databases");
} | java |
public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException {
storage.checkConnection();
try {
if (storage.getName() == null || storage.getName().length() <= 0) {
OLogManager.instance().error(this, "Cannot create unnamed remote storage. Check your syntax", OStorageException.class);
} else {
if (iStorageMode == null)
iStorageMode = "csv";
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_CREATE);
try {
network.writeString(storage.getName());
if (network.getSrvProtocolVersion() >= 8)
network.writeString(iDatabaseType);
network.writeString(iStorageMode);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create the remote storage: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
} | java |
public synchronized boolean existsDatabase() throws IOException {
storage.checkConnection();
try {
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_EXIST);
try {
network.writeString(storage.getName());
} finally {
storage.endRequest(network);
}
try {
storage.beginResponse(network);
return network.readByte() == 1;
} finally {
storage.endResponse(network);
}
} catch (Exception e) {
OLogManager.instance().exception("Error on checking existence of the remote storage: " + storage.getName(), e,
OStorageException.class);
storage.close(true);
}
return false;
} | java |
public synchronized OServerAdmin dropDatabase() throws IOException {
storage.checkConnection();
boolean retry = true;
while (retry)
try {
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_DROP);
try {
network.writeString(storage.getName());
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
retry = false;
} catch (OModificationOperationProhibitedException oope) {
retry = handleDBFreeze();
} catch (Exception e) {
OLogManager.instance().exception("Cannot delete the remote storage: " + storage.getName(), e, OStorageException.class);
}
for (OStorage s : Orient.instance().getStorages()) {
if (s.getURL().startsWith(getURL())) {
s.removeResource(OSchema.class.getSimpleName());
s.removeResource(OIndexManager.class.getSimpleName());
s.removeResource(OSecurity.class.getSimpleName());
}
}
ODatabaseRecordThreadLocal.INSTANCE.set(null);
return this;
} | java |
public ODocument clusterStatus() {
final ODocument response = sendRequest(OChannelBinaryProtocol.REQUEST_CLUSTER, new ODocument().field("operation", "status"),
"Cluster status");
OLogManager.instance().debug(this, "Cluster status %s", response.toJSON());
return response;
} | java |
public synchronized OServerAdmin replicationStop(final String iDatabaseName, final String iRemoteServer) throws IOException {
sendRequest(OChannelBinaryProtocol.REQUEST_REPLICATION, new ODocument().field("operation", "stop").field("node", iRemoteServer)
.field("db", iDatabaseName), "Stop replication");
OLogManager.instance().debug(this, "Stopped replication of database '%s' from server '%s' to '%s'", iDatabaseName,
storage.getURL(), iRemoteServer);
return this;
} | java |
public synchronized ODocument getReplicationJournal(final String iDatabaseName, final String iRemoteServer) throws IOException {
OLogManager.instance().debug(this, "Retrieving the replication log for database '%s' from server '%s'...", iDatabaseName,
storage.getURL());
final ODocument response = sendRequest(OChannelBinaryProtocol.REQUEST_REPLICATION,
new ODocument().field("operation", "getJournal").field("node", iRemoteServer).field("db", iDatabaseName),
"Retrieve replication log");
OLogManager.instance().debug(this,
"Returned %d replication log entries for the database '%s' from server '%s' against server '%s'", response.fields(),
iDatabaseName, storage.getURL(), iRemoteServer);
return response;
} | java |
public OServerAdmin replicationAlign(final String iDatabaseName, final String iRemoteServer, final String iOptions) {
OLogManager.instance().debug(this, "Started the alignment of database '%s' from server '%s' to '%s' with options %s",
iDatabaseName, storage.getURL(), iRemoteServer, iOptions);
sendRequest(OChannelBinaryProtocol.REQUEST_REPLICATION, new ODocument().field("operation", "align")
.field("node", iRemoteServer).field("db", iDatabaseName).field("options", iOptions), "Align databases");
OLogManager.instance().debug(this, "Alignment finished");
return this;
} | java |
public synchronized OServerAdmin copyDatabase(final String iDatabaseName, final String iDatabaseUserName,
final String iDatabaseUserPassword, final String iRemoteName, final String iRemoteEngine) throws IOException {
storage.checkConnection();
try {
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_COPY);
try {
network.writeString(iDatabaseName);
network.writeString(iDatabaseUserName);
network.writeString(iDatabaseUserPassword);
network.writeString(iRemoteName);
network.writeString(iRemoteEngine);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
OLogManager.instance().debug(this, "Database '%s' has been copied to the server '%s'", iDatabaseName, iRemoteName);
} catch (Exception e) {
OLogManager.instance().exception("Cannot copy the database: " + iDatabaseName, e, OStorageException.class);
}
return this;
} | java |
public Object execute(final OIdentifiable o, final OCommandExecutor iRequester) {
// RESOLVE VALUES USING THE CURRENT RECORD
for (int i = 0; i < configuredParameters.length; ++i) {
if (configuredParameters[i] instanceof OSQLFilterItemField)
runtimeParameters[i] = ((OSQLFilterItemField) configuredParameters[i]).getValue(o, null);
else if (configuredParameters[i] instanceof OSQLFunctionRuntime)
runtimeParameters[i] = ((OSQLFunctionRuntime) configuredParameters[i]).execute(o, iRequester);
}
final Object functionResult = function.execute(o, runtimeParameters, iRequester);
return transformValue(o, functionResult);
} | java |
public static EmbeddedJettyBuilder.ServletContextHandlerBuilder addWicketHandler(EmbeddedJettyBuilder embeddedJettyBuilder,
String contextPath,
EventListener springContextloader,
Class<? extends WebApplication> wicketApplication,
boolean development){
EmbeddedJettyBuilder.ServletContextHandlerBuilder wicketHandler = embeddedJettyBuilder.createRootServletContextHandler(contextPath)
.setClassLoader(Thread.currentThread().getContextClassLoader())
.addEventListener(springContextloader);
return addWicketHandler(wicketHandler, wicketApplication, development);
} | java |
public boolean add(final OIdentifiable e) {
if (e.getIdentity().isNew()) {
final ORecord<?> record = e.getRecord();
// ADD IN TEMP LIST
if (newItems == null)
newItems = new IdentityHashMap<ORecord<?>, Object>();
else if (newItems.containsKey(record))
return false;
newItems.put(record, NEWMAP_VALUE);
setDirty();
return true;
} else if (OGlobalConfiguration.LAZYSET_WORK_ON_STREAM.getValueAsBoolean() && getStreamedContent() != null) {
// FAST INSERT
final String ridString = e.getIdentity().toString();
final StringBuilder buffer = getStreamedContent();
if (buffer.indexOf(ridString) < 0) {
if (buffer.length() > 0)
buffer.append(',');
e.getIdentity().toString(buffer);
setDirty();
return true;
}
return false;
} else {
final int pos = indexOf(e);
if (pos < 0) {
// FOUND
delegate.add(pos * -1 - 1, e);
return true;
}
return false;
}
} | java |
public int indexOf(final OIdentifiable iElement) {
if (delegate.isEmpty())
return -1;
final boolean prevConvert = delegate.isAutoConvertToRecord();
if (prevConvert)
delegate.setAutoConvertToRecord(false);
final int pos = Collections.binarySearch(delegate, iElement);
if (prevConvert)
// RESET PREVIOUS SETTINGS
delegate.setAutoConvertToRecord(true);
return pos;
} | java |
public ORDER compare(OQueryOperator other) {
final Class<?> thisClass = this.getClass();
final Class<?> otherClass = other.getClass();
int thisPosition = -1;
int otherPosition = -1;
for (int i = 0; i < DEFAULT_OPERATORS_ORDER.length; i++) {
// subclass of default operators inherit their parent ordering
final Class<?> clazz = DEFAULT_OPERATORS_ORDER[i];
if (clazz.isAssignableFrom(thisClass)) {
thisPosition = i;
}
if (clazz.isAssignableFrom(otherClass)) {
otherPosition = i;
}
}
if (thisPosition == -1 || otherPosition == -1) {
// can not decide which comes first
return ORDER.UNKNOWNED;
}
if (thisPosition > otherPosition) {
return ORDER.AFTER;
} else if (thisPosition < otherPosition) {
return ORDER.BEFORE;
}
return ORDER.EQUAL;
} | java |
public Object execute(final Map<Object, Object> iArgs) {
if (attribute == null)
throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");
final ODatabaseRecord database = getDatabase();
database.checkSecurity(ODatabaseSecurityResources.DATABASE, ORole.PERMISSION_UPDATE);
((ODatabaseComplex<?>) database).setInternal(attribute, value);
return null;
} | java |
@Override
public boolean open() throws IOException {
lock.acquireExclusiveLock();
try {
// IGNORE IF IT'S SOFTLY CLOSED
super.open();
// CHECK FOR PENDING TRANSACTION ENTRIES TO RECOVER
recoverTransactions();
return true;
} finally {
lock.releaseExclusiveLock();
}
} | java |
public void addLog(final byte iOperation, final int iTxId, final int iClusterId, final long iClusterOffset,
final byte iRecordType, final int iRecordVersion, final byte[] iRecordContent, int dataSegmentId) throws IOException {
final int contentSize = iRecordContent != null ? iRecordContent.length : 0;
final int size = OFFSET_RECORD_CONTENT + contentSize;
lock.acquireExclusiveLock();
try {
int offset = file.allocateSpace(size);
file.writeByte(offset, STATUS_COMMITTING);
offset += OBinaryProtocol.SIZE_BYTE;
file.writeByte(offset, iOperation);
offset += OBinaryProtocol.SIZE_BYTE;
file.writeInt(offset, iTxId);
offset += OBinaryProtocol.SIZE_INT;
file.writeShort(offset, (short) iClusterId);
offset += OBinaryProtocol.SIZE_SHORT;
file.writeLong(offset, iClusterOffset);
offset += OBinaryProtocol.SIZE_LONG;
file.writeByte(offset, iRecordType);
offset += OBinaryProtocol.SIZE_BYTE;
file.writeInt(offset, iRecordVersion);
offset += OBinaryProtocol.SIZE_INT;
file.writeInt(offset, dataSegmentId);
offset += OBinaryProtocol.SIZE_INT;
file.writeInt(offset, contentSize);
offset += OBinaryProtocol.SIZE_INT;
file.write(offset, iRecordContent);
offset += contentSize;
if (synchEnabled)
file.synch();
} finally {
lock.releaseExclusiveLock();
}
} | java |
private Set<Integer> scanForTransactionsToRecover() throws IOException {
// SCAN ALL THE FILE SEARCHING FOR THE TRANSACTIONS TO RECOVER
final Set<Integer> txToRecover = new HashSet<Integer>();
final Set<Integer> txToNotRecover = new HashSet<Integer>();
// BROWSE ALL THE ENTRIES
for (long offset = 0; eof(offset); offset = nextEntry(offset)) {
// READ STATUS
final byte status = file.readByte(offset);
// READ TX-ID
final int txId = file.readInt(offset + OFFSET_TX_ID);
switch (status) {
case STATUS_FREE:
// NOT RECOVER IT SINCE IF FIND AT LEAST ONE "FREE" STATUS MEANS THAT ALL THE LOGS WAS COMMITTED BUT THE USER DIDN'T
// RECEIVED THE ACK
txToNotRecover.add(txId);
break;
case STATUS_COMMITTING:
// TO RECOVER UNLESS THE REQ/TX IS IN THE MAP txToNotRecover
txToRecover.add(txId);
break;
}
}
if (txToNotRecover.size() > 0)
// FILTER THE TX MAP TO RECOVER BY REMOVING THE TX WITH AT LEAST ONE "FREE" STATUS
txToRecover.removeAll(txToNotRecover);
return txToRecover;
} | java |
private int recoverTransaction(final int iTxId) throws IOException {
int recordsRecovered = 0;
final ORecordId rid = new ORecordId();
final List<Long> txRecordPositions = new ArrayList<Long>();
// BROWSE ALL THE ENTRIES
for (long beginEntry = 0; eof(beginEntry); beginEntry = nextEntry(beginEntry)) {
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
if (status != STATUS_FREE) {
// DIRTY TX LOG ENTRY
offset += OBinaryProtocol.SIZE_BYTE;
final int txId = file.readInt(offset);
if (txId == iTxId) {
txRecordPositions.add(beginEntry);
}
}
}
for (int i = txRecordPositions.size() - 1; i >= 0; i--) {
final long beginEntry = txRecordPositions.get(i);
long offset = beginEntry;
final byte status = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// DIRTY TX LOG ENTRY
final byte operation = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
// TX ID FOUND
final int txId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
rid.clusterId = file.readShort(offset);
offset += OBinaryProtocol.SIZE_SHORT;
rid.clusterPosition = file.readLong(offset);
offset += OBinaryProtocol.SIZE_LONG;
final byte recordType = file.readByte(offset);
offset += OBinaryProtocol.SIZE_BYTE;
final int recordVersion = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int dataSegmentId = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final int recordSize = file.readInt(offset);
offset += OBinaryProtocol.SIZE_INT;
final byte[] buffer;
if (recordSize > 0) {
buffer = new byte[recordSize];
file.read(offset, buffer, recordSize);
offset += recordSize;
} else
buffer = null;
recoverTransactionEntry(status, operation, txId, rid, recordType, recordVersion, buffer, dataSegmentId);
recordsRecovered++;
// CLEAR THE ENTRY BY WRITING '0'
file.writeByte(beginEntry, STATUS_FREE);
}
return recordsRecovered;
} | java |
public static String pingJdbcEndpoint(MuleContext muleContext, String muleJdbcDataSourceName, String tableName) {
DataSource ds = JdbcUtil.lookupDataSource(muleContext, muleJdbcDataSourceName);
Connection c = null;
Statement s = null;
ResultSet rs = null;
try {
c = ds.getConnection();
s = c.createStatement();
rs = s.executeQuery("select 1 from " + tableName);
} catch (SQLException e) {
return ERROR_PREFIX + ": The table " + tableName + " was not found in the data source " + muleJdbcDataSourceName + ", reason: " + e.getMessage();
} finally {
try {if (rs != null) rs.close();} catch (SQLException e) {}
try {if ( s != null) s.close();} catch (SQLException e) {}
try {if ( c != null) c.close();} catch (SQLException e) {}
}
return OK_PREFIX + ": The table " + tableName + " was found in the data source " + muleJdbcDataSourceName;
} | java |
public static String pingJmsEndpoint(MuleContext muleContext, String queueName) {
return pingJmsEndpoint(muleContext, DEFAULT_MULE_JMS_CONNECTOR, queueName);
} | java |
@SuppressWarnings("rawtypes")
private static boolean isQueueEmpty(MuleContext muleContext, String muleJmsConnectorName, String queueName) throws JMSException {
JmsConnector muleCon = (JmsConnector)MuleUtil.getSpringBean(muleContext, muleJmsConnectorName);
Session s = null;
QueueBrowser b = null;
try {
// Get a jms connection from mule and create a jms session
s = muleCon.getConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue q = s.createQueue(queueName);
b = s.createBrowser(q);
Enumeration e = b.getEnumeration();
return !e.hasMoreElements();
} finally {
try {if (b != null) b.close();} catch (JMSException e) {}
try {if (s != null) s.close();} catch (JMSException e) {}
}
} | java |
@Override
public T select(Object item) {
if (item == null) {
return null;
}
if (itemClass.isInstance(item)) {
return itemClass.cast(item);
}
logger.debug("item [{}] is not assignable to class [{}], returning null", item, itemClass);
return null;
} | java |
public BeanQuery<T> orderBy(String orderByProperty, Comparator propertyValueComparator) {
this.comparator = new DelegatedSortOrderableComparator(new PropertyComparator(orderByProperty,
propertyValueComparator));
return this;
} | java |
public BeanQuery<T> orderBy(Comparator... beanComparator) {
this.comparator = new DelegatedSortOrderableComparator(ComparatorUtils.chainedComparator(beanComparator));
return this;
} | java |
public T executeFrom(Object bean) {
List<T> executeFromCollectionResult = executeFrom(Collections.singleton(bean));
if (CollectionUtils.isEmpty(executeFromCollectionResult)) {
return null;
} else {
return executeFromCollectionResult.get(0);
}
} | java |
public List<T> execute() {
if (CollectionUtils.isEmpty(from)) {
logger.info("Querying from an empty collection, returning empty list.");
return Collections.emptyList();
}
List copied = new ArrayList(this.from);
logger.info("Start apply predicate [{}] to collection with [{}] items.", predicate, copied.size());
CollectionUtils.filter(copied, this.predicate);
logger.info("Done filtering collection, filtered result size is [{}]", copied.size());
if (null != this.comparator && copied.size()>1) {
Comparator actualComparator = this.descSorting ? comparator.desc() : comparator.asc();
logger.info("Start to sort the filtered collection with comparator [{}]", actualComparator);
Collections.sort(copied, actualComparator);
logger.info("Done sorting the filtered collection.");
}
logger.info("Start to slect from filtered collection with selector [{}].", selector);
List<T> select = this.selector.select(copied);
logger.info("Done select from filtered collection.");
return select;
} | java |
public static BeanQuery<Map<String, Object>> select(KeyValueMapSelector... selectors) {
return new BeanQuery<Map<String, Object>>(new CompositeSelector(selectors));
} | java |
@Override
public void write(final Writer writer) throws ConfigurationException, IOException {
Preconditions.checkNotNull(writer);
@SuppressWarnings("unchecked") final
HashMap<String, Object> settings = (HashMap<String, Object>) fromNode(this.getModel().getInMemoryRepresentation());
this.mapper.writerWithDefaultPrettyPrinter().writeValue(writer, settings);
} | java |
private ImmutableNode toNode(final Builder builder, final Object obj) {
assert !(obj instanceof List);
if (obj instanceof Map) {
return mapToNode(builder, (Map<String, Object>) obj);
} else {
return valueToNode(builder, obj);
}
} | java |
private ImmutableNode mapToNode(final Builder builder, final Map<String, Object> map) {
for (final Map.Entry<String, Object> entry : map.entrySet()) {
final String key = entry.getKey();
final Object value = entry.getValue();
if (value instanceof List) {
// For a list, add each list item as a child of this node.
for (final Object item : (List)value) {
addChildNode(builder, key, item);
}
} else {
// Otherwise, add the value as a child of this node.
addChildNode(builder, key, value);
}
}
return builder.create();
} | java |
private void addChildNode(final Builder builder, final String name, final Object value) {
assert !(value instanceof List);
final Builder childBuilder = new Builder();
// Set the name of the child node.
childBuilder.name(name);
// Set the value of the child node.
final ImmutableNode childNode = toNode(childBuilder, value);
// Add the node to the children of the node being built.
builder.addChild(childNode);
} | java |
private ImmutableNode valueToNode(final Builder builder, final Object value) {
// Set the value of the node being built.
return builder.value(value).create();
} | java |
private Object fromNode(final ImmutableNode node) {
if (!node.getChildren().isEmpty()) {
final Map<String, List<ImmutableNode>> children = getChildrenWithName(node);
final HashMap<String, Object> map = new HashMap<>();
for (final Map.Entry<String, List<ImmutableNode>> entry : children.entrySet()) {
assert !entry.getValue().isEmpty();
if (entry.getValue().size() == 1) {
// Just one node.
final ImmutableNode child = entry.getValue().get(0);
final Object childValue = fromNode(child);
map.put(entry.getKey(), childValue);
} else {
// Multiple nodes.
final ArrayList<Object> list = new ArrayList<>();
for (final ImmutableNode child : entry.getValue()) {
final Object childValue = fromNode(child);
list.add(childValue);
}
map.put(entry.getKey(), list);
}
}
return map;
} else {
return node.getValue();
}
} | java |
public ClassSelector except(String... propertyNames) {
if(ArrayUtils.isEmpty(propertyNames)){
return this;
}
boolean updated = false;
for (String propertyToRemove : propertyNames) {
if (removePropertySelector(propertyToRemove)) {
updated = true;
}
}
if (updated) {
compositeSelector = new CompositeSelector(this.propertySelectors);
}
return this;
} | java |
public ClassSelector add(String... propertyNames) {
if (ArrayUtils.isNotEmpty(propertyNames)) {
for (String propertyNameToAdd : propertyNames) {
addPropertySelector(propertyNameToAdd);
}
}
return this;
} | java |
public ViewSelectionAttributeAssert attribute(String attributeName) {
isNotEmpty();
ViewSelectionAttribute attributeValues = new ViewSelectionAttribute(actual, attributeName);
return new ViewSelectionAttributeAssert(attributeValues);
} | java |
private static Message generateHeader(HeaderValues param) {
HeaderFields header = new HeaderFields();
setValues(header, param);
Message headerMsg = header.unwrap();
for (String comment : param.comments) {
headerMsg.addComment(comment);
}
return headerMsg;
} | java |
public ViewSelection selectViews(View view) {
ViewSelection result = new ViewSelection();
for (List<Selector> selectorParts : selectorGroups) {
result.addAll(selectViewsForGroup(selectorParts, view));
}
return result;
} | java |
@Override
public int compareTo(final Problem o) {
final int ix = this.severity.ordinal();
final int oid = o.severity.ordinal();
return ix - oid;
} | java |
public static String fixValue(String value) {
if (value != null && !value.equals("")) {
final String[] words = value.toLowerCase().split("_");
value = "";
for (final String word : words) {
if (word.length() > 1) {
value += word.substring(0, 1).toUpperCase() + word.substring(1) + " ";
} else {
value = word;
}
}
}
if (value.contains("\\n")) {
value = value.replace("\\n", System.getProperty("line.separator"));
}
return value;
} | java |
public static String removeLast(String original, String string) {
int lastIndexOf = original.lastIndexOf(string);
if (lastIndexOf == -1) {
return original;
}
return original.substring(0, lastIndexOf);
} | java |
public static String getFirstLine(final String message) {
if (isEmpty(message)) {
return message;
}
if (message.contains("\n")) {
return message.split("\n")[0];
}
return message;
} | java |
public static void copyToClipboard(String text) {
final StringSelection stringSelection = new StringSelection(text);
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, stringSelection);
} | java |
public String toQueryString() {
final StringBuffer buf = new StringBuffer();
final Object value1 = this.values.get(0);
buf.append(this.column.getName());
switch (this.type) {
case STARTS_WIDTH:
buf.append(" like '" + value1 + "%'");
break;
case CONTAINS:
buf.append(" like '%" + value1 + "%'");
break;
case ENDS_WITH:
buf.append(" like '%" + value1 + "'");
break;
case DOESNOT_CONTAINS:
buf.append(" not like '%" + value1 + "%'");
break;
case MORE_THAN:
buf.append(" > '" + value1 + "'");
break;
case LESS_THAN:
buf.append(" < '" + value1 + "'");
break;
}
return buf.toString();
} | java |
public static String getNaturalAnalogueSequence(PolymerNotation polymer) throws HELM2HandledException, PeptideUtilsException, ChemistryException {
checkPeptidePolymer(polymer);
return FastaFormat.generateFastaFromPeptide(MethodsMonomerUtils.getListOfHandledMonomers(polymer.getListMonomers()));
} | java |
public static String getSequence(PolymerNotation polymer) throws HELM2HandledException, PeptideUtilsException, ChemistryException{
checkPeptidePolymer(polymer);
StringBuilder sb = new StringBuilder();
List<Monomer> monomers = MethodsMonomerUtils.getListOfHandledMonomers(polymer.getListMonomers());
for (Monomer monomer : monomers) {
String id = monomer.getAlternateId();
if (id.length() > 1) {
id = "[" + id + "]";
}
sb.append(id);
}
return sb.toString();
} | java |
private static void processOtherMappings() {
codeToJavaMapping.clear();
codeToJKTypeMapping.clear();
shortListOfJKTypes.clear();
Set<Class<?>> keySet = javaToCodeMapping.keySet();
for (Class<?> clas : keySet) {
List<Integer> codes = javaToCodeMapping.get(clas);
for (Integer code : codes) {
codeToJavaMapping.put(code, clas);
logger.debug(" Code ({}) class ({}) name ({})", code, clas.getSimpleName(), namesMapping.get(code));
codeToJKTypeMapping.put(code, new JKType(code, clas, namesMapping.get(code)));
}
shortListOfJKTypes.add(new JKType(codes.get(0), clas, namesMapping.get(codes.get(0))));
}
} | java |
protected void loadDefaultConfigurations() {
if (JK.getURL(DEFAULT_LABLES_FILE_NAME) != null) {
logger.debug("Load default lables from : " + DEFAULT_LABLES_FILE_NAME);
addLables(JKIOUtil.readPropertiesFile(DEFAULT_LABLES_FILE_NAME));
}
} | java |
public static <T> T cloneBean(final Object bean) {
try {
return (T) BeanUtils.cloneBean(bean);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
} | java |
public static Class<?> getClass(final String beanClassName) {
try {
return Class.forName(beanClassName);
} catch (final ClassNotFoundException e) {
throw new RuntimeException(e);
}
} | java |
public static <T> T getPropertyValue(final Object instance, final String fieldName) {
try {
return (T) PropertyUtils.getProperty(instance, fieldName);
} catch (final Exception e) {
throw new RuntimeException(e);
}
} | java |
public static boolean isBoolean(final Class type) {
if (Boolean.class.isAssignableFrom(type)) {
return true;
}
return type.getName().equals("boolean");
} | java |
public static void setPeopertyValue(final Object target, final String fieldName, Object value) {
JK.logger.trace("setPeopertyValue On class({}) on field ({}) with value ({})", target, fieldName, value);
try {
if (value != null) {
Field field = getFieldByName(target.getClass(), fieldName);
if (field.getType().isEnum()) {
Class<? extends Enum> clas = (Class) field.getType();
value = Enum.valueOf(clas, value.toString());
JK.logger.debug("Field is enum, new value is ({}) for class ({})", value, value.getClass());
}
}
PropertyUtils.setNestedProperty(target, fieldName, value);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public static void addItemToList(final Object target, final String fieldName, final Object value) {
try {
List list = (List) getFieldValue(target, fieldName);
list.add(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java |
public static Class<?> toClass(final String name) {
try {
return Class.forName(name);
} catch (final ClassNotFoundException e) {
throw new RuntimeException(e);
}
} | java |
public static Class<?>[] toClassesFromObjects(final Object[] params) {
final Class<?>[] classes = new Class<?>[params.length];
int i = 0;
for (final Object object : params) {
if (object != null) {
classes[i++] = object.getClass();
} else {
classes[i++] = Object.class;
}
}
return classes;
} | java |
public static boolean isMethodDirectlyExists(Object object, String methodName, Class<?>... params) {
try {
Method method = object.getClass().getDeclaredMethod(methodName, params);
return true;
} catch (NoSuchMethodException e) {
return false;
} catch (SecurityException e) {
throw new RuntimeException(e);
}
} | java |
public static Object toObject(final String xml) {
// XStream x = createXStream();
// return x.fromXML(xml);
// try {
final ByteArrayInputStream out = new ByteArrayInputStream(xml.getBytes());
final XMLDecoder encoder = new XMLDecoder(out);
final Object object = encoder.readObject();
//
encoder.close();
return object;
// } catch (Exception e) {
// System.err.println("Failed to decode object : \n" + xml);
// return null;
// }
// return null;
} | java |
public static <T> Class<? extends T> getGenericParamter(String handler) {
ParameterizedType parameterizedType = (ParameterizedType) JKObjectUtil.getClass(handler).getGenericInterfaces()[0];
Class<? extends T> clas = (Class<? extends T>) (parameterizedType.getActualTypeArguments()[0]);
return clas;
} | java |
public static boolean isClassAvilableInClassPath(String string) {
try {
Class.forName(string);
return true;
} catch (ClassNotFoundException e) {
return false;
}
} | java |
public static <T> String getInstanceVariables(Class<T> clas) {
StringBuffer fieldsString = new StringBuffer();
Field[] fields = clas.getDeclaredFields();
int i = 0;
for (Field field : fields) {
if (i++ > 0) {
fieldsString.append(JK.CSV_SEPARATOR);
}
fieldsString.append(field.getName());
}
return fieldsString.toString();
} | java |
public static String toJson(Object obj) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.writeValueAsString(obj);
} catch (IOException e) {
JK.throww(e);
return null;
}
} | java |
public static <T> Object jsonToObject(String json, Class<T> clas) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readValue(json, clas);
} catch (IOException e) {
JK.throww(e);
return null;
}
} | java |
public static String getFieldNameByType(Class<?> classType, Class<?> fieldType) {
Field[] declaredFields = classType.getDeclaredFields();
for (Field field : declaredFields) {
if (field.getType().isAssignableFrom(fieldType)) {
return field.getName();
}
}
if (classType.getSuperclass() != null) {
return getFieldNameByType(classType.getSuperclass(), fieldType);
}
return null;
} | java |
public static boolean isFieldExists(Class<?> clas, String fieldName) {
Field[] fields = clas.getDeclaredFields();
for (Field field : fields) {
if (field.getName().equals(fieldName)) {
return true;
}
}
if (clas.getSuperclass() != null) {
return isFieldExists(clas.getSuperclass(), fieldName);
}
return false;
} | java |
public static List<String> getAllClassesInPackage(String packageName) {
List<String> classesNames = new Vector<>();
// create scanner and disable default filters (that is the 'false' argument)
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
// add include filters which matches all the classes (or use your own)
provider.addIncludeFilter(new RegexPatternTypeFilter(Pattern.compile(".*")));
// get matching classes defined in the package
final Set<BeanDefinition> classes = provider.findCandidateComponents(packageName);
// this is how you can load the class type from BeanDefinition instance
for (BeanDefinition bean : classes) {
classesNames.add(bean.getBeanClassName());
}
return classesNames;
} | java |
public static List<Field> getAllFields(Class<?> clas) {
JK.fixMe("add caching..");
List<Field> list = new Vector<>();
// start by fields from the super class
if (clas.getSuperclass() != null) {
list.addAll(getAllFields(clas.getSuperclass()));
}
Field[] fields = clas.getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())) {
list.add(field);
}
}
return list;
} | java |
public static <T> T createInstanceForGenericClass(Object parent) {
try {
Object instance = getGenericClassFromParent(parent).newInstance();
return (T) instance;
} catch (InstantiationException | IllegalAccessException e) {
JK.throww(e);
}
return null;
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.