language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java | @Data
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Builder
@Table(name = "invoices")
public class Invoice {
@org.springframework.data.annotation.Id
@javax.persistence.Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
@Schema(
name = "invoice_id",
description = "The globally unique identifier of the invoice",
example = "589",
required = true)
@JsonProperty("invoice_id")
@Column(name = "invoice_id", nullable = false)
private String invoiceId;
@JsonProperty("invoice_amount")
@Column(name = "invoice_amount", nullable = false)
@Schema(
name = "invoice_amount",
description = "The amount in the currency due.",
example = "100.000000",
required = true)
private String invoiceAmount;
@JsonProperty("amount_paid")
@Column(name = "amount_paid", nullable = false)
@Schema(
name = "amount_paid",
description = "The amount paid to date",
example = "0.000000",
required = true)
private String amountPaid;
@JsonProperty("amount_remaining")
@Column(name = "amount_remaining", nullable = false)
@Schema(
name = "amount_remaining",
description = "The amount remaining to be paid",
example = "100.000000",
required = true)
private String amountRemaining;
@JsonProperty("crypto_address")
@Column(name = "crypto_address", nullable = false)
@Schema(
name = "crypto_address",
description = "The crypto address to which the amount due should be paid",
example = "r9JuxGPccGjMGr54t4JXUDsemAcECQWXTf",
required = true)
private String cryptoAddress;
@JsonProperty("currency")
@Column(name = "currency", nullable = false)
@Schema(
name = "currency",
description = "The currency of the invoice",
example = "XRP",
required = true)
private String currency;
@JsonProperty("chain")
@Column(name = "chain", nullable = false)
@Schema(
name = "chain",
description = "The identifier of the blockchain.",
example = "XRPL",
required = true)
private String chain;
@JsonProperty("chain_environment")
@Column(name = "chain_environment", nullable = true)
@Schema(
name = "chain_environment",
description = "Some block chains support multiple environments. Specify that here.",
example = "TESTNET",
required = false)
private String chainEnvironment;
@JsonProperty("invoice_status")
@Column(name = "invoice_status", nullable = false)
@Schema(
name = "invoice_status",
description = "The status of the invoice",
example = "NEW",
required = true)
private InvoiceStatus invoiceStatus;
@JsonProperty("due_date")
@Column(name = "due_date", nullable = false)
@Schema(
name = "due_date",
description = "The due date of the invoice",
example = "2021-03-17T12:42:59.663Z",
required = true)
private Instant dueDate;
} |
Java | public class Tag {
// Identity fields
private final TagName tagName;
// Data fields
private final FileAddress fileAddress;
private final Set<Label> labels = new HashSet<>();
/**
* Every field must be present and not null.
*/
public Tag(TagName tagName, FileAddress fileAddress, Set<Label> labels) {
requireAllNonNull(tagName, fileAddress, labels);
this.tagName = tagName;
this.fileAddress = fileAddress;
this.labels.addAll(labels);
}
public TagName getTagName() {
return tagName;
}
public FileAddress getFileAddress() {
return fileAddress;
}
public Set<Label> getLabels() {
return Collections.unmodifiableSet(labels);
}
/**
* Converts the current tag to one with absolute address.
*
* @return The same tag but with absolute file address.
* @throws IllegalArgumentException If file does not exist.
*/
public Tag toAbsolute(boolean isAbsolutePath, FileAddress currentPath) {
File file;
if (isAbsolutePath) {
file = new File(fileAddress.value);
} else {
file = new File(currentPath.value, fileAddress.value);
}
if (!file.exists()) {
throw new IllegalArgumentException("Tag address not valid!");
}
FileAddress absAddress;
try {
absAddress = new FileAddress(Paths.get(file.getCanonicalPath()).normalize().toString());
} catch (IOException e) {
throw new IllegalArgumentException("Tag address not found!");
}
return new Tag(tagName, absAddress, labels);
}
/**
* Returns true if both persons of the same name have at least one other identity field that is the same.
* This defines a weaker notion of equality between two persons.
*/
public boolean isSameTag(Tag otherTag) {
if (otherTag == this) {
return true;
}
return otherTag != null
&& otherTag.getTagName().equals(getTagName());
}
/**
* Returns true if both tag have the same identity and data fields.
* This defines a stronger notion of equality between two tags.
*/
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (!(other instanceof Tag)) {
return false;
}
Tag otherTag = (Tag) other;
return otherTag.getTagName().equals(getTagName())
&& otherTag.getFileAddress().equals(getFileAddress())
&& otherTag.getLabels().equals(getLabels());
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(tagName, fileAddress, labels);
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(getTagName())
.append("\nFileAddress: ")
.append(getFileAddress())
.append("\nLabels: ");
getLabels().forEach((label) -> builder.append(label.getLabel() + ", "));
builder.delete(builder.length() - 2, builder.length());
return builder.toString();
}
} |
Java | public class ValidateStatusProblematicSurgicalWound extends AbstractClinicalItemValidator implements RecordItemValidatorIF {
/**
* returns the edit list
*
* @return non-null list of edits for this validator
*/
public List<OasisEditIF> getEditIdsUsed() {
return super.getEditIdsUsed_base(OasisEditsEN.EDIT_3060, OasisEditsEN.EDIT_4240, OasisEditsEN.EDIT_4250);
}
public int validate(HomeHealthRecordIF record, CollectionValidationEditsIF edits) {
int count = 0;
if (ValidateUtils.isValidValue(record.getASSMT_REASON(), AbstractItemValidator.ASSESSMENT_1_3_4_5_9_ONLY)) {
final String surgPresent = record.getSRGCL_WND_PRSNT();
final String statSurg = record.getSTUS_PRBLM_SRGCL_WND();
if (!ValidateUtils.isValidValue(statSurg,
ValidateUtils.ARRAY_DOUBLE_0,
ValidateUtils.ARRAY_DOUBLE_1,
ValidateUtils.ARRAY_DOUBLE_2,
ValidateUtils.ARRAY_DOUBLE_3,
ValidateUtils.ARRAY_CARET_VALUES)) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_3060,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1342_STUS_PRBLM_SRGCL_WND, statSurg)));
}
if (ValidateUtils.isValidValue(surgPresent, ValidateUtils.ARRAY_DOUBLE_1)) {
// if there is an observable surgical wound, then
// the status can not be blank/^
if (ValidateUtils.isValidValue(statSurg, ValidateUtils.ARRAY_CARET_VALUES)) {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4250,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1340_SRGCL_WND_PRSNT, surgPresent)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4250,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1342_STUS_PRBLM_SRGCL_WND, surgPresent)));
}
} else if (ValidateUtils.isValidValue(surgPresent, ValidateUtils.ARRAY_DOUBLE_0, ValidateUtils.ARRAY_DOUBLE_2)) {
if (!ValidateUtils.isValidValue(statSurg, ValidateUtils.ARRAY_CARET_VALUES)) {
// if there is no or unobservable surgical wound,
// then the status must be blank
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4240,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1340_SRGCL_WND_PRSNT, surgPresent)));
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_4240,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1342_STUS_PRBLM_SRGCL_WND, surgPresent)));
}
} else {
count++;
edits.add(new OasisValidationEdit(OasisEditsEN.EDIT_3060,
new HHOasisDataItem(HomeHealthRecord_C1_IF.OASIS_C1_ITEM_M1340_SRGCL_WND_PRSNT, surgPresent)));
}
}
return count;
}
/**
* Gets the description
*
* @return non-null string
*/
@Override
public String getDescription() {
return "Validates Status Problematic Surgical Wound for edits: 3060, 4240, 4250";
}
} |
Java | public class SearchPrototypeEventHandlerFactory implements WorkspaceEventListenerFactory {
//TODO RESKE JAVADOC
//TODO RESKE TEST
@Override
public WorkspaceEventListener configure(final Map<String, String> cfg)
throws ListenerInitializationException {
//TODO RESKE may need more opts for sharding
final String mongoHost = cfg.get("mongohost");
final String mongoDatabase = cfg.get("mongodatabase");
String mongoUser = cfg.get("mongouser");
if (mongoUser == null || mongoUser.trim().isEmpty()) {
mongoUser = null;
}
final String mongoPwd = cfg.get("mongopwd");
LoggerFactory.getLogger(getClass()).info("Starting Search Prototype event handler. " +
"mongohost={} mongodatabase={} mongouser={}", mongoHost, mongoDatabase, mongoUser);
return new SearthPrototypeEventHandler(mongoHost, mongoDatabase, mongoUser, mongoPwd);
}
public class SearthPrototypeEventHandler implements WorkspaceEventListener {
private static final String TRUE = "true";
private static final String IS_TEMP_NARRATIVE = "is_temporary";
private static final String NARRATIVE_TYPE = "KBaseNarrative.Narrative";
private static final String DATA_SOURCE = "WS";
private static final String NEW_OBJECT_VER = "NEW_VERSION";
private static final String NEW_OBJECT = "NEW_ALL_VERSIONS";
private static final String CLONED_WORKSPACE = "COPY_ACCESS_GROUP";
private static final String RENAME_OBJECT = "RENAME_ALL_VERSIONS";
private static final String DELETE_OBJECT = "DELETE_ALL_VERSIONS";
private static final String UNDELETE_OBJECT = "UNDELETE_ALL_VERSIONS";
private static final String DELETE_WS = "DELETE_ACCESS_GROUP";
private static final String SET_GLOBAL_READ = "PUBLISH_ACCESS_GROUP";
private static final String REMOVE_GLOBAL_READ = "UNPUBLISH_ACCESS_GROUP";
// this might need to be configurable
private static final String COLLECTION = "searchEvents";
private final DB db;
public SearthPrototypeEventHandler(
final String mongoHost,
final String mongoDatabase,
String mongoUser,
final String mongoPwd)
throws ListenerInitializationException {
//TODO RESKE check args
if (mongoUser == null || mongoUser.trim().isEmpty()) {
mongoUser = null;
}
try {
if (mongoUser == null) {
db = GetMongoDB.getDB(mongoHost, mongoDatabase, 0, 10);
} else {
db = GetMongoDB.getDB(mongoHost, mongoDatabase, mongoUser, mongoPwd, 0, 10);
}
} catch (InterruptedException ie) {
throw new ListenerInitializationException(
"Connection to MongoDB was interrupted. This should never "
+ "happen and indicates a programming problem. Error: " +
ie.getLocalizedMessage(), ie);
} catch (UnknownHostException uhe) {
throw new ListenerInitializationException("Couldn't find mongo host "
+ mongoHost + ": " + uhe.getLocalizedMessage(), uhe);
} catch (IOException | MongoTimeoutException e) {
throw new ListenerInitializationException("Couldn't connect to mongo host "
+ mongoHost + ": " + e.getLocalizedMessage(), e);
} catch (MongoException e) {
throw new ListenerInitializationException(
"There was an error connecting to the mongo database: " +
e.getLocalizedMessage());
} catch (MongoAuthException ae) {
throw new ListenerInitializationException("Not authorized for mongo database "
+ mongoHost + ": " + ae.getLocalizedMessage(), ae);
} catch (InvalidHostException ihe) {
throw new ListenerInitializationException(mongoHost +
" is an invalid mongo database host: " +
ihe.getLocalizedMessage(), ihe);
}
}
@Override
public void createWorkspace(final long id, final Instant time) {
// no action
}
@Override
public void cloneWorkspace(final long id, final boolean isPublic, final Instant time) {
newWorkspaceEvent(id, CLONED_WORKSPACE, isPublic, time);
}
@Override
public void setWorkspaceMetadata(final long id, final Instant time) {
// no action
}
@Override
public void lockWorkspace(final long id, final Instant time) {
// no action
}
@Override
public void renameWorkspace(final long id, final String newname, final Instant time) {
// no action
}
@Override
public void setGlobalPermission(final long id, final Permission perm, final Instant time) {
newWorkspaceEvent(id, Permission.READ.equals(perm) ?
SET_GLOBAL_READ : REMOVE_GLOBAL_READ, null, time);
}
@Override
public void setPermissions(
final long id,
final Permission permission,
final List<WorkspaceUser> users,
final Instant time) {
// no action
}
@Override
public void setWorkspaceDescription(final long id, final Instant time) {
// no action
}
@Override
public void setWorkspaceOwner(
final long id,
final WorkspaceUser newUser,
final Optional<String> newName,
final Instant time) {
// no action
}
@Override
public void setWorkspaceDeleted(
final long id,
final boolean delete,
final long maxObjectID,
final Instant time) {
if (delete) {
newEvent(id, maxObjectID, null, null, null, DELETE_WS, null, time);
} else {
LoggerFactory.getLogger(getClass()).info(
"Workspace {} was undeleted. Workspace undeletion events are not " +
"supported by KBase Search", id);
}
}
@Override
public void renameObject(
final long workspaceId,
final long objectId,
final String newName,
final Instant time) {
newEvent(workspaceId, objectId, null, newName, null, RENAME_OBJECT, null, time);
}
@Override
public void revertObject(final ObjectInformation oi, final boolean isPublic) {
newVersionEvent(oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(),
oi.getTypeString(), isPublic, oi.getSavedDate().toInstant());
}
@Override
public void setObjectDeleted(
final long workspaceId,
final long objectId,
final boolean delete,
final Instant time) {
newEvent(workspaceId, objectId, null, null, null,
delete ? DELETE_OBJECT : UNDELETE_OBJECT, null, time);
}
@Override
public void copyObject(final ObjectInformation oi, final boolean isPublic) {
newVersionEvent(oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(),
oi.getTypeString(), isPublic, oi.getSavedDate().toInstant());
}
@Override
public void copyObject(
final long workspaceId,
final long objectId,
final int latestVersion,
final Instant time,
final boolean isPublic) {
newObjectEvent(workspaceId, objectId, isPublic, time);
}
@Override
public void saveObject(final ObjectInformation oi, final boolean isPublic) {
if (oi.getTypeString().startsWith(NARRATIVE_TYPE) &&
TRUE.equals(oi.getUserMetaData().getMetadata().get(IS_TEMP_NARRATIVE))) {
return;
}
newVersionEvent(oi.getWorkspaceId(), oi.getObjectId(), oi.getVersion(),
oi.getTypeString(), isPublic, oi.getSavedDate().toInstant());
}
private void newObjectEvent(
final long workspaceId,
final long objectId,
final boolean isPublic,
final Instant time) {
newEvent(workspaceId, objectId, null, null, null, NEW_OBJECT, isPublic, time);
}
private void newVersionEvent(
final long workspaceId,
final long objectId,
final Integer version,
final String type,
final boolean isPublic,
final Instant time) {
newEvent(workspaceId, objectId, version, null, type, NEW_OBJECT_VER, isPublic, time);
}
private void newWorkspaceEvent(
final long workspaceId,
final String eventType,
final Boolean isPublic,
final Instant time) {
newEvent(workspaceId, null, null, null, null, eventType, isPublic, time);
}
private void newEvent(
final long workspaceId,
final Long objectId,
final Integer version,
final String newName,
final String type,
final String eventType,
final Boolean isPublic,
final Instant time) {
if (!wsidOK(workspaceId)) {
return;
}
final DBObject dobj = new BasicDBObject();
dobj.put("strcde", DATA_SOURCE);
dobj.put("accgrp", (int) workspaceId);
dobj.put("objid", objectId == null ? null : "" + objectId);
dobj.put("ver", version);
dobj.put("newname", newName);
dobj.put("time", Date.from(time));
dobj.put("evtype", eventType);
dobj.put("objtype", type == null ? null : type.split("-")[0]);
dobj.put("objtypever", type == null ?
null : Integer.parseInt(type.split("-")[1].split("\\.")[0]));
dobj.put("public", isPublic);
dobj.put("status", "UNPROC");
try {
db.getCollection(COLLECTION).insert(dobj);
} catch (MongoException me) {
LoggerFactory.getLogger(getClass()).error(String.format(
"RESKE save %s/%s/%s: Failed to connect to MongoDB",
workspaceId, objectId, version), me);
}
}
private boolean wsidOK(final long workspaceId) {
if (workspaceId > Integer.MAX_VALUE) {
LoggerFactory.getLogger(getClass()).error(
"Workspace id {} is out of int range. Cannot send data to KBase Search",
workspaceId);
return false;
}
return true;
}
}
} |
Java | public final class SdkTracerProvider implements TracerProvider, Closeable {
private static final Logger logger = Logger.getLogger(SdkTracerProvider.class.getName());
static final String DEFAULT_TRACER_NAME = "";
private final TracerSharedState sharedState;
private final ComponentRegistry<SdkTracer> tracerSdkComponentRegistry;
/**
* Returns a new {@link SdkTracerProviderBuilder} for {@link SdkTracerProvider}.
*
* @return a new {@link SdkTracerProviderBuilder} for {@link SdkTracerProvider}.
*/
public static SdkTracerProviderBuilder builder() {
return new SdkTracerProviderBuilder();
}
SdkTracerProvider(
Clock clock,
IdGenerator idsGenerator,
Resource resource,
Supplier<SpanLimits> spanLimitsSupplier,
Sampler sampler,
List<SpanProcessor> spanProcessors) {
this.sharedState =
new TracerSharedState(
clock, idsGenerator, resource, spanLimitsSupplier, sampler, spanProcessors);
this.tracerSdkComponentRegistry =
new ComponentRegistry<>(
instrumentationLibraryInfo -> new SdkTracer(sharedState, instrumentationLibraryInfo));
}
@Override
public Tracer get(String instrumentationName) {
return tracerBuilder(instrumentationName).build();
}
@Override
public Tracer get(String instrumentationName, String instrumentationVersion) {
return tracerBuilder(instrumentationName)
.setInstrumentationVersion(instrumentationVersion)
.build();
}
@Override
public TracerBuilder tracerBuilder(@Nullable String instrumentationName) {
// Per the spec, both null and empty are "invalid" and a default value should be used.
if (instrumentationName == null || instrumentationName.isEmpty()) {
logger.fine("Tracer requested without instrumentation name.");
instrumentationName = DEFAULT_TRACER_NAME;
}
return new SdkTracerBuilder(tracerSdkComponentRegistry, instrumentationName);
}
/** Returns the {@link SpanLimits} that are currently applied to created spans. */
public SpanLimits getSpanLimits() {
return sharedState.getSpanLimits();
}
/** Returns the configured {@link Sampler}. */
public Sampler getSampler() {
return sharedState.getSampler();
}
/**
* Attempts to stop all the activity for this {@link Tracer}. Calls {@link
* SpanProcessor#shutdown()} for all registered {@link SpanProcessor}s.
*
* <p>The returned {@link CompletableResultCode} will be completed when all the Spans are
* processed.
*
* <p>After this is called, newly created {@code Span}s will be no-ops.
*
* <p>After this is called, further attempts at re-using or reconfiguring this instance will
* result in undefined behavior. It should be considered a terminal operation for the SDK
* implementation.
*
* @return a {@link CompletableResultCode} which is completed when all the span processors have
* been shut down.
*/
public CompletableResultCode shutdown() {
if (sharedState.hasBeenShutdown()) {
logger.log(Level.WARNING, "Calling shutdown() multiple times.");
return CompletableResultCode.ofSuccess();
}
return sharedState.shutdown();
}
/**
* Requests the active span processor to process all span events that have not yet been processed
* and returns a {@link CompletableResultCode} which is completed when the flush is finished.
*
* @see SpanProcessor#forceFlush()
*/
public CompletableResultCode forceFlush() {
return sharedState.getActiveSpanProcessor().forceFlush();
}
/**
* Attempts to stop all the activity for this {@link Tracer}. Calls {@link
* SpanProcessor#shutdown()} for all registered {@link SpanProcessor}s.
*
* <p>This operation may block until all the Spans are processed. Must be called before turning
* off the main application to ensure all data are processed and exported.
*
* <p>After this is called, newly created {@code Span}s will be no-ops.
*
* <p>After this is called, further attempts at re-using or reconfiguring this instance will
* result in undefined behavior. It should be considered a terminal operation for the SDK
* implementation.
*/
@Override
public void close() {
shutdown().join(10, TimeUnit.SECONDS);
}
} |
Java | public class ProfileReportUnitTest {
private class SimpleKernel extends Kernel {
@Override
public void run() {
//Empty method intended
}
}
/**
* This test validates that all threads can start a profiling process after another thread
* that has already started profiling.
* @throws InterruptedException
* @throws Exception
*/
@Test
public void testAllThreadCanStartPass() throws IllegalStateException, InterruptedException {
final int javaThreads = ProfilingEvent.values().length;
final KernelProfile kernelProfile = new KernelProfile(SimpleKernel.class);
final KernelDeviceProfile kernelDeviceProfile = new KernelDeviceProfile(kernelProfile, SimpleKernel.class, JavaDevice.THREAD_POOL);
final AtomicInteger receivedReports = new AtomicInteger(0);
final ConcurrentSkipListSet<Long> onEventAccepted = new ConcurrentSkipListSet<Long>();
final AtomicInteger index = new AtomicInteger(0);
final long[] threadIds = new long[javaThreads + 1];
kernelProfile.setReportObserver(new IProfileReportObserver() {
@Override
public void receiveReport(Class<? extends Kernel> kernelClass, Device device, WeakReference<ProfileReport> profileInfo) {
receivedReports.incrementAndGet();
onEventAccepted.add(profileInfo.get().getThreadId());
}
});
//Ensure that the first thread as started profiling, before testing the others
kernelDeviceProfile.onEvent(ProfilingEvent.START);
List<ProfilingEvent> events = Arrays.asList(ProfilingEvent.values());
ExecutorService executorService = Executors.newFixedThreadPool(javaThreads);
try {
try {
events.forEach(evt -> {
final int idx = index.getAndIncrement();
executorService.submit(() -> {
threadIds[idx] = Thread.currentThread().getId();
kernelDeviceProfile.onEvent(ProfilingEvent.START);
kernelDeviceProfile.onEvent(ProfilingEvent.EXECUTED);
});
});
} finally {
executorService.shutdown();
if (!executorService.awaitTermination(1, TimeUnit.MINUTES)) {
executorService.shutdownNow();
throw new IllegalStateException("ExecutorService terminated abnormaly");
}
}
threadIds[index.get()] = Thread.currentThread().getId();
for (int i = 0; i < javaThreads; i++) {
assertTrue("Report wasn't received for thread with index " + i, onEventAccepted.contains(threadIds[i]));
}
assertFalse("Report was received for main thread", onEventAccepted.contains(threadIds[javaThreads]));
assertEquals("Reports from all threads should have been received", javaThreads, receivedReports.get());
//Only after this event should the main thread have received a report
kernelDeviceProfile.onEvent(ProfilingEvent.EXECUTED);
assertTrue("Report wasn't received for main thread", onEventAccepted.contains(threadIds[javaThreads]));
assertEquals("Reports from all threads should have been received", javaThreads + 1, receivedReports.get());
} finally {
kernelProfile.setReportObserver(null);
}
}
@Test
public void testGetProfilingEventsNames() {
String[] stages = ProfilingEvent.getStagesNames();
int i = 0;
for (String stage : stages) {
assertNotNull("Stage is null at index " + i, stage);
assertFalse("Stage name is empty at index " + i, stage.isEmpty());
ProfilingEvent event = ProfilingEvent.valueOf(stage);
assertTrue("Stage name does not translate to an event", event != null);
assertEquals("Stage name does match correct order", i, event.ordinal());
i++;
}
}
@Test
public void testProfileReportClone() {
final int reportId = 101;
final int threadId = 192;
final long[] values = new long[ProfilingEvent.values().length];
for (int i = 0; i < values.length; i++) {
values[i] = 900 + i;
}
ProfileReport report = new ProfileReport(threadId, SimpleKernel.class, JavaDevice.THREAD_POOL);
report.setProfileReport(reportId, values);
ProfileReport clonedReport = report.clone();
assertNotEquals("Object references shouldn't be the same", report, clonedReport);
assertEquals("Report Id doesn't match", reportId, clonedReport.getReportId());
assertEquals("Class doesn't match", SimpleKernel.class, clonedReport.getKernelClass());
assertEquals("Device doesn't match", JavaDevice.THREAD_POOL, clonedReport.getDevice());
for (int i = 0; i < values.length; i++) {
assertEquals("Values don't match for index " + i, report.getElapsedTime(i), clonedReport.getElapsedTime(i), 1e-10);
}
long[] valuesB = new long[ProfilingEvent.values().length];
for (int i = 0; i < valuesB.length; i++) {
valuesB[i] = 100 + i*100;
}
report.setProfileReport(reportId + 1, valuesB);
for (int i = 1; i < values.length; i++) {
assertNotEquals("Values match after new assingment for index " + i, report.getElapsedTime(i), clonedReport.getElapsedTime(i), 1e-10);
}
}
} |
Java | public class ATMTester
{
public static void main(String[] args)
throws IOException, SQLException, ClassNotFoundException
{
if (args.length == 0)
{
System.out.println(
"Usage: ATMTester propertiesFile");
return;
}
else
SimpleDataSource.init(args[0]);
Bank theBank = new Bank();
ATM theATM = new ATM(theBank);
Scanner in = new Scanner(System.in);
while (true)
{
int state = theATM.getState();
if (state == ATM.START)
{
System.out.print("Enter account number: ");
int number = in.nextInt();
theATM.setCustomerNumber(number);
}
else if (state == ATM.PIN)
{
System.out.print("Enter PIN: ");
int pin = in.nextInt();
theATM.selectCustomer(pin);
}
else if (state == ATM.ACCOUNT)
{
System.out.print("A=Checking, B=Savings, C=Quit: ");
String command = in.next();
if (command.equalsIgnoreCase("A"))
theATM.selectAccount(ATM.CHECKING);
else if (command.equalsIgnoreCase("B"))
theATM.selectAccount(ATM.SAVINGS);
else if (command.equalsIgnoreCase("C"))
theATM.reset();
else
System.out.println("Illegal input!");
}
else if (state == ATM.TRANSACT)
{
System.out.println("Balance=" + theATM.getBalance());
System.out.print("A=Deposit, B=Withdrawal, C=Cancel: ");
String command = in.next();
if (command.equalsIgnoreCase("A"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.deposit(amount);
theATM.back();
}
else if (command.equalsIgnoreCase("B"))
{
System.out.print("Amount: ");
double amount = in.nextDouble();
theATM.withdraw(amount);
theATM.back();
}
else if (command.equalsIgnoreCase("C"))
theATM.back();
else
System.out.println("Illegal input!");
}
}
}
} |
Java | public class EnvironmentTests_PortletRequestDispatcher_ApiRender2 implements Portlet {
private PortletConfig portletConfig = null;
private static final String HTML_PREFIX = "/WEB-INF/html/";
private static final String HTML_SUFFIX = ".html";
@Override
public void init(PortletConfig config) throws PortletException {
this.portletConfig = config;
}
@Override
public void destroy() {}
@Override
public void processAction(ActionRequest portletReq, ActionResponse portletResp)
throws PortletException, IOException {
portletResp.setRenderParameters(portletReq.getParameterMap());
long tid = Thread.currentThread().getId();
portletReq.setAttribute(THREADID_ATTR, tid);
}
@Override
public void render(RenderRequest renderReq, RenderResponse renderResp)
throws PortletException, IOException {
long tid = Thread.currentThread().getId();
renderReq.setAttribute(THREADID_ATTR, tid);
PrintWriter writer = renderResp.getWriter();
// Create result objects for the tests
PortletRequest portletReq = renderReq;
PortletResponse portletResp = renderResp;
JSR286ApiTestCaseDetails tcd = new JSR286ApiTestCaseDetails();
String tc = renderReq.getParameter(BUTTON_PARAM_NAME);
/* TestCase: V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward1 */
/* Details: "Method forward(PortletRequest, PortletResponse): Can */
/* forward to a JSP page to create the response" */
if (tc != null && tc.equals(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD1)) {
String target_tr8 = JSP_PREFIX + "V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward1" + JSP_SUFFIX
+ "?" + QUERY_STRING;
PortletRequestDispatcher rd_tr8 =
portletConfig.getPortletContext().getRequestDispatcher(target_tr8);
rd_tr8.forward(portletReq, portletResp);
} else if (tc==null) {
PortletURL rurl = renderResp.createRenderURL();
TestButton tb =
new TestButton(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD1, rurl);
tb.writeTo(writer);
}
/* TestCase: V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward2 */
/* Details: "Method forward(PortletRequest, PortletResponse): Can */
/* forward to a HTML Page to create the response" */
if (tc != null && tc.equals(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD2)) {
String target_tr9 =
HTML_PREFIX + "V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward2"
+ HTML_SUFFIX + "?" + QUERY_STRING;
PortletRequestDispatcher rd_tr9 =
portletConfig.getPortletContext().getRequestDispatcher(target_tr9);
rd_tr9.forward(portletReq, portletResp);
} else if (tc==null) {
PortletURL rurl = renderResp.createRenderURL();
TestButton tb =
new TestButton(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD2, rurl);
tb.writeTo(writer);
}
/* TestCase: V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward3 */
/* Details: "Method forward(PortletRequest, PortletResponse): Throws */
/* IllegalStateException if the response was already committed" */
if (tc != null && tc.equals(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD3)) {
TestResult tr10 =
tcd.getTestResultFailed(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD3);
String target_tr10 = SERVLET_PREFIX
+ "V2EnvironmentTests_PortletRequestDispatcher_ApiRender_PortletRequest_Forward"
+ SERVLET_SUFFIX;
PortletRequestDispatcher rd_tr10 =
portletConfig.getPortletContext().getRequestDispatcher(target_tr10);
try {
rd_tr10.forward(portletReq, portletResp);
} catch (Exception e) {
tr10.setTcSuccess(true);
tr10.appendTcDetail(e.toString());
}
tr10.writeTo(writer);
} else if (tc==null) {
PortletURL rurl = renderResp.createRenderURL();
TestButton tb =
new TestButton(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD3, rurl);
tb.writeTo(writer);
}
/* TestCase: V2EnvironmentTests_PortletRequestDispatcher_ApiRender_forward4 */
/* Details: "Method forward(PortletRequest, PortletResponse): Throws */
/* PortletException if the forwarded servlet throws any excpetion */
/* other than IOException or a runtime exception " */
if (tc != null && tc.equals(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD4)) {
TestResult tr11 =
tcd.getTestResultFailed(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD4);
String target_tr11 = SERVLET_PREFIX
+ "V2EnvironmentTests_PortletRequestDispatcher_ApiRender_PortletRequest_Forward"
+ SERVLET_SUFFIX;
PortletRequestDispatcher rd_tr11 =
portletConfig.getPortletContext().getRequestDispatcher(target_tr11);
try {
rd_tr11.forward(portletReq, portletResp);
} catch (Exception e) {
tr11.setTcSuccess(true);
tr11.appendTcDetail(e.toString());
}
tr11.writeTo(writer);
} else if (tc==null) {
PortletURL rurl = renderResp.createRenderURL();
TestButton tb =
new TestButton(V2ENVIRONMENTTESTS_PORTLETREQUESTDISPATCHER_APIRENDER_FORWARD4, rurl);
tb.writeTo(writer);
}
}
} |
Java | public class DiffCommand extends GitCommand<List<DiffEntry>> {
private AbstractTreeIterator oldTree;
private AbstractTreeIterator newTree;
private boolean cached;
private TreeFilter pathFilter = TreeFilter.ALL;
private boolean showNameAndStatusOnly;
private OutputStream out;
private int contextLines = -1;
private String sourcePrefix;
private String destinationPrefix;
private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
/**
* Constructor for DiffCommand
*
* @param repo
* a {@link org.eclipse.jgit.lib.Repository} object.
*/
protected DiffCommand(Repository repo) {
super(repo);
}
private DiffFormatter getDiffFormatter() {
return out != null && !showNameAndStatusOnly
? new DiffFormatter(new BufferedOutputStream(out))
: new DiffFormatter(NullOutputStream.INSTANCE);
}
/**
* {@inheritDoc}
* <p>
* Executes the {@code Diff} command with all the options and parameters
* collected by the setter methods (e.g. {@link #setCached(boolean)} of this
* class. Each instance of this class should only be used for one invocation
* of the command. Don't call this method twice on an instance.
*/
@Override
public List<DiffEntry> call() throws GitAPIException {
try (DiffFormatter diffFmt = getDiffFormatter()) {
diffFmt.setRepository(repo);
diffFmt.setProgressMonitor(monitor);
if (cached) {
if (oldTree == null) {
ObjectId head = repo.resolve(HEAD + "^{tree}"); //$NON-NLS-1$
if (head == null)
throw new NoHeadException(JGitText.get().cannotReadTree);
CanonicalTreeParser p = new CanonicalTreeParser();
try (ObjectReader reader = repo.newObjectReader()) {
p.reset(reader, head);
}
oldTree = p;
}
newTree = new DirCacheIterator(repo.readDirCache());
} else {
if (oldTree == null)
oldTree = new DirCacheIterator(repo.readDirCache());
if (newTree == null)
newTree = new FileTreeIterator(repo);
}
diffFmt.setPathFilter(pathFilter);
List<DiffEntry> result = diffFmt.scan(oldTree, newTree);
if (showNameAndStatusOnly)
return result;
else {
if (contextLines >= 0)
diffFmt.setContext(contextLines);
if (destinationPrefix != null)
diffFmt.setNewPrefix(destinationPrefix);
if (sourcePrefix != null)
diffFmt.setOldPrefix(sourcePrefix);
diffFmt.format(result);
diffFmt.flush();
return result;
}
} catch (IOException e) {
throw new JGitInternalException(e.getMessage(), e);
}
}
/**
* Whether to view the changes staged for the next commit
*
* @param cached
* whether to view the changes staged for the next commit
* @return this instance
*/
public DiffCommand setCached(boolean cached) {
this.cached = cached;
return this;
}
/**
* Set path filter
*
* @param pathFilter
* parameter, used to limit the diff to the named path
* @return this instance
*/
public DiffCommand setPathFilter(TreeFilter pathFilter) {
this.pathFilter = pathFilter;
return this;
}
/**
* Set old tree
*
* @param oldTree
* the previous state
* @return this instance
*/
public DiffCommand setOldTree(AbstractTreeIterator oldTree) {
this.oldTree = oldTree;
return this;
}
/**
* Set new tree
*
* @param newTree
* the updated state
* @return this instance
*/
public DiffCommand setNewTree(AbstractTreeIterator newTree) {
this.newTree = newTree;
return this;
}
/**
* Set whether to return only names and status of changed files
*
* @param showNameAndStatusOnly
* whether to return only names and status of changed files
* @return this instance
*/
public DiffCommand setShowNameAndStatusOnly(boolean showNameAndStatusOnly) {
this.showNameAndStatusOnly = showNameAndStatusOnly;
return this;
}
/**
* Set output stream
*
* @param out
* the stream to write line data
* @return this instance
*/
public DiffCommand setOutputStream(OutputStream out) {
this.out = out;
return this;
}
/**
* Set number of context lines instead of the usual three.
*
* @param contextLines
* the number of context lines
* @return this instance
*/
public DiffCommand setContextLines(int contextLines) {
this.contextLines = contextLines;
return this;
}
/**
* Set the given source prefix instead of "a/".
*
* @param sourcePrefix
* the prefix
* @return this instance
*/
public DiffCommand setSourcePrefix(String sourcePrefix) {
this.sourcePrefix = sourcePrefix;
return this;
}
/**
* Set the given destination prefix instead of "b/".
*
* @param destinationPrefix
* the prefix
* @return this instance
*/
public DiffCommand setDestinationPrefix(String destinationPrefix) {
this.destinationPrefix = destinationPrefix;
return this;
}
/**
* The progress monitor associated with the diff operation. By default, this
* is set to <code>NullProgressMonitor</code>
*
* @see NullProgressMonitor
* @param monitor
* a progress monitor
* @return this instance
*/
public DiffCommand setProgressMonitor(ProgressMonitor monitor) {
if (monitor == null) {
monitor = NullProgressMonitor.INSTANCE;
}
this.monitor = monitor;
return this;
}
} |
Java | public class Goblinese extends StdLanguage
{
@Override
public String ID()
{
return "Goblinese";
}
private final static String localizedName = CMLib.lang().L("Goblinese");
@Override
public String name()
{
return localizedName;
}
public static List<String[]> wordLists=null;
public Goblinese()
{
super();
}
@Override
public List<String[]> translationLists(final String language)
{
if(wordLists==null)
{
final String[] one={"i","klpt","ih","g"};
final String[] two={"te","il","ag","go"};
final String[] three={"nik","rem","tit","nip","pop","pon","ipi","wip","pec"};
final String[] four={"perp","merp","nerp","pein","noog","gobo","koer","werp","terp","tert","grlt","Jrl","gran","kert"};
final String[] five={"whamb","thwam","nipgo","pungo","upoin","krepe","tungo","pongo","twang","hrgap","splt","krnch","baam","poww"};
final String[] six={"tawthak","krsplt","palpep","poopoo","dungdung","owwie","greepnak","tengak","grnoc","pisspiss","phlyyytt","plllb","hrangnok","ticktick","nurang"};
wordLists=new Vector<String[]>();
wordLists.add(one);
wordLists.add(two);
wordLists.add(three);
wordLists.add(four);
wordLists.add(five);
wordLists.add(six);
}
return wordLists;
}
private static final Hashtable<String,String> hashwords=new Hashtable<String,String>();
@Override
public Map<String, String> translationHash(final String language)
{
if((hashwords!=null)&&(hashwords.size()>0))
return hashwords;
hashwords.put("0","di");
hashwords.put("A","ah");
hashwords.put("ABLE","gafnahkk");
hashwords.put("ABOUT","bah");
hashwords.put("ABOVE","hat");
hashwords.put("ACCORDING","gi");
hashwords.put("AGAIN","vi");
hashwords.put("AGREE","yoess");
hashwords.put("ALIVE","gongki");
hashwords.put("ALL","jay");
hashwords.put("ALRIGHT","yoess");
hashwords.put("RIGHT","yoess");
hashwords.put("ALLIANCE","zmat'him");
hashwords.put("ALLY","zmat");
hashwords.put("ALONGSIDE","kho");
hashwords.put("ALSO","dok");
hashwords.put("AM","ko");
hashwords.put("AND","tw");
hashwords.put("ANIMAL","achi");
hashwords.put("ANYONE","chay");
hashwords.put("ANYTHING","chez");
hashwords.put("APPRENTICE","podri");
hashwords.put("ARE","ko");
hashwords.put("AREA","rrey");
hashwords.put("AS","gon");
hashwords.put("ASK","banrahk");
hashwords.put("ASSIST","pod");
hashwords.put("ASSISTANCE","podum");
hashwords.put("ASSISTANT","podri");
hashwords.put("AT","hm");
hashwords.put("BACK","let");
hashwords.put("BAD","neo");
hashwords.put("BATTLE","znavo");
hashwords.put("BAY","relah");
hashwords.put("BE","kok");
hashwords.put("BEAST","achi");
hashwords.put("BECAUSE","ckhw");
hashwords.put("BECOME","kok");
hashwords.put("BEFRIEND","zmat");
hashwords.put("BEGIN","plint");
hashwords.put("BEGINNING","plin");
hashwords.put("BEHIND","let");
hashwords.put("BELOW","get");
hashwords.put("BENEATH","get");
hashwords.put("BIG","loakh");
hashwords.put("BLACK","eske");
hashwords.put("BLEED","gurr");
hashwords.put("BLOOD","gurrde");
hashwords.put("BLUE","meh");
hashwords.put("BOTTOM","get");
hashwords.put("BRIGHT","epli");
hashwords.put("BROTHER","kokihn");
hashwords.put("BROWN","ikm");
hashwords.put("BUT","vw");
hashwords.put("BY","gi");
hashwords.put("BYE","dzo");
hashwords.put("CAN","gafnahkk");
hashwords.put("CAST","uvoj");
hashwords.put("CHIEF","kore");
hashwords.put("COME","ling");
hashwords.put("RETURN","umkloer");
hashwords.put("COMMON","mantan");
hashwords.put("TONGUE","mantan");
hashwords.put("COMPLICATED","efichi");
hashwords.put("CONCEDE","yoess");
hashwords.put("CONCEPT","ezo");
hashwords.put("CURE","vuor");
hashwords.put("CURIOUS","blomgreh");
hashwords.put("DARK","eske");
hashwords.put("DARKNESS","eske");
hashwords.put("DAUGHTER","getrihn");
hashwords.put("DAY","hn");
hashwords.put("DEAD","kurri");
hashwords.put("DEATH","kurrte");
hashwords.put("DEEP","legin");
hashwords.put("DIE","kurr");
hashwords.put("DIFFICULT","efichi");
hashwords.put("DIRECT","noreyg");
hashwords.put("DIRT","shikm");
hashwords.put("DISCOVER","kurflig");
hashwords.put("DO","uft");
hashwords.put("DWARF","dahrfw");
hashwords.put("EASY","imshi");
hashwords.put("EAT","chip");
hashwords.put("ELF","elfw");
hashwords.put("END","skeh");
hashwords.put("ENEMY","neot'h");
hashwords.put("ENJOY","gyur");
hashwords.put("ENTER","ling");
hashwords.put("ENTRANCE","lin");
hashwords.put("ENTRUST","obranyuj");
hashwords.put("EVERYONE","jay");
hashwords.put("EVERYTHING","jez");
hashwords.put("EXIT","keh");
hashwords.put("FAERY","feyri");
hashwords.put("FAIL","poep");
hashwords.put("FAR","eysah");
hashwords.put("FAT","nerri");
hashwords.put("FATHER","hatkihn");
hashwords.put("FAVOR","rekyom");
hashwords.put("FEATHER","pwm");
hashwords.put("FEMALE","rihn");
hashwords.put("FIGHT","znav");
hashwords.put("FIND","kurflig");
hashwords.put("FINISH","sket");
hashwords.put("FIRE","ikh");
hashwords.put("FIX","yokok");
hashwords.put("FOLLOW","podr");
hashwords.put("FOLLOWER","podri");
hashwords.put("FOOD","chipo");
hashwords.put("FOR","cho");
hashwords.put("FORGET","nrvidoj");
hashwords.put("FORWARD","lit");
hashwords.put("FREE","jihf");
hashwords.put("FREEDOM","jihfo");
hashwords.put("FRIEND","zmat'h");
hashwords.put("FRIENDSHIP","zmat'him");
hashwords.put("FROM","che");
hashwords.put("FRONT","lit");
hashwords.put("FULFILL","ghrakh");
hashwords.put("FULFILLED","ghrakh");
hashwords.put("FULL","meyrlin");
hashwords.put("GET","tuhg");
hashwords.put("GIFT","tuh");
hashwords.put("GIVE","tuhv");
hashwords.put("GO","loer");
hashwords.put("GOBLIN","goblin");
hashwords.put("GOBLINESE","goblintan");
hashwords.put("GOING","po");
hashwords.put("GOOD","yoe");
hashwords.put("EVENING","hayke");
hashwords.put("MORNING","hayli");
hashwords.put("MIDNIGHT","dzoke");
hashwords.put("GOODBYE","dzojo");
hashwords.put("GRAY","pliske");
hashwords.put("GREEN","epo");
hashwords.put("GREMLIN","grihm");
hashwords.put("GROUND","shah");
hashwords.put("GUARD","ckhut");
hashwords.put("GUARDIAN","ckhuttro");
hashwords.put("GUIDE","norey");
hashwords.put("HAPPY","ashi");
hashwords.put("HARD","efichi");
hashwords.put("HAS","ko");
hashwords.put("HAVE","uk");
hashwords.put("HE","kah");
hashwords.put("HEAL","vuor");
hashwords.put("HELLO","hay");
hashwords.put("PLEASED","hayay");
hashwords.put("MEET","hayay");
hashwords.put("HELP","pod");
hashwords.put("HELPER","podri");
hashwords.put("HER","rah");
hashwords.put("HERE","me");
hashwords.put("HEY","hay");
hashwords.put("HI","hay");
hashwords.put("HIM","kah");
hashwords.put("HIS","kahif");
hashwords.put("HOBGOBLIN","hoblin");
hashwords.put("HOW","fw");
hashwords.put("HOWEVER","vw");
hashwords.put("HUMAN","man");
hashwords.put("SPEECH","mantan");
hashwords.put("HUSBAND","kihnkahn");
hashwords.put("I","ngah");
hashwords.put("APOLOGIZE","jahsht");
hashwords.put("SORRY","jahsht");
hashwords.put("IF","lun");
hashwords.put("IMP","ihm");
hashwords.put("IN","wm");
hashwords.put("INSTRUCT","tuhdoch");
hashwords.put("INSTRUCTOR","tuhdoche");
hashwords.put("INTRUDE","jrach");
hashwords.put("INTRUDER","jrachw");
hashwords.put("IS","ko");
hashwords.put("IT","ez");
hashwords.put("ITS","ezif");
hashwords.put("JESTER","speyah");
hashwords.put("JOKESTER","speyah");
hashwords.put("KNOW","doj");
hashwords.put("KOBOLD","achilin");
hashwords.put("LAKE","relah");
hashwords.put("LANGUAGE","tan");
hashwords.put("LARGE","loakh");
hashwords.put("LEAD","noreyg");
hashwords.put("LEADER","kore");
hashwords.put("LEARN","port");
hashwords.put("LEARNER","port'h");
hashwords.put("LEAVE","keng");
hashwords.put("LESS","get");
hashwords.put("LIFE","gongko");
hashwords.put("LIGHT","epli");
hashwords.put("LIKE","gon");
hashwords.put("LIQUID","leyfah");
hashwords.put("LIVE","gongk");
hashwords.put("LIVING","gongki");
hashwords.put("LONG","loakh");
hashwords.put("AGO","eysah");
hashwords.put("LOOK","jok");
hashwords.put("LOOKS","turflig");
hashwords.put("LOSE","kurfeckh");
hashwords.put("LOTS","baso");
hashwords.put("LOVE","gyurak");
hashwords.put("MAGIC","uvojn");
hashwords.put("MAGICAL","uvoji");
hashwords.put("MAKE","neot");
hashwords.put("MALE","kihn");
hashwords.put("MARK","shtihk");
hashwords.put("MASTER","norey");
hashwords.put("ME","ngah");
hashwords.put("MINE","ngahif");
hashwords.put("MINERAL","tikm");
hashwords.put("MISPLACE","kurfeckh");
hashwords.put("MOON","meyre");
hashwords.put("MORE","hat");
hashwords.put("MOTHER","hatrihn");
hashwords.put("MOUNTAIN","ikrro");
hashwords.put("MUCH","baso");
hashwords.put("MUD","rekm");
hashwords.put("MUST","ckhiz");
hashwords.put("MY","ngahif");
hashwords.put("MYSTICAL","uvoji");
hashwords.put("NEED","ckhiz");
hashwords.put("NIGHT","meske");
hashwords.put("NO","nah");
hashwords.put("NOBODY","di");
hashwords.put("NOONE","di");
hashwords.put("NOSY","blomgreh");
hashwords.put("NOT","nr");
hashwords.put("NOTHING","di");
hashwords.put("NOW","koy");
hashwords.put("NUMBER","doh");
hashwords.put("OBJECT","ezo");
hashwords.put("OCEAN","relahle");
hashwords.put("CARES","nyah");
hashwords.put("OF","o");
hashwords.put("OGRE","ogrh");
hashwords.put("OKAY","yoess");
hashwords.put("ON","am");
hashwords.put("ONCE","vi");
hashwords.put("BILLION","trw");
hashwords.put("HUNDRED","toy");
hashwords.put("MILLION","tri");
hashwords.put("THOUSAND","tro");
hashwords.put("OR","lw");
hashwords.put("ORANGE","igh");
hashwords.put("ORC","orkh");
hashwords.put("OUR","jadif");
hashwords.put("OVER","bah");
hashwords.put("OWN","uk");
hashwords.put("PLACE","rrey");
hashwords.put("PLANT","ngepo");
hashwords.put("PLEASE","tiki");
hashwords.put("PLUME","pwm");
hashwords.put("POND","relah");
hashwords.put("POSSESS","uk");
hashwords.put("POSSESSION","uktuh");
hashwords.put("PRACTICE","gihspw");
hashwords.put("PRESENT","tuh");
hashwords.put("PRIZE","tyesui");
hashwords.put("PROMISE","obranyu");
hashwords.put("PROTECT","ckhut");
hashwords.put("PURPLE","mede");
hashwords.put("QUESTION","banrakh");
hashwords.put("RECIEVE","tuhg");
hashwords.put("RED","urde");
hashwords.put("RELATE","gong");
hashwords.put("RELATED","gong");
hashwords.put("RELATION","gongah");
hashwords.put("RELATIVE","gongah");
hashwords.put("REMEMBER","vidoj");
hashwords.put("REPAIR","yokok");
hashwords.put("REPLACE","jepwov");
hashwords.put("REPLACEMENT","jepwovw");
hashwords.put("REQUEST","banrahk");
hashwords.put("RESCUE","pod");
hashwords.put("RESCUER","podri");
hashwords.put("REWARD","tyesui");
hashwords.put("RIVER","reloh");
hashwords.put("ROCK","tikm");
hashwords.put("RUN","reloh");
hashwords.put("RUNNING","reloh");
hashwords.put("SACRED","urpfah");
hashwords.put("SAD","eckhi");
hashwords.put("SAND","shikm");
hashwords.put("SAVE","pod");
hashwords.put("SEA","relahle");
hashwords.put("SEARCH","turflig");
hashwords.put("SECRET","urpfah");
hashwords.put("SEE","jok");
hashwords.put("SERIOUS","legin");
hashwords.put("SHALL","po");
hashwords.put("SHE","rah");
hashwords.put("SHORT","loen");
hashwords.put("SIDE","bit");
hashwords.put("SIMPLE","imshi");
hashwords.put("SIMULTANEOUSLY","kahnz");
hashwords.put("SISTER","korihn");
hashwords.put("SKINNY","zifti");
hashwords.put("SKY","mey");
hashwords.put("SLAVE","zruhg");
hashwords.put("SMALL","loen");
hashwords.put("SO","nw");
hashwords.put("SOME","choy");
hashwords.put("SOMEONE","chay");
hashwords.put("SOMETHING","chez");
hashwords.put("SON","getkihn");
hashwords.put("SPEAK","tanz");
hashwords.put("SPRING","reloh");
hashwords.put("START","plint");
hashwords.put("STREAK","shtihk");
hashwords.put("STREAM","reloh");
hashwords.put("STRIPE","shtihk");
hashwords.put("STUDENT","port'h");
hashwords.put("SUBSTITUTE","jepwov");
hashwords.put("SUCCEED","poahp");
hashwords.put("SUN","meykh");
hashwords.put("SUNSET","meykeh");
hashwords.put("SURISE","meykin");
hashwords.put("SWAMP","rehao");
hashwords.put("TAKE","tuhg");
hashwords.put("TALK","tanz");
hashwords.put("TALL","ngeyn");
hashwords.put("TASK","rekyom");
hashwords.put("TEACH","tuhdoch");
hashwords.put("TEACHER","tuhdoche");
hashwords.put("TEASE","speyak");
hashwords.put("TELL","danz");
hashwords.put("THANK","chiwkki");
hashwords.put("THANKS","chiwkki");
hashwords.put("THAT","ez");
hashwords.put("THE","za");
hashwords.put("EIGHT","wihn");
hashwords.put("8","wihn");
hashwords.put("FIVE","ye");
hashwords.put("5","ye");
hashwords.put("FOUR","hi");
hashwords.put("4","hi");
hashwords.put("NINE","yw");
hashwords.put("9","yw");
hashwords.put("ONE","o");
hashwords.put("FIRST","oze");
hashwords.put("SECOND","hoze");
hashwords.put("THIRD","hoyze");
hashwords.put("FOURTH","hize");
hashwords.put("FIFTH","yeze");
hashwords.put("SIXTH","yize");
hashwords.put("SEVENTH","wize");
hashwords.put("EIGHTH","wihnze");
hashwords.put("NINETH","ywze");
hashwords.put("TENTH","toze");
hashwords.put("1","o");
hashwords.put("SEVEN","wi");
hashwords.put("7","wi");
hashwords.put("SIX","yi");
hashwords.put("6","yi");
hashwords.put("TEN","to");
hashwords.put("10","to");
hashwords.put("THREE","hoy");
hashwords.put("3","hoy");
hashwords.put("TWO","ho");
hashwords.put("2","ho");
hashwords.put("THEIR","jedif");
hashwords.put("THEM","jed");
hashwords.put("THEN","noy");
hashwords.put("THERE","mi");
hashwords.put("THEREFORE","nw");
hashwords.put("THESE","ne");
hashwords.put("THEY","jed");
hashwords.put("THIN","zifti");
hashwords.put("THING","ezo");
hashwords.put("THIS","e");
hashwords.put("THOSE","ni");
hashwords.put("TIME","oy");
hashwords.put("TO","cho");
hashwords.put("TODAY","koyn");
hashwords.put("TOGETHER","kahnz");
hashwords.put("TOMORROW","poyn");
hashwords.put("TOO","dok");
hashwords.put("TOP","hat");
hashwords.put("TREAT","vuor");
hashwords.put("TREE","ngeyn");
hashwords.put("TRESPASS","jrach");
hashwords.put("TRESPASSER","jrachw");
hashwords.put("TROLL","trolo");
hashwords.put("UNCOMPLICATED","imshi");
hashwords.put("UNDER","get");
hashwords.put("UNLESS","vw");
hashwords.put("US","jad");
hashwords.put("USE","ghrakh");
hashwords.put("USED","ghrakh");
hashwords.put("VERY","baso");
hashwords.put("VIOLENT","znavo");
hashwords.put("VIOLENCE","znavo");
hashwords.put("VITALITIY","gongko");
hashwords.put("WANT","kiz");
hashwords.put("WAR","znavo");
hashwords.put("WAS","no");
hashwords.put("WATCH","jok");
hashwords.put("WATER","reh");
hashwords.put("WE","jad");
hashwords.put("WELCOME","chiwkkshah");
hashwords.put("WERE","no");
hashwords.put("WHAT","fe");
hashwords.put("WHATEVER","nyah");
hashwords.put("WHEN","foy");
hashwords.put("WHERE","fey");
hashwords.put("WHICH","yr");
hashwords.put("WHITE","epli");
hashwords.put("WHO","fah");
hashwords.put("WHY","fi");
hashwords.put("WIDE","nerri");
hashwords.put("WIFE","rihnkahn");
hashwords.put("WILL","po");
hashwords.put("WIN","poahp");
hashwords.put("WITH","kho");
hashwords.put("WITHOUT","konr");
hashwords.put("WORK","zruhg");
hashwords.put("YELLOW","ekh");
hashwords.put("YES","yah");
hashwords.put("YESTERDAY","noyn");
hashwords.put("YET","vw");
hashwords.put("YOU","so");
hashwords.put("YALL","joth");
hashwords.put("Y`ALL","joth");
hashwords.put("YOUR","soif");
return hashwords;
}
} |
Java | @Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListDevicesRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the project.
* </p>
*/
private String arn;
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*/
private String nextToken;
/**
* <p>
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more values.
* </p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY",
* or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available for the
* OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* </ul>
*/
private java.util.List<DeviceFilter> filters;
/**
* <p>
* The Amazon Resource Name (ARN) of the project.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the project.
*/
public void setArn(String arn) {
this.arn = arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the project.
* </p>
*
* @return The Amazon Resource Name (ARN) of the project.
*/
public String getArn() {
return this.arn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the project.
* </p>
*
* @param arn
* The Amazon Resource Name (ARN) of the project.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesRequest withArn(String arn) {
setArn(arn);
return this;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @param nextToken
* An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @return An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* An identifier that was returned from the previous call to this operation, which can be used to return the next
* set of items in the list.
* </p>
*
* @param nextToken
* An identifier that was returned from the previous call to this operation, which can be used to return the
* next set of items in the list.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* <p>
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more values.
* </p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY",
* or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available for the
* OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* </ul>
*
* @return Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more
* values.</p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device
* filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE",
* "BUSY", or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available
* for the OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
*/
public java.util.List<DeviceFilter> getFilters() {
return filters;
}
/**
* <p>
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more values.
* </p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY",
* or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available for the
* OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* </ul>
*
* @param filters
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more
* values.</p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device
* filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE",
* "BUSY", or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available
* for the OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
*/
public void setFilters(java.util.Collection<DeviceFilter> filters) {
if (filters == null) {
this.filters = null;
return;
}
this.filters = new java.util.ArrayList<DeviceFilter>(filters);
}
/**
* <p>
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more values.
* </p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY",
* or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available for the
* OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* </ul>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setFilters(java.util.Collection)} or {@link #withFilters(java.util.Collection)} if you want to override
* the existing values.
* </p>
*
* @param filters
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more
* values.</p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device
* filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE",
* "BUSY", or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available
* for the OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesRequest withFilters(DeviceFilter... filters) {
if (this.filters == null) {
setFilters(new java.util.ArrayList<DeviceFilter>(filters.length));
}
for (DeviceFilter ele : filters) {
this.filters.add(ele);
}
return this;
}
/**
* <p>
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more values.
* </p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY",
* or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available for the
* OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* </ul>
*
* @param filters
* Used to select a set of devices. A filter is made up of an attribute, an operator, and one or more
* values.</p>
* <ul>
* <li>
* <p>
* Attribute: The aspect of a device such as platform or model used as the selection criteria in a device
* filter.
* </p>
* <p>
* Allowed values include:
* </p>
* <ul>
* <li>
* <p>
* ARN: The Amazon Resource Name (ARN) of the device. For example,
* "arn:aws:devicefarm:us-west-2::device:12345Example".
* </p>
* </li>
* <li>
* <p>
* PLATFORM: The device platform. Valid values are "ANDROID" or "IOS".
* </p>
* </li>
* <li>
* <p>
* OS_VERSION: The operating system version. For example, "10.3.2".
* </p>
* </li>
* <li>
* <p>
* MODEL: The device model. For example, "iPad 5th Gen".
* </p>
* </li>
* <li>
* <p>
* AVAILABILITY: The current availability of the device. Valid values are "AVAILABLE", "HIGHLY_AVAILABLE",
* "BUSY", or "TEMPORARY_NOT_AVAILABLE".
* </p>
* </li>
* <li>
* <p>
* FORM_FACTOR: The device form factor. Valid values are "PHONE" or "TABLET".
* </p>
* </li>
* <li>
* <p>
* MANUFACTURER: The device manufacturer. For example, "Apple".
* </p>
* </li>
* <li>
* <p>
* REMOTE_ACCESS_ENABLED: Whether the device is enabled for remote access. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* REMOTE_DEBUG_ENABLED: Whether the device is enabled for remote debugging. Valid values are "TRUE" or
* "FALSE".
* </p>
* </li>
* <li>
* <p>
* INSTANCE_ARN: The Amazon Resource Name (ARN) of the device instance.
* </p>
* </li>
* <li>
* <p>
* INSTANCE_LABELS: The label of the device instance.
* </p>
* </li>
* <li>
* <p>
* FLEET_TYPE: The fleet type. Valid values are "PUBLIC" or "PRIVATE".
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Operator: The filter operator.
* </p>
* <ul>
* <li>
* <p>
* The EQUALS operator is available for every attribute except INSTANCE_LABELS.
* </p>
* </li>
* <li>
* <p>
* The CONTAINS operator is available for the INSTANCE_LABELS and MODEL attributes.
* </p>
* </li>
* <li>
* <p>
* The IN and NOT_IN operators are available for the ARN, OS_VERSION, MODEL, MANUFACTURER, and INSTANCE_ARN
* attributes.
* </p>
* </li>
* <li>
* <p>
* The LESS_THAN, GREATER_THAN, LESS_THAN_OR_EQUALS, and GREATER_THAN_OR_EQUALS operators are also available
* for the OS_VERSION attribute.
* </p>
* </li>
* </ul>
* </li>
* <li>
* <p>
* Values: An array of one or more filter values.
* </p>
* <ul>
* <li>
* <p>
* The IN and NOT_IN operators take a values array that has one or more elements.
* </p>
* </li>
* <li>
* <p>
* The other operators require an array with a single element.
* </p>
* </li>
* <li>
* <p>
* In a request, the AVAILABILITY attribute takes "AVAILABLE", "HIGHLY_AVAILABLE", "BUSY", or
* "TEMPORARY_NOT_AVAILABLE" as values.
* </p>
* </li>
* </ul>
* </li>
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListDevicesRequest withFilters(java.util.Collection<DeviceFilter> filters) {
setFilters(filters);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getArn() != null)
sb.append("Arn: ").append(getArn()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken()).append(",");
if (getFilters() != null)
sb.append("Filters: ").append(getFilters());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListDevicesRequest == false)
return false;
ListDevicesRequest other = (ListDevicesRequest) obj;
if (other.getArn() == null ^ this.getArn() == null)
return false;
if (other.getArn() != null && other.getArn().equals(this.getArn()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
if (other.getFilters() == null ^ this.getFilters() == null)
return false;
if (other.getFilters() != null && other.getFilters().equals(this.getFilters()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
hashCode = prime * hashCode + ((getFilters() == null) ? 0 : getFilters().hashCode());
return hashCode;
}
@Override
public ListDevicesRequest clone() {
return (ListDevicesRequest) super.clone();
}
} |
Java | public class UnicodeConverter extends WicketExamplePage
{
private static final String FROM_ESCAPED_UNICODE = "from escaped unicode";
private static final String TO_ESCAPED_UNICODE = "to escaped unicode";
private static List<String> translationTypes = Arrays.asList(TO_ESCAPED_UNICODE, FROM_ESCAPED_UNICODE);
private String source = "";
private String translationType = translationTypes.get(0);
/**
* Model that does the conversion. Note that as we 'pull' the value every time we render (we get
* the current value of message), we don't need to update the model itself. The alternative
* strategy would be to have a model with it's own, translated, string representation of the
* source, which should be updated on every form post (e.g. by overriding {@link Form#onSubmit}
* and in that method explicitly setting the new value). But as you can see, this method is
* slighly easier, and if we wanted to use the translated value in e.g. a database, we could
* just query this model directly or indirectly by calling {@link Component#getDefaultModelObject()} on
* the component that holds it, and we would have a recent value.
*/
private final class ConverterModel extends Model<String>
{
/**
* @see org.apache.wicket.model.IModel#getObject()
*/
@Override
public String getObject()
{
String result;
if (TO_ESCAPED_UNICODE.equals(translationType))
{
result = Strings.toEscapedUnicode(source);
}
else
{
result = Strings.fromEscapedUnicode(source);
}
return result;
}
/**
* @see org.apache.wicket.model.IModel#setObject(java.lang.Object)
*/
@Override
public void setObject(String object)
{
// Ignore. We are not interested in updating any value,
// and we don't want to throw an exception like
// AbstractReadOnlyModel either. Alternatively, we
// could have overriden updateModel of FormInputComponent
// and ignore any input there.
}
}
/**
* Constructor.
*/
public UnicodeConverter()
{
Form<UnicodeConverter> form = new Form<UnicodeConverter>("form",
new CompoundPropertyModel<UnicodeConverter>(this));
form.add(new TextArea<String>("source"));
form.add(new DropDownChoice<String>("translationType", translationTypes));
form.add(new TextArea<String>("target", new ConverterModel()));
add(form);
}
/**
* @return the source to translate
*/
public String getSource()
{
return source;
}
/**
* @param source
* the source to set
*/
public void setSource(String source)
{
this.source = source;
}
/**
* @return the selection
*/
public String getTranslationType()
{
return translationType;
}
/**
* @param translationType
* the selection
*/
public void setTranslationType(String translationType)
{
this.translationType = translationType;
}
} |
Java | private final class ConverterModel extends Model<String>
{
/**
* @see org.apache.wicket.model.IModel#getObject()
*/
@Override
public String getObject()
{
String result;
if (TO_ESCAPED_UNICODE.equals(translationType))
{
result = Strings.toEscapedUnicode(source);
}
else
{
result = Strings.fromEscapedUnicode(source);
}
return result;
}
/**
* @see org.apache.wicket.model.IModel#setObject(java.lang.Object)
*/
@Override
public void setObject(String object)
{
// Ignore. We are not interested in updating any value,
// and we don't want to throw an exception like
// AbstractReadOnlyModel either. Alternatively, we
// could have overriden updateModel of FormInputComponent
// and ignore any input there.
}
} |
Java | public abstract class StructureView implements Viewable
{
private GridPane grid;
private SoftReference<Structure> structure;
private ColorMap colorMap;
private Collection<CellView> cellViews;
private String cellViewClass;
private int gridWidth;
private int gridHeight;
private int cellWidth;
private int cellHeight;
/**
* Creates a new Structure view of the desired width and height with a
* SoftReference to its corresponding Structure
* @param width
* @param height
*/
public StructureView(Structure structure, ColorMap cm, int width, int height, String cellViewType)
{
this.structure = new SoftReference<Structure>(structure);
this.grid = new GridPane();
this.cellViews = new ArrayList<CellView>();
this.colorMap = cm;
this.gridWidth = width;
this.gridHeight = height;
this.cellWidth = determineCellWidth();
this.cellHeight = determineCellHeight();
this.cellViewClass = cellViewType;
populateGridPane();
}
/**
* Convenience initilializer
* @param board
*/
public StructureView(Structure structure, ColorMap cm)
{
this(structure,cm,200,200,CellView.RECTANGLE);
}
/**
* Returns the GridPane that contains the GUI of the board
*/
public Node getNode()
{
populateGridPane();
return grid;
}
/**
* Sets the size of the GridPane to width by height
* @param width- the desired width
* @param height- the desired height
*/
public void setSizeOfView(int width, int height)
{
gridWidth = width;
gridHeight = height;
cellWidth = determineCellWidth();
cellHeight = determineCellHeight();
}
/**
* @return the width of the StructureView
*/
public int getGridWidth()
{
return gridWidth;
}
/**
* @return the height of the StructureView
*/
public int getGridHeight()
{
return gridHeight;
}
/**
* Updates the Cell values in the GridPane
*/
public void populateGridPane()
{
for(Point point : structure.get().getAllPoints())
{
Cell current = structure.get().getCell(point);
if(current != null && current.isValid())
{
formatAndAddCellView(current,point.x,point.y);
}
}
}
/**
* Updates the Structure View by calling all the updateView() methods of the CellViews
*/
public void updateView()
{
for(CellView cv : cellViews)
{
cv.updateView();
}
}
/**
* Creates a new CellView object for the Cell cell and places the node of the cell at (i,j) in the
* GridPane. Each CellView will have a width of width.
* @param cell - the model for the CellView
* @param width - desired width of the CellView
* @param i - i location of the CellView
* @param j - j location of the CellView
*/
private void formatAndAddCellView(Cell cell, int row, int col)
{
CellView cellView = getCellView(cell,row,col,colorMap);
cellViews.add(cellView);
cellView.setSize(cellWidth,cellHeight);
grid.add(cellView.getNode(), col, row);
}
/**
* @return the desired width for cells
*/
private int determineCellWidth()
{
int maxCellWidth = gridWidth/structure.get().getWidth();
return maxCellWidth;
}
/**
* @return the desired height for cells
*/
private int determineCellHeight()
{
int maxCellHeight = gridHeight/structure.get().getHeight();
return maxCellHeight;
}
/**
* Defines the CellView for a given cell at location (row,col)
* @param cell- cell the view is representing
* @param row - the row location of that cell in the structure
* @param col - the column location of that cell in the structure
* @param cm - the ColorMap to define Color-State pairings
* @return
*/
protected CellView getCellView(Cell cell,int row, int col,ColorMap cm)
{
if(cellViewClass.equals(CellView.HEXAGON))
{
return new HexagonCellView(cell,cm,col);
}
else if(cellViewClass.equals(CellView.TRIANGLE))
{
return new TriangleCellView(cell,cm,row,col);
}
else
{
return new RectangleCellView(cell,cm);
}
}
/**
* Sets the CellView for the structure to the CellView Class corresponding
* to the cellViewClassString
* @param cellViewClassString- String that resembles a CellView class
*/
public void setCellView(String cellViewClassString)
{
this.cellViewClass = cellViewClassString;
resetGridPaneAndCellViews();
populateGridPane();
}
/**
* Returns the type of CellView for the current structure
*/
public String getCellViewType()
{
return cellViewClass;
}
private void resetGridPaneAndCellViews()
{
this.grid = new GridPane();
this.cellViews = new ArrayList<CellView>();
}
} |
Java | public class Test {
public static void main(String[] args) {
// String text = "thisdate,vendor_id,fancy_os_id,pack_name,req_slot_type,req_slot_width,req_slot_height,req_allowed_creative_type,vendor_id,geo_code,fancy_id,ex_uid,req_slot_type,req_slot_width,req_slot_height,fancy_media_cate,is_mob,network_scene,request_id,url,page_category,fancy_device_type_id,title,media_keyword,pack_name,refer,slot_id,direct_deal_id,vendor_id,ex_uid,req_slot_type,title,pack_name,is_app,thisdate,pack_name,ex_uid,vendor_id,thisdate,idfa,idfa_hash,pack_name,vendor_id,imei,imei_hash";
// List<String> strings = Arrays.asList(text.split(","));
// Set<String> set = new HashSet<>(strings);
// for (String s : set) {
// System.out.println(s);
// }
// for (int i = 2; i < 3; i++) {
// System.out.println(i);
// }
//
// int[] a = {1, 2};
// int b = 3;
// a[0] = b;
// b = 5;
// System.out.println(a[0]);
// System.out.println(finTest());
String dateTimeStr = "2019-12-30 18:10:00";
int orderId = 1;
int vendorId = 2;
int dspId = 3;
String slotTagId = "'11','12'";
String ftxQttSaasKey = "'" + dateTimeStr.substring(0, 10) + "'," + dateTimeStr.substring(11, 13) + "," + "'" + dateTimeStr + "'," + orderId + "," + vendorId + "," + dspId + "," + slotTagId;
System.out.println(ftxQttSaasKey);
}
public static String finTest() {
String t = "hello";
try {
return (t + System.currentTimeMillis());
} finally {
t = "hello world";
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t + System.currentTimeMillis());
return (t + System.currentTimeMillis());
}
}
} |
Java | public class catalogoMedidadVolumetricasJarras extends javax.swing.JFrame {
/**
* Creates new form catalogoCronometro
*/
String columna[];
DefaultTableModel modeloJarras;
LibreriaBDControlador lbd = new LibreriaBDControlador();
public catalogoMedidadVolumetricasJarras() {
lbd.openConnection();
getColumnas();
modeloJarras = lbd.modeloJarras(columna); //Cargo el contenido por defecto
lbd.closeConnection();
initComponents();
}
/*Obtengo los titulos de mi tabla*/
String[] getColumnas(){ //Columnas
columna = new String[] {"N.JARRA","MARCA",
"MODELO",
"SERIE",
"ESTATUS",
"VOL.CONV.20",
"FACTOR KC",
"FEC.CALIB",
"RESULTADO",
"INFORMECALIB",
};
return columna;
}
private void RefrescarCTctionPerformed(java.awt.event.ActionEvent evt) {
lbd.openConnection();
modeloJarras = lbd.modeloJarras(columna);
lbd.closeConnection();
jTable1.setModel(modeloJarras);
modeloJarras.fireTableDataChanged();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
botonAgregar = new javax.swing.JButton();
botonEliminar = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jPanel2 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Catálogo Jarras");
setBackground(new java.awt.Color(255, 255, 255));
setMaximumSize(new java.awt.Dimension(1000, 600));
setMinimumSize(new java.awt.Dimension(1000, 600));
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 153, 51)));
botonAgregar.setFont(new java.awt.Font("Lucida Grande", 0, 20)); // NOI18N
botonAgregar.setText("Agregar");
botonAgregar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonAgregarActionPerformed(evt);
}
});
botonEliminar.setFont(new java.awt.Font("Lucida Grande", 0, 20)); // NOI18N
botonEliminar.setText("Eliminar");
botonEliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botonEliminarActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel1.setText("Catalógo de Jarras");
jTable1.setModel(modeloJarras);
jTable1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 853, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(botonAgregar, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(botonEliminar, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(353, 353, 353)
.addComponent(jLabel1)
.addContainerGap(354, Short.MAX_VALUE)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 467, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(botonAgregar)
.addComponent(botonEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(35, 35, 35))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(266, 266, 266)
.addComponent(jLabel1)
.addContainerGap(267, Short.MAX_VALUE)))
);
jPanel2.setBackground(new java.awt.Color(204, 255, 204));
jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 51, 51)));
jPanel2.setForeground(new java.awt.Color(204, 255, 204));
jLabel2.setText("Bienvenido al Catalogo de Jarras, aquí pueden visualizarse las jarras disponibles en el sistema.");
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(37, 37, 37)
.addComponent(jLabel2)
.addContainerGap(47, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void botonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonAgregarActionPerformed
// TODO add your handling code here:
agregarMedVolumetrica amv = new agregarMedVolumetrica(this, rootPaneCheckingEnabled);
amv.show();
RefrescarCTctionPerformed(evt);
}//GEN-LAST:event_botonAgregarActionPerformed
private void botonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonEliminarActionPerformed
// TODO add your handling code here:
eliminarJarras elj = new eliminarJarras(this,rootPaneCheckingEnabled);
elj.show();
RefrescarCTctionPerformed(evt);
}//GEN-LAST:event_botonEliminarActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botonAgregar;
private javax.swing.JButton botonEliminar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
} |
Java | public class BinaryMathProcessor extends FunctionalBinaryProcessor<Number, Number, Number, BinaryMathOperation> {
public enum BinaryMathOperation implements BiFunction<Number, Number, Number> {
ATAN2((l, r) -> Math.atan2(l.doubleValue(), r.doubleValue())),
MOD(Arithmetics::mod),
POWER((l, r) -> Math.pow(l.doubleValue(), r.doubleValue()));
private final BiFunction<Number, Number, Number> process;
BinaryMathOperation(BiFunction<Number, Number, Number> process) {
this.process = process;
}
@Override
public final Number apply(Number left, Number right) {
if (left == null || right == null) {
return null;
}
return process.apply(left, right);
}
}
public static final String NAME = "mb";
public BinaryMathProcessor(Processor left, Processor right, BinaryMathOperation operation) {
super(left, right, operation);
}
public BinaryMathProcessor(StreamInput in) throws IOException {
super(in, i -> i.readEnum(BinaryMathOperation.class));
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
protected void checkParameter(Object param) {
if (!(param instanceof Number)) {
throw new SqlIllegalArgumentException("A number is required; received [{}]", param);
}
}
} |
Java | public class StringUtil {
public static final String EMPTY = "";
private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
private static final Random RANDOM = new Random();
private static final char[] CHARS = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w',
'e',
'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c',
'v', 'b',
'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J',
'K', 'L',
'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
/**
* 字符串hash算法:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] <br>
* 其中s[]为字符串的字符数组,换算成程序的表达式为:<br>
* h = 31*h + s.charAt(i); => h = (h << 5) - h + s.charAt(i); <br>
*
* @param start hash for s.substring(start, end)
* @param end hash for s.substring(start, end)
*/
public static long hash(String s, int start, int end) {
if (start < 0) {
start = 0;
}
if (end > s.length()) {
end = s.length();
}
long h = 0;
for (int i = start; i < end; ++i) {
h = (h << 5) - h + s.charAt(i);
}
return h;
}
public static byte[] encode(String src, String charset) {
if (src == null) {
return null;
}
try {
return src.getBytes(charset);
} catch (UnsupportedEncodingException e) {
return src.getBytes();
}
}
public static String decode(byte[] src, String charset) {
return decode(src, 0, src.length, charset);
}
public static String decode(byte[] src, int offset, int length, String charset) {
try {
return new String(src, offset, length, charset);
} catch (UnsupportedEncodingException e) {
return new String(src, offset, length);
}
}
public static String getRandomString(int size) {
StringBuilder s = new StringBuilder(size);
int len = CHARS.length;
for (int i = 0; i < size; i++) {
int x = RANDOM.nextInt();
s.append(CHARS[(x < 0 ? -x : x) % len]);
}
return s.toString();
}
public static String safeToString(Object object) {
try {
return object.toString();
} catch (Exception e) {
return "<toString() failure: " + e + ">";
}
}
/**
* <p>Checks if a CharSequence is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param cs the CharSequence to check, may be null
* @return {@code true} if the CharSequence is null, empty or whitespace
* @since 2.0
* @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence)
*/
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
public static byte[] hexString2Bytes(char[] hexString, int offset, int length) {
if (hexString == null) {
return null;
}
if (length == 0) {
return EMPTY_BYTE_ARRAY;
}
boolean odd = length << 31 == Integer.MIN_VALUE;
byte[] bs = new byte[odd ? (length + 1) >> 1 : length >> 1];
for (int i = offset, limit = offset + length; i < limit; ++i) {
char high, low;
if (i == offset && odd) {
high = '0';
low = hexString[i];
} else {
high = hexString[i];
low = hexString[++i];
}
int b;
switch (high) {
case '0':
b = 0;
break;
case '1':
b = 0x10;
break;
case '2':
b = 0x20;
break;
case '3':
b = 0x30;
break;
case '4':
b = 0x40;
break;
case '5':
b = 0x50;
break;
case '6':
b = 0x60;
break;
case '7':
b = 0x70;
break;
case '8':
b = 0x80;
break;
case '9':
b = 0x90;
break;
case 'a':
case 'A':
b = 0xa0;
break;
case 'b':
case 'B':
b = 0xb0;
break;
case 'c':
case 'C':
b = 0xc0;
break;
case 'd':
case 'D':
b = 0xd0;
break;
case 'e':
case 'E':
b = 0xe0;
break;
case 'f':
case 'F':
b = 0xf0;
break;
default:
throw new IllegalArgumentException(
"illegal hex-string: " + new String(hexString, offset, length));
}
switch (low) {
case '0':
break;
case '1':
b += 1;
break;
case '2':
b += 2;
break;
case '3':
b += 3;
break;
case '4':
b += 4;
break;
case '5':
b += 5;
break;
case '6':
b += 6;
break;
case '7':
b += 7;
break;
case '8':
b += 8;
break;
case '9':
b += 9;
break;
case 'a':
case 'A':
b += 10;
break;
case 'b':
case 'B':
b += 11;
break;
case 'c':
case 'C':
b += 12;
break;
case 'd':
case 'D':
b += 13;
break;
case 'e':
case 'E':
b += 14;
break;
case 'f':
case 'F':
b += 15;
break;
default:
throw new IllegalArgumentException(
"illegal hex-string: " + new String(hexString, offset, length));
}
bs[(i - offset) >> 1] = (byte) b;
}
return bs;
}
public static String dumpAsHex(byte[] src, int length) {
StringBuilder out = new StringBuilder(length * 4);
int p = 0;
int rows = length / 8;
for (int i = 0; (i < rows) && (p < length); i++) {
int ptemp = p;
for (int j = 0; j < 8; j++) {
String hexVal = Integer.toHexString(src[ptemp] & 0xff);
if (hexVal.length() == 1) {
out.append('0');
}
out.append(hexVal).append(' ');
ptemp++;
}
out.append(" ");
for (int j = 0; j < 8; j++) {
int b = 0xff & src[p];
if (b > 32 && b < 127) {
out.append((char) b).append(' ');
} else {
out.append(". ");
}
p++;
}
out.append('\n');
}
int n = 0;
for (int i = p; i < length; i++) {
String hexVal = Integer.toHexString(src[i] & 0xff);
if (hexVal.length() == 1) {
out.append('0');
}
out.append(hexVal).append(' ');
n++;
}
for (int i = n; i < 8; i++) {
out.append(" ");
}
out.append(" ");
for (int i = p; i < length; i++) {
int b = 0xff & src[i];
if (b > 32 && b < 127) {
out.append((char) b).append(' ');
} else {
out.append(". ");
}
}
out.append('\n');
return out.toString();
}
public static byte[] escapeEasternUnicodeByteStream(byte[] src, String srcString, int offset,
int length) {
if ((src == null) || (src.length == 0)) {
return src;
}
int bytesLen = src.length;
int bufIndex = 0;
int strIndex = 0;
ByteArrayOutputStream out = new ByteArrayOutputStream(bytesLen);
while (true) {
if (srcString.charAt(strIndex) == '\\') {// write it out as-is
out.write(src[bufIndex++]);
} else {// Grab the first byte
int loByte = src[bufIndex];
if (loByte < 0) {
loByte += 256; // adjust for
}
// signedness/wrap-around
out.write(loByte);// We always write the first byte
if (loByte >= 0x80) {
if (bufIndex < (bytesLen - 1)) {
int hiByte = src[bufIndex + 1];
if (hiByte < 0) {
hiByte += 256; // adjust for
}
// signedness/wrap-around
out.write(hiByte);// write the high byte here, and
// increment the index for the high
// byte
bufIndex++;
if (hiByte == 0x5C) {
out.write(hiByte);// escape 0x5c if
}
// necessary
}
} else if (loByte == 0x5c) {
if (bufIndex < (bytesLen - 1)) {
int hiByte = src[bufIndex + 1];
if (hiByte < 0) {
hiByte += 256; // adjust for
}
// signedness/wrap-around
if (hiByte == 0x62) {// we need to escape the 0x5c
out.write(0x5c);
out.write(0x62);
bufIndex++;
}
}
}
bufIndex++;
}
if (bufIndex >= bytesLen) {
break;// we're done
}
strIndex++;
}
return out.toByteArray();
}
public static String toString(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return "";
}
StringBuffer buffer = new StringBuffer();
for (byte byt : bytes) {
buffer.append((char) byt);
}
return buffer.toString();
}
public static boolean equalsIgnoreCase(String str1, String str2) {
if (str1 == null) {
return str2 == null;
}
return str1.equalsIgnoreCase(str2);
}
public static int countChar(String str, char c) {
if (str == null || str.isEmpty()) {
return 0;
}
final int len = str.length();
int cnt = 0;
for (int i = 0; i < len; ++i) {
if (c == str.charAt(i)) {
++cnt;
}
}
return cnt;
}
public static String replaceOnce(String text, String repl, String with) {
return replace(text, repl, with, 1);
}
public static String replace(String text, String repl, String with) {
return replace(text, repl, with, -1);
}
public static String replace(String text, String repl, String with, int max) {
if ((text == null) || (repl == null) || (with == null) || (repl.length() == 0) || (max == 0)) {
return text;
}
StringBuffer buf = new StringBuffer(text.length());
int start = 0;
int end = 0;
while ((end = text.indexOf(repl, start)) != -1) {
buf.append(text.substring(start, end)).append(with);
start = end + repl.length();
if (--max == 0) {
break;
}
}
buf.append(text.substring(start));
return buf.toString();
}
public static String replaceChars(String str, char searchChar, char replaceChar) {
if (str == null) {
return null;
}
return str.replace(searchChar, replaceChar);
}
public static String replaceChars(String str, String searchChars, String replaceChars) {
if ((str == null) || (str.length() == 0) || (searchChars == null) || (searchChars.length()
== 0)) {
return str;
}
char[] chars = str.toCharArray();
int len = chars.length;
boolean modified = false;
for (int i = 0, isize = searchChars.length(); i < isize; i++) {
char searchChar = searchChars.charAt(i);
if ((replaceChars == null) || (i >= replaceChars.length())) {// 删除
int pos = 0;
for (int j = 0; j < len; j++) {
if (chars[j] != searchChar) {
chars[pos++] = chars[j];
} else {
modified = true;
}
}
len = pos;
} else {// 替换
for (int j = 0; j < len; j++) {
if (chars[j] == searchChar) {
chars[j] = replaceChars.charAt(i);
modified = true;
}
}
}
}
if (!modified) {
return str;
}
return new String(chars, 0, len);
}
/**
* insert into tablexxx
*/
public static String getTableName(String sql) {
int pos = 0;
boolean insertFound = false;
boolean intoFound = false;
int tableStartIndx = -1;
int tableEndIndex = -1;
while (pos < sql.length()) {
char ch = sql.charAt(pos);
if (ch <= ' ' || ch == '(') {//
if (tableStartIndx > 0) {
tableEndIndex = pos;
break;
} else {
pos++;
continue;
}
} else if (ch == 'i' || ch == 'I') {
if (intoFound) {
if (tableStartIndx == -1) {
tableStartIndx = pos;
}
pos++;
} else if (insertFound) {// into start
pos = pos + 5;
intoFound = true;
} else {
// insert start
pos = pos + 7;
insertFound = true;
}
} else {
if (tableStartIndx == -1) {
tableStartIndx = pos;
}
pos++;
}
}
return sql.substring(tableStartIndx, tableEndIndex);
}
public static <T> ArrayList<T> toArray(T ts[]) {
ArrayList<T> array = new ArrayList<T>(ts.length);
for (T t : ts) {
array.add(t);
}
return array;
}
public static <T> ArrayList<T> toArray(Set<T> ts) {
ArrayList<T> array = new ArrayList<T>(ts.size());
Iterator<T> it = ts.iterator();
while (it.hasNext()) {
array.add(it.next());
}
return array;
}
/**
* Returns the given string, with comments removed
*
* @param src the source string
* @param stringOpens characters which delimit the "open" of a string
* @param stringCloses characters which delimit the "close" of a string, in counterpart order to
* <code>stringOpens</code>
* @param slashStarComments strip slash-star type "C" style comments
* @param slashSlashComments strip slash-slash C++ style comments to end-of-line
* @param hashComments strip #-style comments to end-of-line
* @param dashDashComments strip "--" style comments to end-of-line
* @return the input string with all comment-delimited data removed
*/
public static String stripComments(String src, String stringOpens, String stringCloses,
boolean slashStarComments,
boolean slashSlashComments, boolean hashComments, boolean dashDashComments) {
if (src == null) {
return null;
}
StringBuffer buf = new StringBuffer(src.length());
// It's just more natural to deal with this as a stream
// when parsing..This code is currently only called when
// parsing the kind of metadata that developers are strongly
// recommended to cache anyways, so we're not worried
// about the _1_ extra object allocation if it cleans
// up the code
StringReader sourceReader = new StringReader(src);
int contextMarker = Character.MIN_VALUE;
boolean escaped = false;
int markerTypeFound = -1;
int ind = 0;
int currentChar = 0;
try {
while ((currentChar = sourceReader.read()) != -1) {
if (markerTypeFound != -1 && currentChar == stringCloses.charAt(markerTypeFound)
&& !escaped) {
contextMarker = Character.MIN_VALUE;
markerTypeFound = -1;
} else if ((ind = stringOpens.indexOf(currentChar)) != -1 && !escaped
&& contextMarker == Character.MIN_VALUE) {
markerTypeFound = ind;
contextMarker = currentChar;
}
if (contextMarker == Character.MIN_VALUE && currentChar == '/'
&& (slashSlashComments || slashStarComments)) {
currentChar = sourceReader.read();
if (currentChar == '*' && slashStarComments) {
int prevChar = 0;
while ((currentChar = sourceReader.read()) != '/' || prevChar != '*') {
if (currentChar == '\r') {
currentChar = sourceReader.read();
if (currentChar == '\n') {
currentChar = sourceReader.read();
}
} else {
if (currentChar == '\n') {
currentChar = sourceReader.read();
}
}
if (currentChar < 0) {
break;
}
prevChar = currentChar;
}
continue;
} else if (currentChar == '/' && slashSlashComments) {
while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
&& currentChar >= 0) {
;
}
}
} else if (contextMarker == Character.MIN_VALUE && currentChar == '#' && hashComments) {
// Slurp up everything until the newline
while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
&& currentChar >= 0) {
;
}
} else if (contextMarker == Character.MIN_VALUE && currentChar == '-' && dashDashComments) {
currentChar = sourceReader.read();
if (currentChar == -1 || currentChar != '-') {
buf.append('-');
if (currentChar != -1) {
buf.append(currentChar);
}
continue;
}
// Slurp up everything until the newline
while ((currentChar = sourceReader.read()) != '\n' && currentChar != '\r'
&& currentChar >= 0) {
;
}
}
if (currentChar != -1) {
buf.append((char) currentChar);
}
}
} catch (IOException ioEx) {
// we'll never see this from a StringReader
}
return buf.toString();
}
/**
* Determines whether or not the sting 'searchIn' contains the string
* 'searchFor', disregarding case and leading whitespace
*
* @param searchIn the string to search in
* @param searchFor the string to search for
* @return true if the string starts with 'searchFor' ignoring whitespace
*/
public static boolean startsWithIgnoreCaseAndWs(String searchIn, String searchFor) {
return startsWithIgnoreCaseAndWs(searchIn, searchFor, 0);
}
/**
* Determines whether or not the sting 'searchIn' contains the string
* 'searchFor', disregarding case and leading whitespace
*
* @param searchIn the string to search in
* @param searchFor the string to search for
* @param beginPos where to start searching
* @return true if the string starts with 'searchFor' ignoring whitespace
*/
public static boolean startsWithIgnoreCaseAndWs(String searchIn, String searchFor, int beginPos) {
if (searchIn == null) {
return searchFor == null;
}
int inLength = searchIn.length();
for (; beginPos < inLength; beginPos++) {
if (!Character.isWhitespace(searchIn.charAt(beginPos))) {
break;
}
}
return startsWithIgnoreCase(searchIn, beginPos, searchFor);
}
/**
* Determines whether or not the string 'searchIn' contains the string
* 'searchFor', dis-regarding case starting at 'startAt' Shorthand for a
* String.regionMatch(...)
*
* @param searchIn the string to search in
* @param startAt the position to start at
* @param searchFor the string to search for
* @return whether searchIn starts with searchFor, ignoring case
*/
public static boolean startsWithIgnoreCase(String searchIn, int startAt, String searchFor) {
return searchIn.regionMatches(true, startAt, searchFor, 0, searchFor.length());
}
/**
* if string is null,return ""
*
* @return string||""
*/
public static String stringOrEmpty(String string) {
if (null == string) {
return "";
} else {
return string;
}
}
/**
* Returns the first non whitespace char, converted to upper case
*
* @param searchIn the string to search in
* @return the first non-whitespace character, upper cased.
*/
public static char firstNonWsCharUc(String searchIn) {
return firstNonWsCharUc(searchIn, 0);
}
public static char firstNonWsCharUc(String searchIn, int startAt) {
if (searchIn == null) {
return 0;
}
int length = searchIn.length();
for (int i = startAt; i < length; i++) {
char c = searchIn.charAt(i);
if (!Character.isWhitespace(c)) {
return Character.toUpperCase(c);
}
}
return 0;
}
} |
Java | public final class CustomFieldSettingUtil {
private static final Log LOG = LogFactoryUtil.getLog(CustomFieldSettingUtil.class);
private CustomFieldSettingUtil() {
}
/**
* Auxiliary method that returns the expando value of a given expando field
* with a given key.
*
* @param user
* The user whose expando field will be retrieved.
* @param key
* The name of the expando field.
* @return Returns false, if the expando field or the value is not defined.
*/
// CHECKSTYLE:OFF
public static void setExpandoValue(final String resolverHint, final long runAsUserId,
final long groupId, final long company, final Class clazz, final long id,
final String key, final String value) {
String valueCopy = value;
try {
ExpandoValue ev = ExpandoValueLocalServiceUtil.getValue(company, clazz.getName(),
"CUSTOM_FIELDS", key, id);
// resolve any values to be substituted
valueCopy = ResolverUtil.lookupAll(runAsUserId, groupId, company, valueCopy,
resolverHint);
if (ev == null) {
long classNameId = ClassNameLocalServiceUtil.getClassNameId(clazz.getName());
ExpandoTable expandoTable = ExpandoTableLocalServiceUtil.getTable(company,
classNameId, "CUSTOM_FIELDS");
ExpandoColumn expandoColumn = ExpandoColumnLocalServiceUtil.getColumn(company,
classNameId, expandoTable.getName(), key);
// In this we are adding MyUserColumnData for the column
// MyUserColumn. See the
// above line
ev = ExpandoValueLocalServiceUtil.addValue(classNameId, expandoTable.getTableId(),
expandoColumn.getColumnId(), id, valueCopy);
} else {
ev.setData(valueCopy);
ExpandoValueLocalServiceUtil.updateExpandoValue(ev);
}
} catch (Exception ex) {
LOG.error("Expando (custom field) not found or problem accessing it: " + key + " for "
+ "class " + clazz.getName() + " with id " + id, ex);
}
}
// CHECKSTYLE:ON
} |
Java | public class GetMyCommandsResponse extends BaseResponse {
private BotCommand[] result;
public BotCommand[] commands() {
return result;
}
@Override
public String toString() {
return "GetMyCommandsResponse{" +
"result=" + Arrays.toString(result) +
'}';
}
} |
Java | @Module
public class ActivityModules {
private final Activity mActivity;
public ActivityModules(Activity activity) {
this.mActivity = activity;
}
@Provides
@PerActivity
Activity getActivity() {
return mActivity;
}
@Provides
@PerActivity
@SpQualifier("share1")
SharedPreferences provideSharedPreferences1() {
return mActivity.getSharedPreferences("share1", Context.MODE_PRIVATE);
}
@Provides
@SpQualifier("share2")
SharedPreferences provideSharedPreferences2() {
return mActivity.getSharedPreferences("share2", Context.MODE_PRIVATE);
}
} |
Java | @Designate(ocd = JwtConfig.class)
@Component(service = JwtService.class, configurationPolicy = REQUIRE)
public class JwtServiceImpl implements JwtService {
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private final String defaultIssuer;
private final String[] mandatoryClaims;
private final Duration expirationDuration;
private final SignatureAlgorithm algorithm;
private final PrivateKey signingKey;
private final JwtVerifier jwtVerifier;
@Activate
public JwtServiceImpl(@NotNull JwtConfig config) {
this.defaultIssuer = config.default_issuer();
this.expirationDuration = Duration.of(config.expiration_time(), MINUTES);
this.mandatoryClaims = config.mandatory_claims();
try {
this.algorithm = SignatureAlgorithm.forName(config.signature_algorithm());
LOGGER.info("Selected JWT SignatureAlgorithm: [{}]", this.algorithm.getJcaName());
RsaSigningKeyInfo signingKeyInfo = new RsaSigningKeyInfo(this.algorithm, config.private_key());
signingKeyInfo.setPrivateKeyPassword(config.private_key_password());
this.signingKey = JwtKeys.createSigningKey(signingKeyInfo);
Key verificationKey = JwtKeys.createVerificationKey(new RsaVerificationKeyInfo(this.algorithm, config.public_key()));
this.jwtVerifier = new JwtVerifier(verificationKey, config.log_jwt_verification_exception_trace());
} catch (SignatureException | JwtKeyInitializationException | IllegalArgumentException ex) {
LOGGER.error(ex.getMessage(), ex);
throw ex;
}
}
/**
* {@inheritDoc}
*/
@Override
public String createJwt(String subject, Map<String, Object> claims) {
Assert.hasText(subject, "Subject can't be blank!!");
JwtUtil.assertClaims(claims);
Instant now = Instant.now();
return Jwts.builder()
.setHeaderParam(TYPE, JWT_TYPE)
.setSubject(subject)
.setClaims(claims) // passed claims map can override the subject claim.
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.plus(this.expirationDuration)))
.setId(claims.containsKey(ID) ? claims.get(ID).toString() : RandomGenerators.uuidString())
.setIssuer(claims.containsKey(ISSUER) ? (String) claims.get(ISSUER) : this.defaultIssuer)
.signWith(this.signingKey, this.algorithm)
.serializeToJsonWith(new JwtSerializer())
.compact();
}
/**
* {@inheritDoc}
*/
@Override
public String createJwt(Map<String, Object> claims) {
JwtUtil.assertClaims(claims, this.mandatoryClaims);
return Jwts.builder()
.setHeaderParam(TYPE, JWT_TYPE)
.setClaims(claims)
.signWith(this.signingKey, this.algorithm)
.serializeToJsonWith(new JwtSerializer())
.compact();
}
/**
* {@inheritDoc}
*/
@Override
public JwtClaims verifyJwt(String jwt) {
return this.jwtVerifier.verify(jwt);
}
} |
Java | class Solution1 implements Solution {
public boolean find132pattern(int[] nums) {
int n = nums.length;
int[] left = new int[n];
left[0] = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
left[i] = Math.min(left[i - 1], nums[i - 1]);
}
Deque<Integer> deque = new LinkedList<>();
for (int i = n - 1; i >= 0; i--) {
while (!deque.isEmpty() && deque.peek() < nums[i]) {
if (left[i] < deque.pop()) {
return true;
}
}
deque.push(nums[i]);
}
return false;
}
public static void main(String[] args) {
System.out.println(123);
}
} |
Java | public class HistogramTwoLevelInvoker {
private QueryEngine queryEngine;
private String groupingOne;
private String groupingTwo;
private String sum;
private Integer parentDirDepth;
private String timeRange;
private Stream<INode> filteredINodes;
private Map<String, Map<String, Long>> histogram;
private String binLabels;
/**
* Constructor.
*
* @param queryEngine the query engine
* @param groupingOne the top level grouping field
* @param groupingTwo the secondary grouping field
* @param sum the sum aggregation field
* @param parentDirDepth the parent dir depth
* @param timeRange the time range used
* @param filteredINodes the inode stream
*/
public HistogramTwoLevelInvoker(
QueryEngine queryEngine,
String groupingOne,
String groupingTwo,
String sum,
Integer parentDirDepth,
String timeRange,
Stream<INode> filteredINodes) {
this.queryEngine = queryEngine;
this.groupingOne = groupingOne;
this.groupingTwo = groupingTwo;
this.sum = sum;
this.parentDirDepth = parentDirDepth;
this.timeRange = timeRange;
this.filteredINodes = filteredINodes;
}
public Map<String, Map<String, Long>> getHistogram() {
return histogram;
}
public String getBinLabels() {
return binLabels;
}
/**
* Performs the histogram function and stores data within this same object.
*
* @return the current object with histogram and labelling complete
*/
public HistogramTwoLevelInvoker invoke() {
histogram = callTwoLevelGroupingHistogram();
switch (groupingOne) {
case "user":
binLabels = "User Names";
break;
case "group":
binLabels = "Group Names";
break;
case "accessTime":
// histogram = Histograms.orderByKeyOrder(histogram, TimeHistogram.getKeys(timeRange));
binLabels = "Last Accessed Time";
break;
case "modTime":
// histogram = Histograms.orderByKeyOrder(histogram, TimeHistogram.getKeys(timeRange));
binLabels = "Last Modified Time";
break;
case "fileSize":
binLabels = "File Sizes (No Replication Factor)";
break;
case "diskspaceConsumed":
binLabels = "Diskspace Consumed (File Size * Replication Factor)";
break;
case "fileReplica":
binLabels = "File Replication Factor";
break;
case "storageType":
binLabels = "Storage Type Policy";
break;
case "memoryConsumed":
binLabels = "Memory Consumed";
break;
case "parentDir":
histogram.remove("NO_MAPPING");
binLabels = "Directory Path";
break;
case "fileType":
// histogram = removeKeysOnConditional("gt:0", histogram);
binLabels = "File Type";
break;
case "dirQuota":
// histogram = removeKeysOnConditional("gt:0", histogram);
binLabels = "Directory Path";
break;
default:
binLabels = "";
break;
}
// histogram = removeKeysOnConditional(histogramConditionsStr, histogram);
// histogram = sliceTopBottom(top, bottom, histogram);
// histogram = sortHistogramAscDesc(sortAscending, sortDescending, histogram);
return this;
}
private Map<String, Map<String, Long>> callTwoLevelGroupingHistogram() {
Function<INode, String> groupingFunc1 =
queryEngine.getGroupingFunctionToStringForINode(groupingOne, parentDirDepth, timeRange);
Function<INode, String> groupingFunc2 =
queryEngine.getGroupingFunctionToStringForINode(groupingTwo, parentDirDepth, timeRange);
if (groupingFunc1 == null) {
throwIllegalHistogramException(groupingOne);
}
if (groupingFunc2 == null) {
throwIllegalHistogramException(groupingTwo);
}
return queryEngine.genericTwoLevelHistogram(
filteredINodes,
groupingFunc1,
groupingFunc2,
queryEngine.getSumFunctionForINode(sum, null));
}
private void throwIllegalHistogramException(String group) {
throw new IllegalArgumentException(
"Could not determine histogram type: "
+ group
+ ".\nPlease check /histograms for available histograms.");
}
} |
Java | public final class AmplifyExtended {
private static Map<String, CategoryMetadata<? extends Plugin<?>>> categoryData = new HashMap<>();
private static Map<String, ExtendedCategory<? extends Plugin<?>>> categories = new HashMap<>();
// Used as a synchronization locking object. Set to true once configure() is complete.
private static final AtomicBoolean CONFIGURATION_LOCK = new AtomicBoolean(false);
// An executor on which categories may be initialized.
private static final ExecutorService INITIALIZATION_POOL = Executors.newSingleThreadExecutor();
/**
* Dis-allows instantiation of this utility class.
*/
private AmplifyExtended() {
throw new UnsupportedOperationException("No instances allowed.");
}
/**
* Add a new category. It should extend {@link ExtendedCategory} and have a unique identifier defined by
* {@link ExtendedCategoryTypeable#getExtendedCategoryType()}.
* @param category A new {@link ExtendedCategory}.
* @param emptyConfiguration A new instance of {@link ExtendedCategoryConfiguration} specialized
* for your plugin.
* @param configurationFileName Name of the configuration file for your plugin.
* @param <P> Type of the category's plugins.
*/
@SuppressWarnings("unchecked")
public static <P extends Plugin<?>> void addCategory(@NonNull ExtendedCategory<? extends Plugin<?>> category,
@NonNull ExtendedCategoryConfiguration emptyConfiguration,
@NonNull String configurationFileName) {
if (categories.containsValue(category)) {
return;
}
categories.put(category.getExtendedCategoryType(), category);
categoryData.put(category.getExtendedCategoryType(), new CategoryMetadata<P>((ExtendedCategory<P>) category,
emptyConfiguration, configurationFileName));
}
/**
* Remove a category.
* @param category An instance of {@link ExtendedCategory} with an identifier matching the category
* you wish to remove.
*/
public static void removeCategory(ExtendedCategory<? extends Plugin<?>> category) {
categories.remove(category.getExtendedCategoryType());
}
/**
* Retrieve an {@link ExtendedCategory} with the given name. It must have been added using
* {@link AmplifyExtended#addCategory(ExtendedCategory, ExtendedCategoryConfiguration, String)}
* @param categoryName Name of the desired category.
* @param <C> Type of category you'd like the behaviors of.
* @return The desired {@link ExtendedCategory}.
*/
@SuppressWarnings("unchecked")
public static <C extends ExtendedCategory<?>> C category(String categoryName) {
try {
return (C) categories.get(categoryName);
} catch (ClassCastException noPlugin) {
return null;
} catch (NullPointerException noCategory) {
return null;
}
}
/**
* Add a new 3rd party plugin.
* @param category A new {@link Category} instance for your plugin.
* @param plugin A new conforming instance of {@link Plugin}.
* @param <P> Plugin type.
* @throws AmplifyException If the plugin and category types do not match.
*/
public static <P extends Plugin<?>> void addPlugin(@NonNull final ExtendedCategory<P> category,
@NonNull final P plugin)
throws AmplifyException {
category.addPlugin(plugin);
}
/**
* Remove a 3rd part plugin.
* @param category The category from which the plugin should be removed.
* @param plugin An instance of the plugin with the same {@link Plugin#getPluginKey()} as a
* plugin you've added before.
* @param <P> Plugin type.
* @throws AmplifyException If the plugin and category types do not match.
*/
@SuppressWarnings("unchecked")
public static <P extends Plugin<?>> void removePlugin(@NonNull final ExtendedCategory<P> category,
@NonNull final P plugin) {
category.removePlugin(plugin);
}
/**
* This is where the configurations are actually read and parsed for each plugin.
* @param context Application context.
* @throws AmplifyException If something really goes wrong.
*/
public static void configure(@NonNull Context context) throws AmplifyException {
Objects.requireNonNull(context);
synchronized (CONFIGURATION_LOCK) {
if (CONFIGURATION_LOCK.get()) {
throw new AmplifyException(
"The client issued a subsequent call to `AmplifyExtended.configure` after "
+ "the first had already succeeded.",
"Be sure to only call AmplifyExtended.configure once"
);
}
for (ExtendedCategory<?> category : categories.values()) {
CategoryMetadata<? extends Plugin<?>> metadata = categoryData.get(category.getExtendedCategoryType());
// Actually a subclass -- used to know the right type
ExtendedCategoryConfiguration emptyConfig = metadata.getExtendedCategoryConfiguration();
ExtendedCategoryConfiguration categoryConfiguration;
try {
categoryConfiguration = ExtendedConfiguration.read(context,
metadata.getConfigFileName(), emptyConfig);
} catch (AmplifyException exception) {
Log.e("AmplifyExt", String.format("Configuration file [%s] could not be read.",
metadata.getConfigFileName()), exception);
continue;
}
category.configure(categoryConfiguration, context);
beginInitialization(category, context);
}
CONFIGURATION_LOCK.set(true);
}
}
private static void beginInitialization(@NonNull Category<? extends Plugin<?>> category, @NonNull Context context) {
INITIALIZATION_POOL.execute(() -> category.initialize(context));
}
} |
Java | public class SarlActiveAnnotationContextProvider extends ActiveAnnotationContextProvider {
@Override
protected void searchAnnotatedElements(final EObject element, final IAcceptor<Pair<JvmAnnotationType, XAnnotation>> acceptor) {
if (element instanceof SarlAgent) {
final SarlAgent elt = (SarlAgent) element;
registerMacroAnnotations(elt, acceptor);
elt.getMembers().forEach(it -> searchAnnotatedElements(it, acceptor));
return;
}
if (element instanceof SarlBehavior) {
final SarlBehavior elt = (SarlBehavior) element;
registerMacroAnnotations(elt, acceptor);
elt.getMembers().forEach(it -> searchAnnotatedElements(it, acceptor));
return;
}
if (element instanceof SarlSkill) {
final SarlSkill elt = (SarlSkill) element;
registerMacroAnnotations(elt, acceptor);
elt.getMembers().forEach(it -> searchAnnotatedElements(it, acceptor));
return;
}
super.searchAnnotatedElements(element, acceptor);
}
} |
Java | public class helpBox {
public static ImageIcon getImageIcon(String name) {
return new ImageIcon(ClassLoader.getSystemResource(name));
}
public helpBox() throws IOException {
final JFrame helpbox = new JFrame("Help");
ComponentMover cm = new ComponentMover();
cm.registerComponent(helpbox);
JLabel label = new JLabel("");
JButton exit = new JButton("");
JTextArea text = new JTextArea(26, 33);
JScrollPane scrol = new JScrollPane(text);
helpbox.setSize(420, 500);
helpbox.setLocationRelativeTo(Encrypter.Center);
helpbox.setResizable(false);
helpbox.setIconImage(Toolkit.getDefaultToolkit().getImage(
getClass().getClassLoader().getResource("assets/ico.png")));
helpbox.setUndecorated(true);
helpbox.getRootPane().setBorder(
BorderFactory.createLineBorder(Encrypter.color_black, 2));
helpbox.setVisible(true);
helpbox.getContentPane().setBackground(Encrypter.color_light);
helpbox.setLayout(new FlowLayout());
helpbox.add(label);
helpbox.add(Box.createHorizontalStrut(330));
helpbox.add(exit);
helpbox.add(scrol);
ImageIcon label_Icon = getImageIcon("assets/icons/help.png");
label.setIcon(label_Icon);
label.setForeground(Encrypter.color_blue);
label.setFont(Encrypter.font16);
text.setEditable(false);
text.setSelectionColor(Encrypter.color_black);
text.setSelectedTextColor(Encrypter.color_white);
text.setBackground(Encrypter.color_light);
scrol.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrol.setViewportBorder(BorderFactory.createLineBorder(
Encrypter.color_black, 0));
ImageIcon exit_icon = getImageIcon("assets/icons/exit.png");
exit.setBackground(Encrypter.color_light);
exit.setBorder(BorderFactory.createLineBorder(Encrypter.color_dark, 0));
exit.setForeground(Encrypter.color_black);
exit.setFont(Encrypter.font16);
exit.setIcon(exit_icon);
exit.setToolTipText("Exit");
try {
FileReader file = new FileReader(ClassLoader.getSystemResource(
"assets/helpBox.txt").getPath());
BufferedReader buff = new BufferedReader(file);
String line = null;
while ((line = buff.readLine()) != null) {
text.append(line);
text.append("\n");
}
buff.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
helpbox.dispose();
}
});
}
} |
Java | public class JavaSpaceProducer extends DefaultProducer {
private static final Logger LOG = LoggerFactory.getLogger(JavaSpaceProducer.class);
private final boolean transactional;
private final long transactionTimeout;
private JavaSpace javaSpace;
private TransactionHelper transactionHelper;
public JavaSpaceProducer(JavaSpaceEndpoint endpoint) throws Exception {
super(endpoint);
this.transactional = endpoint.isTransactional();
this.transactionTimeout = endpoint.getTransactionTimeout();
}
public void process(Exchange exchange) throws Exception {
Entry entry;
Object body = exchange.getIn().getBody();
if (!(body instanceof Entry)) {
entry = new InEntry();
if (body instanceof BeanInvocation) {
((InEntry) entry).correlationId = (new UID()).toString();
}
if (body instanceof byte[]) {
((InEntry) entry).binary = true;
((InEntry) entry).buffer = (byte[]) body;
} else {
((InEntry) entry).binary = false;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(body);
((InEntry) entry).buffer = bos.toByteArray();
}
} else {
entry = (Entry) body;
}
Transaction tnx = null;
if (transactionHelper != null) {
tnx = transactionHelper.getJiniTransaction(transactionTimeout).transaction;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Writing body : " + entry);
}
javaSpace.write(entry, tnx, Lease.FOREVER);
if (ExchangeHelper.isOutCapable(exchange)) {
OutEntry tmpl = new OutEntry();
tmpl.correlationId = ((InEntry)entry).correlationId;
OutEntry replyCamelEntry = null;
while (replyCamelEntry == null) {
replyCamelEntry = (OutEntry)javaSpace.take(tmpl, tnx, 100);
}
Object obj;
if (replyCamelEntry.binary) {
obj = replyCamelEntry.buffer;
} else {
ByteArrayInputStream bis = new ByteArrayInputStream(replyCamelEntry.buffer);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
}
exchange.getOut().setBody(obj);
}
if (tnx != null) {
tnx.commit();
}
}
@Override
protected void doStart() throws Exception {
// TODO: There should be a switch to enable/disable using this security hack
Utility.setSecurityPolicy("policy.all", "policy_producer.all");
javaSpace = JiniSpaceAccessor.findSpace(((JavaSpaceEndpoint) this.getEndpoint()).getRemaining(),
((JavaSpaceEndpoint) this.getEndpoint()).getSpaceName());
if (transactional) {
transactionHelper = TransactionHelper.getInstance(((JavaSpaceEndpoint) this.getEndpoint()).getRemaining());
}
(new File("policy_producer.all")).delete();
}
@Override
protected void doStop() throws Exception {
}
} |
Java | public class OvsdbClientServiceAdapter implements OvsdbClientService {
@Override
public OvsdbNodeId nodeId() {
return null;
}
/**
* Creates a mirror port. Mirrors the traffic
* that goes to selectDstPort or comes from
* selectSrcPort or packets containing selectVlan
* to mirrorPort or to all ports that trunk mirrorVlan.
*
* @param bridgeName the name of the bridge
* @param mirror the OVSDB mirror description
* @return true if mirror creation is successful, false otherwise
*/
@Override
public boolean createMirror(String bridgeName, OvsdbMirror mirror) {
return true;
}
/**
* Gets the Mirror uuid.
*
* @param mirrorName mirror name
* @return mirror uuid, empty if no uuid is found
*/
@Override
public String getMirrorUuid(String mirrorName) {
return null;
}
/**
* Gets mirroring statistics of the device.
*
* @param deviceId target device id
* @return set of mirroring statistics; empty if no mirror is found
*/
@Override
public Set<MirroringStatistics> getMirroringStatistics(DeviceId deviceId) {
return null;
}
@Override
public void applyQos(PortNumber portNumber, String qosId) {
}
@Override
public void removeQos(PortNumber portNumber) {
}
@Override
public boolean createQos(OvsdbQos ovsdbQos) {
return false;
}
@Override
public void dropQos(QosId qosId) {
}
@Override
public OvsdbQos getQos(QosId qosId) {
return null;
};
@Override
public Set<OvsdbQos> getQoses() {
return null;
}
@Override
public boolean createQueue(OvsdbQueue queue) {
return false;
}
@Override
public void dropQueue(QueueId queueId) {
}
@Override
public OvsdbQueue getQueue(QueueId queueId) {
return null;
};
@Override
public Set<OvsdbQueue> getQueues() {
return null;
}
/**
* Drops the configuration for mirror.
*
* @param mirroringName
*/
@Override
public void dropMirror(MirroringName mirroringName) {
}
@Override
public boolean createTunnel(String bridgeName, String portName, String tunnelType, Map<String, String> options) {
return true;
}
@Override
public void dropTunnel(IpAddress srcIp, IpAddress dstIp) {
}
@Override
public boolean createInterface(String bridgeName, OvsdbInterface ovsdbIface) {
return true;
}
@Override
public boolean dropInterface(String name) {
return true;
}
@Override
public void createBridge(String bridgeName) {
}
@Override
public boolean createBridge(String bridgeName, String dpid, List<ControllerInfo> controllers) {
return true;
}
@Override
public boolean createBridge(OvsdbBridge ovsdbBridge) {
return true;
}
@Override
public void dropBridge(String bridgeName) {
}
@Override
public Set<OvsdbBridge> getBridges() {
return null;
}
@Override
public Set<ControllerInfo> getControllers(DeviceId openflowDeviceId) {
return null;
}
@Override
public ControllerInfo localController() {
return null;
}
@Override
public void setControllersWithDeviceId(DeviceId deviceId, List<ControllerInfo> controllers) {
}
@Override
public void createPort(String bridgeName, String portName) {
}
@Override
public void dropPort(String bridgeName, String portName) {
}
@Override
public Set<OvsdbPort> getPorts() {
return null;
}
@Override
public boolean isConnected() {
return false;
}
@Override
public String getBridgeUuid(String bridgeName) {
return null;
}
@Override
public String getPortUuid(String portName, String bridgeUuid) {
return null;
}
@Override
public ListenableFuture<DatabaseSchema> getOvsdbSchema(String dbName) {
return null;
}
@Override
public ListenableFuture<TableUpdates> monitorTables(String dbName, String id) {
return null;
}
@Override
public DatabaseSchema getDatabaseSchema(String dbName) {
return null;
}
@Override
public Row getRow(String dbName, String tableName, String uuid) {
return null;
}
@Override
public void removeRow(String dbName, String tableName, String uuid) {
}
@Override
public void updateOvsdbStore(String dbName, String tableName, String uuid, Row row) {
}
@Override
public Set<OvsdbPort> getLocalPorts(Iterable<String> ifaceids) {
return null;
}
@Override
public void disconnect() {
}
@Override
public ListenableFuture<JsonNode> getSchema(List<String> dbnames) {
return null;
}
@Override
public ListenableFuture<List<String>> echo() {
return null;
}
@Override
public ListenableFuture<JsonNode> monitor(DatabaseSchema dbSchema, String monitorId) {
return null;
}
@Override
public ListenableFuture<List<String>> listDbs() {
return null;
}
@Override
public ListenableFuture<List<JsonNode>> transact(DatabaseSchema dbSchema, List<Operation> operations) {
return null;
}
@Override
public void createBridge(String bridgeName, String dpid, String exPortName) {
}
} |
Java | public class Clause extends VecLit {
// struct {
// unsigned mark : 2;
private byte mark;
// unsigned learnt : 1;
private boolean learnt;
// unsigned has_extra : 1;
private boolean has_extra;
// unsigned reloced : 1;
// unsigned size : 27; } header;
// union { Lit lit; float act; uint32_t abs; CRef rel; } data[0];
private float act;
private int abs;
//
// friend class ClauseAllocator;
//
// // NOTE: This constructor cannot be used directly (doesn't allocate enough memory).
// template<class V>
// Clause(const V& ps, bool use_extra, bool learnt) {
// header.mark = 0;
// header.learnt = learnt;
// header.has_extra = use_extra;
// header.reloced = 0;
// header.size = ps.size();
//
// for (int i = 0; i < ps.size(); i++)
// data[i].lit = ps[i];
//
// if (header.has_extra){
// if (header.learnt)
// data[header.size].act = 0;
// else
// calcAbstraction(); }
// }
public Clause(VecLit ps, boolean use_extra, boolean learnt) {
this.mark = 0;
this.learnt = learnt;
this.has_extra = use_extra;
for (int i = 0; i < ps.size(); ++i)
push(ps.get(i));
if (has_extra)
if (learnt)
act = 0;
else
calcAbstraction();
}
//
//public:
// void calcAbstraction() {
// assert(header.has_extra);
// uint32_t abstraction = 0;
// for (int i = 0; i < size(); i++)
// abstraction |= 1 << (var(data[i].lit) & 31);
// data[header.size].abs = abstraction; }
public void calcAbstraction() {
if (!has_extra)
throw new IllegalStateException("has_extra is false");
int abstraction = 0;
for (int i = 0; i < size(); ++i)
abstraction |= 1 << (get(i).var() & 31);
abs = abstraction;
}
//
//
// int size () const { return header.size; }
// defined in super class
// void shrink (int i) { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; }
// public void shrink(int i) {
// if (i <= 0 || i > size())
// throw new IllegalArgumentException("i");
// int newSize = size() - i;
// while (size() > newSize)
// pop();
// }
// void pop () { shrink(1); }
// defined in super class
// bool learnt () const { return header.learnt; }
public boolean learnt() { return learnt; }
// bool has_extra () const { return header.has_extra; }
public boolean has_extra() { return has_extra; }
// uint32_t mark () const { return header.mark; }
public int mark() { return mark; }
// void mark (uint32_t m) { header.mark = m; }
public void mark(int m) { mark = (byte)m; }
// const Lit& last () const { return data[header.size-1].lit; }
// defined in super class
//
// bool reloced () const { return header.reloced; }
public boolean reloced() { return false; }
// CRef relocation () const { return data[0].rel; }
public Clause relocation() { throw new UnsupportedOperationException(); }
// void relocate (CRef c) { header.reloced = 1; data[0].rel = c; }
public void relocate(Clause c) { throw new UnsupportedOperationException(); }
//
// // NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for
// // subsumption operations to behave correctly.
// Lit& operator [] (int i) { return data[i].lit; }
// use get(int index) in super class
// Lit operator [] (int i) const { return data[i].lit; }
// use get(int index) in super class
// operator const Lit* (void) const { return (Lit*)data; }
// unsupported
//
// float& activity () { assert(header.has_extra); return data[header.size].act; }
public float activity() {
if (!has_extra) throw new IllegalStateException("has_extra is false");
return act;
}
public float activity(double value) { return act = (float)value; }
// uint32_t abstraction () const { assert(header.has_extra); return data[header.size].abs; }
public int abstraction() {
if (!has_extra) throw new IllegalStateException("has_extra is false");
return abs;
}
//
// Lit subsumes (const Clause& other) const;
// void strengthen (Lit p);
//};
///*_________________________________________________________________________________________________
//|
//| subsumes : (other : const Clause&) -> Lit
//|
//| Description:
//| Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other'
//| by subsumption resolution.
//|
//| Result:
//| lit_Error - No subsumption or simplification
//| lit_Undef - Clause subsumes 'other'
//| p - The literal p can be deleted from 'other'
//|________________________________________________________________________________________________@*/
//inline Lit Clause::subsumes(const Clause& other) const
//{
// //if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0)
// //if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0))
// assert(!header.learnt); assert(!other.header.learnt);
// assert(header.has_extra); assert(other.header.has_extra);
// if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0)
// return lit_Error;
//
// Lit ret = lit_Undef;
// const Lit* c = (const Lit*)(*this);
// const Lit* d = (const Lit*)other;
//
// for (unsigned i = 0; i < header.size; i++) {
// // search for c[i] or ~c[i]
// for (unsigned j = 0; j < other.header.size; j++)
// if (c[i] == d[j])
// goto ok;
// else if (ret == lit_Undef && c[i] == ~d[j]){
// ret = c[i];
// goto ok;
// }
//
// // did not find it
// return lit_Error;
// ok:;
// }
//
// return ret;
//}
public Lit subsumes(Clause other) {
if (learnt || other.learnt)
throw new IllegalStateException("learnt is true");
if (!has_extra || other.has_extra)
throw new IllegalStateException("has_extra is false");
if (other.size() < size() || (abs & ~other.abs) != 0)
return Lit.ERROR;
Lit ret = Lit.UNDEF;
L: for (int i = 0; i < size(); i++) {
Lit cc = this.get(i);
// search for c[i] or ~c[i]
for (int j = 0; j < other.size(); j++) {
Lit dd = other.get(j);
if (cc.equals(dd))
continue L;
else if (ret.equals(Lit.UNDEF) && cc.equals(dd.not())) {
ret = cc;
continue L;
}
}
// did not find it
return Lit.ERROR;
}
return ret;
}
//
//inline void Clause::strengthen(Lit p)
//{
// remove(*this, p);
// calcAbstraction();
//}
public void strengthen(Lit p) {
remove(p);
calcAbstraction();
}
public static final Clause CRef_Undef = new Clause(new VecLit(), false, false);
} |
Java | public class ChunkHelper {
public static final String IHDR = "IHDR";
public static final byte[] b_IHDR = toBytes(IHDR);
public static final String PLTE = "PLTE";
public static final byte[] b_PLTE = toBytes(PLTE);
public static final String IDAT = "IDAT";
public static final byte[] b_IDAT = toBytes(IDAT);
public static final String IEND = "IEND";
public static final byte[] b_IEND = toBytes(IEND);
public static final String cHRM = "cHRM";
public static final String gAMA = "gAMA";
public static final String iCCP = "iCCP";
public static final String sBIT = "sBIT";
public static final String sRGB = "sRGB";
public static final String bKGD = "bKGD";
public static final String hIST = "hIST";
public static final String tRNS = "tRNS";
public static final String pHYs = "pHYs";
public static final String sPLT = "sPLT";
public static final String tIME = "tIME";
public static final String iTXt = "iTXt";
public static final String tEXt = "tEXt";
public static final String zTXt = "zTXt";
/*
* static auxiliary buffer. any method that uses this should synchronize against this
*/
private static byte[] tmpbuffer = new byte[4096];
ChunkHelper() {
}
/**
* Converts to bytes using Latin1 (ISO-8859-1)
*/
public static byte[] toBytes(String x) {
try {
return x.getBytes(PngHelperInternal.charsetLatin1name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* Converts to String using Latin1 (ISO-8859-1)
*/
public static String toString(byte[] x) {
try {
return new String(x, PngHelperInternal.charsetLatin1name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* Converts to String using Latin1 (ISO-8859-1)
*/
public static String toString(byte[] x, int offset, int len) {
try {
return new String(x, offset, len, PngHelperInternal.charsetLatin1name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* Converts to bytes using UTF-8
*/
public static byte[] toBytesUTF8(String x) {
try {
return x.getBytes(PngHelperInternal.charsetUTF8name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* Converts to string using UTF-8
*/
public static String toStringUTF8(byte[] x) {
try {
return new String(x, PngHelperInternal.charsetUTF8name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* Converts to string using UTF-8
*/
public static String toStringUTF8(byte[] x, int offset, int len) {
try {
return new String(x, offset, len, PngHelperInternal.charsetUTF8name);
} catch (UnsupportedEncodingException e) {
throw new PngBadCharsetException(e);
}
}
/**
* critical chunk : first letter is uppercase
*/
public static boolean isCritical(String id) {
return (Character.isUpperCase(id.charAt(0)));
}
/**
* public chunk: second letter is uppercase
*/
public static boolean isPublic(String id) { //
return (Character.isUpperCase(id.charAt(1)));
}
/**
* Safe to copy chunk: fourth letter is lower case
*/
public static boolean isSafeToCopy(String id) {
return (!Character.isUpperCase(id.charAt(3)));
}
/**
* "Unknown" just means that our chunk factory (even when it has been augmented by client code) did not recognize its
* id
*/
public static boolean isUnknown(PngChunk c) {
return c instanceof PngChunkUNKNOWN;
}
/**
* Finds position of null byte in array
*
* @param b
* @return -1 if not found
*/
public static int posNullByte(byte[] b) {
for (int i = 0; i < b.length; i++)
if (b[i] == 0)
return i;
return -1;
}
/**
* Decides if a chunk should be loaded, according to a ChunkLoadBehaviour
*
* @param id
* @param behav
* @return true/false
*/
public static boolean shouldLoad(String id, ChunkLoadBehaviour behav) {
if (isCritical(id))
return true;
switch (behav) {
case LOAD_CHUNK_ALWAYS:
return true;
case LOAD_CHUNK_IF_SAFE:
return isSafeToCopy(id);
case LOAD_CHUNK_NEVER:
return false;
}
return false; // should not reach here
}
public final static byte[] compressBytes(byte[] ori, boolean compress) {
return compressBytes(ori, 0, ori.length, compress);
}
public static byte[] compressBytes(byte[] ori, int offset, int len, boolean compress) {
try {
ByteArrayInputStream inb = new ByteArrayInputStream(ori, offset, len);
InputStream in = compress ? inb : new InflaterInputStream(inb);
ByteArrayOutputStream outb = new ByteArrayOutputStream();
OutputStream out = compress ? new DeflaterOutputStream(outb) : outb;
shovelInToOut(in, out);
in.close();
out.close();
return outb.toByteArray();
} catch (Exception e) {
throw new PngjException(e);
}
}
/**
* Shovels all data from an input stream to an output stream.
*/
private static void shovelInToOut(InputStream in, OutputStream out) throws IOException {
synchronized (tmpbuffer) {
int len;
while ((len = in.read(tmpbuffer)) > 0) {
out.write(tmpbuffer, 0, len);
}
}
}
/**
* Returns only the chunks that "match" the predicate
* <p/>
* See also trimList()
*/
public static List<PngChunk> filterList(List<PngChunk> target, ChunkPredicate predicateKeep) {
List<PngChunk> result = new ArrayList<PngChunk>();
for (PngChunk element : target) {
if (predicateKeep.match(element)) {
result.add(element);
}
}
return result;
}
/**
* Remove (in place) the chunks that "match" the predicate
* <p/>
* See also filterList
*/
public static int trimList(List<PngChunk> target, ChunkPredicate predicateRemove) {
Iterator<PngChunk> it = target.iterator();
int cont = 0;
while (it.hasNext()) {
PngChunk c = it.next();
if (predicateRemove.match(c)) {
it.remove();
cont++;
}
}
return cont;
}
/**
* Adhoc criteria: two ancillary chunks are "equivalent" ("practically same type") if they have same id and (perhaps,
* if multiple are allowed) if the match also in some "internal key" (eg: key for string values, palette for sPLT,
* etc)
* <p/>
* When we use this method, we implicitly assume that we don't allow/expect two "equivalent" chunks in a single PNG
* <p/>
* Notice that the use of this is optional, and that the PNG standard actually allows text chunks that have same key
*
* @return true if "equivalent"
*/
public static final boolean equivalent(PngChunk c1, PngChunk c2) {
if (c1 == c2)
return true;
if (c1 == null || c2 == null || !c1.id.equals(c2.id))
return false;
if (c1.crit)
return false;
// same id
if (c1.getClass() != c2.getClass())
return false; // should not happen
if (!c2.allowsMultiple())
return true;
if (c1 instanceof PngChunkTextVar) {
return ((PngChunkTextVar) c1).getKey().equals(((PngChunkTextVar) c2).getKey());
}
if (c1 instanceof PngChunkSPLT) {
return ((PngChunkSPLT) c1).getPalName().equals(((PngChunkSPLT) c2).getPalName());
}
// unknown chunks that allow multiple? consider they don't match
return false;
}
public static boolean isText(PngChunk c) {
return c instanceof PngChunkTextVar;
}
} |
Java | public class IgniteSpiMBeanAdapter implements IgniteSpiManagementMBean {
/** */
protected IgniteSpiAdapter spiAdapter;
/**
* Constructor
*
* @param spiAdapter Spi implementation.
*/
public IgniteSpiMBeanAdapter(IgniteSpiAdapter spiAdapter) {
this.spiAdapter = spiAdapter;
}
/** {@inheritDoc} */
@Override public final String getStartTimestampFormatted() {
return DateFormat.getDateTimeInstance().format(new Date(spiAdapter.getStartTstamp()));
}
/** {@inheritDoc} */
@Override public final String getUpTimeFormatted() {
return X.timeSpan2DHMSM(getUpTime());
}
/** {@inheritDoc} */
@Override public final long getStartTimestamp() {
return spiAdapter.getStartTstamp();
}
/** {@inheritDoc} */
@Override public final long getUpTime() {
final long startTstamp = spiAdapter.getStartTstamp();
return startTstamp == 0 ? 0 : U.currentTimeMillis() - startTstamp;
}
/** {@inheritDoc} */
@Override public UUID getLocalNodeId() {
return spiAdapter.ignite.cluster().localNode().id();
}
/** {@inheritDoc} */
@Override public final String getIgniteHome() {
return spiAdapter.ignite.configuration().getIgniteHome();
}
/** {@inheritDoc} */
@Override public String getName() {
return spiAdapter.getName();
}
} |
Java | public class XmlPath {
public static XmlPathConfig config = null;
private final CompatibilityMode mode;
private LazyXmlParser lazyXmlParser;
private XmlPathConfig xmlPathConfig = null;
/**
* Parameters for groovy console (not initialized here to save memory for queries that don't use params)
*/
private Map<String, Object> params;
private String rootPath = "";
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public XmlPath(String text) {
this(XML, text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public XmlPath(InputStream stream) {
this(XML, stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public XmlPath(InputSource source) {
this(XML, source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public XmlPath(File file) {
this(XML, file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public XmlPath(Reader reader) {
this(XML, reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public XmlPath(URI uri) {
this(XML, uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param text The text containing the XML document
*/
public XmlPath(CompatibilityMode mode, String text) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseText(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param stream The stream containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputStream stream) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseInputStream(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param source The source containing the XML document
*/
public XmlPath(CompatibilityMode mode, InputSource source) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseInputSource(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param file The file containing the XML document
*/
public XmlPath(CompatibilityMode mode, File file) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseFile(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param reader The reader containing the XML document
*/
public XmlPath(CompatibilityMode mode, Reader reader) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseReader(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param mode The compatibility mode
* @param uri The URI containing the XML document
*/
public XmlPath(CompatibilityMode mode, URI uri) {
Validate.notNull(mode, "Compatibility mode cannot be null");
this.mode = mode;
lazyXmlParser = parseURI(uri);
}
/**
* Configure XmlPath to use a specific JAXB object mapper factory
*
* @param factory The JAXB object mapper factory instance
* @return a new XmlPath instance
*/
public XmlPath using(JAXBObjectMapperFactory factory) {
return new XmlPath(this, getXmlPathConfig().jaxbObjectMapperFactory(factory));
}
/**
* Configure XmlPath to with a specific XmlPathConfig.
*
* @param config The XmlPath config
* @return a new XmlPath instance
*/
public XmlPath using(XmlPathConfig config) {
return new XmlPath(this, config);
}
private XmlPath(XmlPath xmlPath, XmlPathConfig config) {
this.xmlPathConfig = config;
this.mode = xmlPath.mode;
this.lazyXmlParser = xmlPath.lazyXmlParser.changeCompatibilityMode(mode).changeConfig(config);
if (xmlPath.params != null) {
this.params = new HashMap<String, Object>(xmlPath.params);
}
}
/**
* Get the entire XML graph as an Object
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @return The XML Node. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node get() {
return (Node) get("$");
}
/**
* Get the result of an XML path expression. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @param <T> The type of the return value.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> T get(String path) {
AssertParameter.notNull(path, "path");
return getFromPath(path, true);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @param <T> The list type
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path) {
return getAsList(path);
}
/**
* Get the result of an XML path expression as a list. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @param genericType The generic list type
* @param <T> The type
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <T> List<T> getList(String path, Class<T> genericType) {
return getAsList(path, genericType);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path) {
return get(path);
}
/**
* Get the result of an XML path expression as a map. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @param keyType The type of the expected key
* @param valueType The type of the expected value
* @param <K> The type of the expected key
* @param <V> The type of the expected value
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public <K, V> Map<K, V> getMap(String path, Class<K> keyType, Class<V> valueType) {
final Map<K, V> originalMap = get(path);
final Map<K, V> newMap = new HashMap<K, V>();
for (Entry<K, V> entry : originalMap.entrySet()) {
final K key = entry.getKey() == null ? null : convertObjectTo(entry.getKey(), keyType);
final V value = entry.getValue() == null ? null : convertObjectTo(entry.getValue(), valueType);
newMap.put(key, value);
}
return Collections.unmodifiableMap(newMap);
}
/**
* Get an XML document as a Java Object.
*
* @param objectType The type of the java object.
* @param <T> The type of the java object
* @return A Java object representation of the XML document
*/
public <T> T getObject(String path, Class<T> objectType) {
Object object = getFromPath(path, false);
return getObjectAsType(object, objectType);
}
private <T> T getObjectAsType(Object object, Class<T> objectType) {
if (object == null) {
return null;
} else if (object instanceof GPathResult) {
try {
object = XmlUtil.serialize((GPathResult) object);
} catch (GroovyRuntimeException e) {
throw new IllegalArgumentException("Failed to convert XML to Java Object. If you're trying convert to a list then use the getList method instead.", e);
}
} else if (object instanceof groovy.util.slurpersupport.Node) {
object = GroovyNodeSerializer.toXML((groovy.util.slurpersupport.Node) object);
}
XmlPathConfig cfg = new XmlPathConfig(getXmlPathConfig());
if (cfg.hasCustomJaxbObjectMapperFactory()) {
cfg = cfg.defaultParserType(XmlParserType.JAXB);
}
if (!(object instanceof String)) {
throw new IllegalStateException("Internal error: XML object was not an instance of String, please report to the REST Assured mailing-list.");
}
return XmlObjectDeserializer.deserialize((String) object, objectType, cfg);
}
private <T> T getFromPath(String path, boolean convertToJavaObject) {
final GPathResult input = lazyXmlParser.invoke();
final XMLAssertion xmlAssertion = new XMLAssertion();
if (params != null) {
xmlAssertion.setParams(params);
}
final String root = rootPath.equals("") ? rootPath : rootPath.endsWith(".") ? rootPath : rootPath + ".";
xmlAssertion.setKey(root + path);
return (T) xmlAssertion.getResult(input, convertToJavaObject, true);
}
/**
* Get the result of an XML path expression as an int. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public int getInt(String path) {
final Object object = get(path);
return convertObjectTo(object, Integer.class);
}
/**
* Get the result of an XML path expression as a boolean. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public boolean getBoolean(String path) {
Object object = get(path);
return convertObjectTo(object, Boolean.class);
}
/**
* Get the result of an XML path expression as a {@link Node}. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public Node getNode(String path) {
return convertObjectTo(get(path), Node.class);
}
/**
* Get the result of an XML path expression as a {@link NodeChildren}. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public NodeChildren getNodeChildren(String path) {
return convertObjectTo(get(path), NodeChildren.class);
}
/**
* Get the result of an XML path expression as a char. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public char getChar(String path) {
Object object = get(path);
return convertObjectTo(object, Character.class);
}
/**
* Get the result of an XML path expression as a byte. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public byte getByte(String path) {
Object object = get(path);
return convertObjectTo(object, Byte.class);
}
/**
* Get the result of an XML path expression as a short. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public short getShort(String path) {
Object object = get(path);
return convertObjectTo(object, Short.class);
}
/**
* Get the result of an XML path expression as a float. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public float getFloat(String path) {
Object object = get(path);
return convertObjectTo(object, Float.class);
}
/**
* Get the result of an XML path expression as a double. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public double getDouble(String path) {
Object object = get(path);
return convertObjectTo(object, Double.class);
}
/**
* Get the result of an XML path expression as a long. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public long getLong(String path) {
Object object = get(path);
return convertObjectTo(object, Long.class);
}
/**
* Get the result of an XML path expression as a string. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public String getString(String path) {
Object object = get(path);
return convertObjectTo(object, String.class);
}
/**
* Get the result of an XML path expression as a UUID. For syntax details please refer to
* <a href="http://www.groovy-lang.org/processing-xml.html#_manipulating_xml">this</a> url.
*
* @param path The XML path.
* @return The object matching the XML path. A {@link java.lang.ClassCastException} will be thrown if the object
* cannot be casted to the expected type.
*/
public UUID getUUID(String path) {
Object object = get(path);
return convertObjectTo(object, UUID.class);
}
/**
* Add a parameter for the expression. Example:
* <pre>
* String type = System.console().readLine();
* List<Map> books = with(Object).param("type", type).get("shopping.category.findAll { it.@type == type}");
* </pre>
*
* @param key The name of the parameter. Just use this name in your expression as a variable
* @param value The value of the parameter
* @return New XmlPath instance with the parameter set
*/
public XmlPath param(String key, Object value) {
XmlPath newP = new XmlPath(this, getXmlPathConfig());
if (newP.params == null) {
newP.params = new HashMap<String, Object>();
}
newP.params.put(key, value);
return newP;
}
/**
* Peeks into the XML/HTML that XmlPath will parse by printing it to the console. You can
* continue working with XmlPath afterwards. This is mainly for debug purposes. If you want to return a prettified version of the content
* see {@link #prettify()}. If you want to return a prettified version of the content and also print it to the console use {@link #prettyPrint()}.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by XmlPath) and the XML is rendered
* from this data structure.
* </p>
*
* @return The same XmlPath instance
*/
public XmlPath peek() {
final GPathResult result = lazyXmlParser.invoke();
final String render = XmlRenderer.render(result);
System.out.println(render);
return this;
}
/**
* Peeks into the XML/HTML that XmlPath will parse by printing it to the console in a prettified manner. You can
* continue working with XmlPath afterwards. This is mainly for debug purposes. If you want to return a prettified version of the content
* see {@link #prettify()}. If you want to return a prettified version of the content and also print it to the console use {@link #prettyPrint()}.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by XmlPath) and the XML is rendered
* from this data structure.
* </p>
*
* @return The same XmlPath instance
*/
public XmlPath prettyPeek() {
final GPathResult result = lazyXmlParser.invoke();
final String prettify = XmlPrettifier.prettify(result);
System.out.println(prettify);
return this;
}
/**
* Get the XML as a prettified string.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by XmlPath) and the XML is rendered
* from this data structure.
* </p>
*
* @return The XML as a prettified String.
*/
public String prettify() {
return XmlPrettifier.prettify(lazyXmlParser.invoke());
}
/**
* Get and print the XML as a prettified string.
* <p/>
* <p>
* Note that the content is not guaranteed to be looking exactly like the it does at the source. This is because once you peek
* the content has been downloaded and transformed into another data structure (used by XmlPath) and the XML is rendered
* from this data structure.
* </p>
*
* @return The XML as a prettified String.
*/
public String prettyPrint() {
final String pretty = prettify();
System.out.println(pretty);
return pretty;
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath given(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath given(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath given(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath given(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath given(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath given(URI uri) {
return new XmlPath(uri);
}
public static XmlPath with(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath with(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath with(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath with(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath with(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath with(URI uri) {
return new XmlPath(uri);
}
/**
* Instantiate a new XmlPath instance.
*
* @param stream The stream containing the XML document
*/
public static XmlPath from(InputStream stream) {
return new XmlPath(stream);
}
/**
* Instantiate a new XmlPath instance.
*
* @param text The text containing the XML document
*/
public static XmlPath from(String text) {
return new XmlPath(text);
}
/**
* Instantiate a new XmlPath instance.
*
* @param source The source containing the XML document
*/
public static XmlPath from(InputSource source) {
return new XmlPath(source);
}
/**
* Instantiate a new XmlPath instance.
*
* @param file The file containing the XML document
*/
public static XmlPath from(File file) {
return new XmlPath(file);
}
/**
* Instantiate a new XmlPath instance.
*
* @param reader The reader containing the XML document
*/
public static XmlPath from(Reader reader) {
return new XmlPath(reader);
}
/**
* Instantiate a new XmlPath instance.
*
* @param uri The URI containing the XML document
*/
public static XmlPath from(URI uri) {
return new XmlPath(uri);
}
private LazyXmlParser parseText(final String text) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parseText(text);
}
};
}
/**
* Set the root path of the document so that you don't need to write the entire path. E.g.
* <pre>
* final XmlPath xmlPath = new XmlPath(XML).setRoot("shopping.category.item");
* assertThat(xmlPath.getInt("size()"), equalTo(5));
* assertThat(xmlPath.getList("children().list()", String.class), hasItem("Pens"));
* </pre>
*
* @param rootPath The root path to use.
*/
public XmlPath setRoot(String rootPath) {
AssertParameter.notNull(rootPath, "Root path");
this.rootPath = rootPath;
return this;
}
private <T> List<T> getAsList(String path) {
return getAsList(path, null);
}
private <T> List<T> getAsList(String path, final Class<?> explicitType) {
Object returnObject = get(path);
if (returnObject instanceof NodeChildren) {
final NodeChildren nodeChildren = (NodeChildren) returnObject;
returnObject = convertElementsListTo(nodeChildren.list(), explicitType);
} else if (!(returnObject instanceof List)) {
final List<T> asList = new ArrayList<T>();
if (returnObject != null) {
final T e;
if (explicitType == null) {
e = (T) returnObject.toString();
} else {
e = (T) convertObjectTo(returnObject, explicitType);
}
asList.add(e);
}
returnObject = asList;
} else if (explicitType != null) {
final List<?> returnObjectAsList = (List<?>) returnObject;
final List<T> convertedList = new ArrayList<T>();
for (Object o : returnObjectAsList) {
convertedList.add((T) convertObjectTo(o, explicitType));
}
returnObject = convertedList;
}
return returnObject == null ? null : Collections.unmodifiableList((List<T>) returnObject);
}
private List<Object> convertElementsListTo(List<Node> list, Class<?> explicitType) {
List<Object> convertedList = new ArrayList<Object>();
if (list != null && list.size() > 0) {
for (Node node : list) {
if (explicitType == null) {
convertedList.add(node.toString());
} else {
convertedList.add(convertObjectTo(node, explicitType));
}
}
}
return convertedList;
}
private <T> T convertObjectTo(Object object, Class<T> explicitType) {
if (object instanceof NodeBase && !ObjectConverter.canConvert(object, explicitType)) {
return getObjectAsType(((NodeBase) object).getBackingGroovyObject(), explicitType);
}
return ObjectConverter.convertObjectTo(object, explicitType);
}
private LazyXmlParser parseInputStream(final InputStream stream) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(stream);
}
};
}
private LazyXmlParser parseReader(final Reader reader) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(reader);
}
};
}
private LazyXmlParser parseFile(final File file) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(file);
}
};
}
private LazyXmlParser parseURI(final URI uri) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(uri.toString());
}
};
}
private LazyXmlParser parseInputSource(final InputSource source) {
return new LazyXmlParser(getXmlPathConfig(), mode) {
protected GPathResult method(XmlSlurper slurper) throws Exception {
return slurper.parse(source);
}
};
}
private XmlPathConfig getXmlPathConfig() {
XmlPathConfig cfg;
if (config == null && xmlPathConfig == null) {
cfg = new XmlPathConfig();
} else if (xmlPathConfig != null) {
cfg = xmlPathConfig;
} else {
cfg = config;
}
return cfg;
}
private static abstract class LazyXmlParser {
protected abstract GPathResult method(XmlSlurper slurper) throws Exception;
private volatile XmlPathConfig config;
private volatile CompatibilityMode compatibilityMode;
protected LazyXmlParser(XmlPathConfig config, CompatibilityMode compatibilityMode) {
this.config = config;
this.compatibilityMode = compatibilityMode;
}
public LazyXmlParser changeCompatibilityMode(CompatibilityMode mode) {
this.compatibilityMode = mode;
return this;
}
public LazyXmlParser changeConfig(XmlPathConfig config) {
this.config = config;
return this;
}
private GPathResult input;
private boolean isInputParsed;
public synchronized GPathResult invoke() {
if (isInputParsed) {
return input;
}
isInputParsed = true;
try {
final XmlSlurper slurper;
if (compatibilityMode == XML) {
slurper = new XmlSlurper(config.isValidating(), config.isNamespaceAware(), config.isAllowDocTypeDeclaration());
} else {
XMLReader p = new org.ccil.cowan.tagsoup.Parser();
slurper = new XmlSlurper(p);
}
// Apply features
Map<String, Boolean> features = config.features();
for (Entry<String, Boolean> feature : features.entrySet()) {
slurper.setFeature(feature.getKey(), feature.getValue());
}
// Apply properties
Map<String, Object> properties = config.properties();
for (Entry<String, Object> feature : properties.entrySet()) {
slurper.setProperty(feature.getKey(), feature.getValue());
}
final GPathResult result = method(slurper);
if (config.hasDeclaredNamespaces()) {
result.declareNamespace(config.declaredNamespaces());
}
input = result;
return input;
} catch (Exception e) {
throw new XmlPathException("Failed to parse the XML document", e);
}
}
}
public static enum CompatibilityMode {
XML, HTML
}
/**
* Resets static XmlPath configuration to default values
*/
public static void reset() {
XmlPath.config = null;
}
} |
Java | public static class Line
extends DataObject
{
/**
* The address of the line.
*/
private String address;
/**
* The display name of the line.
*/
private String name;
/**
* The group under witch to display the line.
*/
private String group;
/**
* Asterisk pickup prefix.
*/
private String pickupTemplate;
/**
* The parent provider.
*/
private ProtocolProviderService provider;
/**
* Constructs Line.
*
* @param address the address of the line.
* @param name the display name if any
* @param group the group name if any
* @param pickup the pickup dial template
* @param provider the parent provider.
*/
public Line(String address, String name, String group, String pickup,
ProtocolProviderService provider)
{
this.address = address;
this.name = name;
this.group = group;
this.pickupTemplate = pickup;
this.provider = provider;
}
/**
* The address of the line.
* @return address of the line.
*/
public String getAddress()
{
return address;
}
/**
* The name of the line.
* @return the name of the line.
*/
public String getName()
{
return name;
}
/**
* The group name.
* @return the group name.
*/
public String getGroup()
{
return group;
}
/**
* The pickup template.
* @return the pickup template.
*/
public String getPickupTemplate()
{
return pickupTemplate;
}
/**
* The provider.
* @return the provider.
*/
public ProtocolProviderService getProvider()
{
return provider;
}
@Override
public boolean equals(Object o)
{
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
return address.equals(line.address);
}
@Override
public int hashCode()
{
return address.hashCode();
}
} |
Java | class WeakSyncListener implements FHSyncListener {
private final WeakReference<FHSyncListener> ref;
public WeakSyncListener(FHSyncListener listener) {
ref = new WeakReference<>(listener);
}
public boolean hasLeaked() {
return getWrapped() == null;
}
public FHSyncListener getWrapped() {
return ref.get();
}
@Override
public void onSyncStarted(final NotificationMessage message) {
notNullDo(ref.get(), l -> onSyncStarted(message));
}
@Override
public void onSyncCompleted(NotificationMessage message) {
notNullDo(ref.get(), l -> onSyncCompleted(message));
}
@Override
public void onUpdateOffline(NotificationMessage message) {
notNullDo(ref.get(), l -> onUpdateOffline(message));
}
@Override
public void onCollisionDetected(NotificationMessage message) {
notNullDo(ref.get(), l -> onCollisionDetected(message));
}
@Override
public void onRemoteUpdateFailed(NotificationMessage message) {
notNullDo(ref.get(), l -> onRemoteUpdateFailed(message));
}
@Override
public void onRemoteUpdateApplied(NotificationMessage message) {
notNullDo(ref.get(), l -> onRemoteUpdateFailed(message));
}
@Override
public void onLocalUpdateApplied(NotificationMessage message) {
notNullDo(ref.get(), l -> onLocalUpdateApplied(message));
}
@Override
public void onDeltaReceived(NotificationMessage message) {
notNullDo(ref.get(), l -> onDeltaReceived(message));
}
@Override
public void onSyncFailed(NotificationMessage message) {
notNullDo(ref.get(), l -> onSyncFailed(message));
}
@Override
public void onClientStorageFailed(NotificationMessage message) {
notNullDo(ref.get(), l -> onClientStorageFailed(message));
}
} |
Java | public class ConnectionImpl implements Session {
private ManagedConnectionImpl managedConnection;
private SessionImpl session;
public ConnectionImpl(ManagedConnectionImpl managedConnection) {
this.managedConnection = managedConnection;
}
/*
* ----- callbacks -----
*/
/**
* Called by {@link ManagedConnectionImpl#associateConnection}.
*/
protected ManagedConnectionImpl getManagedConnection() {
return managedConnection;
}
/**
* Called by {@link ManagedConnectionImpl#associateConnection}.
*/
protected void setManagedConnection(ManagedConnectionImpl managedConnection) {
this.managedConnection = managedConnection;
}
/**
* Called by {@link ManagedConnectionImpl#addConnection}.
*/
protected void associate(SessionImpl session) {
this.session = session;
}
/**
* Called by {@link ManagedConnectionImpl#removeConnection}.
*/
protected void disassociate() {
closeStillOpenQueryResults();
session = null;
}
/*
* ----- javax.resource.cci.Connection -----
*/
protected Throwable closeTrace;
@Override
public void close() throws ResourceException {
if (managedConnection == null) {
IllegalStateException error = new IllegalStateException("connection already closed " + this);
error.addSuppressed(closeTrace);
throw error;
}
try {
managedConnection.close(this);
} finally {
closeTrace = new Throwable("close stack trace");
managedConnection = null;
}
}
@Override
public Interaction createInteraction() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public LocalTransaction getLocalTransaction() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public ConnectionMetaData getMetaData() throws ResourceException {
throw new UnsupportedOperationException();
}
@Override
public ResultSetInfo getResultSetInfo() throws ResourceException {
throw new UnsupportedOperationException();
}
/*
* ----- org.nuxeo.ecm.core.storage.sql.Session -----
*/
private Session getSession() {
if (session == null) {
throw new NuxeoException("Cannot use closed connection handle: " + this);
}
return session;
}
@Override
public Mapper getMapper() {
return getSession().getMapper();
}
@Override
public boolean isLive() {
return session != null && session.isLive();
}
@Override
public String getRepositoryName() {
return getSession().getRepositoryName();
}
@Override
public Model getModel() {
return getSession().getModel();
}
@Override
public void save() {
getSession().save();
}
@Override
public Node getRootNode() {
return getSession().getRootNode();
}
@Override
public Node getNodeById(Serializable id) {
return getSession().getNodeById(id);
}
@Override
public List<Node> getNodesByIds(Collection<Serializable> ids) {
return getSession().getNodesByIds(ids);
}
@Override
public Node getNodeByPath(String path, Node node) {
return getSession().getNodeByPath(path, node);
}
@Override
public boolean addMixinType(Node node, String mixin) {
return getSession().addMixinType(node, mixin);
}
@Override
public boolean removeMixinType(Node node, String mixin) {
return getSession().removeMixinType(node, mixin);
}
@Override
public ScrollResult<String> scroll(String query, int batchSize, int keepAliveSeconds) {
return getSession().scroll(query, batchSize, keepAliveSeconds);
}
@Override
public ScrollResult<String> scroll(String query, QueryFilter queryFilter, int batchSize, int keepAliveSeconds) {
return getSession().scroll(query, queryFilter, batchSize, keepAliveSeconds);
}
@Override
public ScrollResult<String> scroll(String scrollId) {
return getSession().scroll(scrollId);
}
@Override
public boolean hasChildNode(Node parent, String name, boolean complexProp) {
return getSession().hasChildNode(parent, name, complexProp);
}
@Override
public Node getChildNode(Node parent, String name, boolean complexProp) {
return getSession().getChildNode(parent, name, complexProp);
}
@Override
public boolean hasChildren(Node parent, boolean complexProp) {
return getSession().hasChildren(parent, complexProp);
}
@Override
public List<Node> getChildren(Node parent, String name, boolean complexProp) {
return getSession().getChildren(parent, name, complexProp);
}
@Override
public Node addChildNode(Node parent, String name, Long pos, String typeName, boolean complexProp) {
return getSession().addChildNode(parent, name, pos, typeName, complexProp);
}
@Override
public Node addChildNode(Serializable id, Node parent, String name, Long pos, String typeName,
boolean complexProp) {
return getSession().addChildNode(id, parent, name, pos, typeName, complexProp);
}
@Override
public void removeNode(Node node, Consumer<Node> beforeRecordRemove) {
getSession().removeNode(node, beforeRecordRemove);
}
@Override
public void removeNode(Node node) {
getSession().removeNode(node);
}
@Override
public void removePropertyNode(Node node) {
getSession().removePropertyNode(node);
}
@Override
public Node getParentNode(Node node) {
return getSession().getParentNode(node);
}
@Override
public String getPath(Node node) {
return getSession().getPath(node);
}
@Override
public void orderBefore(Node node, Node src, Node dest) {
getSession().orderBefore(node, src, dest);
}
@Override
public Node move(Node source, Node parent, String name) {
return getSession().move(source, parent, name);
}
@Override
public Node copy(Node source, Node parent, String name, Consumer<Node> afterRecordCopy) {
return getSession().copy(source, parent, name, afterRecordCopy);
}
@Override
public Node copy(Node source, Node parent, String name) {
return getSession().copy(source, parent, name);
}
@Override
public Node checkIn(Node node, String label, String checkinComment) {
return getSession().checkIn(node, label, checkinComment);
}
@Override
public void checkOut(Node node) {
getSession().checkOut(node);
}
@Override
public void restore(Node node, Node version) {
getSession().restore(node, version);
}
@Override
public Node getVersionByLabel(Serializable versionSeriesId, String label) {
return getSession().getVersionByLabel(versionSeriesId, label);
}
@Override
public List<Node> getVersions(Serializable versionSeriesId) {
return getSession().getVersions(versionSeriesId);
}
@Override
public Node getLastVersion(Serializable versionSeriesId) {
return getSession().getLastVersion(versionSeriesId);
}
@Override
public List<Node> getProxies(Node document, Node parent) {
return getSession().getProxies(document, parent);
}
@Override
public List<Node> getProxies(Node document) {
return getSession().getProxies(document);
}
@Override
public void setProxyTarget(Node proxy, Serializable targetId) {
getSession().setProxyTarget(proxy, targetId);
}
@Override
public Node addProxy(Serializable targetId, Serializable versionSeriesId, Node parent, String name, Long pos) {
return getSession().addProxy(targetId, versionSeriesId, parent, name, pos);
}
@Override
public PartialList<Serializable> query(String query, QueryFilter queryFilter, boolean countTotal) {
return getSession().query(query, queryFilter, countTotal);
}
@Override
public PartialList<Serializable> query(String query, String queryType, QueryFilter queryFilter, long countUpTo) {
return getSession().query(query, queryType, queryFilter, countUpTo);
}
@Override
public IterableQueryResult queryAndFetch(String query, String queryType, QueryFilter queryFilter,
Object... params) {
IterableQueryResult result = getSession().queryAndFetch(query, queryType, queryFilter, params);
noteQueryResult(result);
return result;
}
@Override
public IterableQueryResult queryAndFetch(String query, String queryType, QueryFilter queryFilter,
boolean distinctDocuments, Object... params) {
IterableQueryResult result = getSession().queryAndFetch(query, queryType, queryFilter, distinctDocuments,
params);
noteQueryResult(result);
return result;
}
@Override
public PartialList<Map<String,Serializable>> queryProjection(String query, String queryType, QueryFilter queryFilter,
boolean distinctDocuments, long countUpTo, Object... params) {
return getSession().queryProjection(query, queryType, queryFilter, distinctDocuments, countUpTo, params);
}
public static class QueryResultContextException extends Exception {
private static final long serialVersionUID = 1L;
public final IterableQueryResult queryResult;
public QueryResultContextException(IterableQueryResult queryResult) {
super("queryAndFetch call context");
this.queryResult = queryResult;
}
}
protected final Set<QueryResultContextException> queryResults = new HashSet<>();
protected void noteQueryResult(IterableQueryResult result) {
queryResults.add(new QueryResultContextException(result));
}
protected void closeStillOpenQueryResults() {
for (QueryResultContextException context : queryResults) {
if (!context.queryResult.mustBeClosed()) {
continue;
}
try {
context.queryResult.close();
} catch (RuntimeException e) {
LogFactory.getLog(ConnectionImpl.class).error("Cannot close query result", e);
} finally {
LogFactory.getLog(ConnectionImpl.class)
.warn("Closing a query results for you, check stack trace for allocating point", context);
}
}
queryResults.clear();
}
@Override
public LockManager getLockManager() {
return getSession().getLockManager();
}
@Override
public void requireReadAclsUpdate() {
if (session != null) {
session.requireReadAclsUpdate();
}
}
@Override
public void updateReadAcls() {
getSession().updateReadAcls();
}
@Override
public void rebuildReadAcls() {
getSession().rebuildReadAcls();
}
@Override
public boolean isFulltextStoredInBlob() {
return getSession().isFulltextStoredInBlob();
}
@Override
public Map<String, String> getBinaryFulltext(Serializable id) {
return getSession().getBinaryFulltext(id);
}
@Override
public boolean isChangeTokenEnabled() {
return getSession().isChangeTokenEnabled();
}
@Override
public void markUserChange(Serializable id) {
getSession().markUserChange(id);
}
} |
Java | public class ClassTypeNodeSerializer implements TypeSerializer<Object> {
@Override
public Object deserialize(@NonNull TypeToken<?> type, @NonNull ConfigurationNode value) throws ObjectMappingException {
Class<?> clazz = getInstantiableType(type, value.getNode("__class__").getString());
return NotSoStupidObjectMapper.forClass(clazz).bindToNew().populate(value);
}
private Class<?> getInstantiableType(TypeToken<?> type, String configuredName) throws ObjectMappingException {
Class<?> retClass;
if (type.getRawType().isInterface() || Modifier.isAbstract(type.getRawType().getModifiers())) {
if (configuredName == null) {
throw new ObjectMappingException("No available configured type for instances of " + type);
} else {
try {
retClass = Class.forName(configuredName);
} catch (ClassNotFoundException e) {
throw new ObjectMappingException("Unknown class of object " + configuredName, e);
}
if (!type.getRawType().isAssignableFrom(retClass)) {
throw new ObjectMappingException("Configured type " + configuredName + " does not extend "
+ type.getRawType().getCanonicalName());
}
}
} else {
retClass = type.getRawType();
}
return retClass;
}
@Override
@SuppressWarnings("unchecked")
public void serialize(@NonNull TypeToken<?> type, @Nullable Object obj, @NonNull ConfigurationNode value) throws ObjectMappingException {
if (type.getRawType().isInterface() || Modifier.isAbstract(type.getRawType().getModifiers())) {
// serialize obj's concrete type rather than the interface/abstract class
value.getNode("__class__").setValue(obj.getClass().getName());
}
NotSoStupidObjectMapper.forObject(obj).serialize(value);
}
} |
Java | public class ScopeFilter
extends AbstractArtifactsFilter
{
private String includeScope;
private String excludeScope;
/**
* <p>Constructor for ScopeFilter.</p>
*
* @param includeScope the scope to be included.
* @param excludeScope the scope to be excluded.
*/
public ScopeFilter( String includeScope, String excludeScope )
{
this.includeScope = includeScope;
this.excludeScope = excludeScope;
}
/**
* {@inheritDoc}
*
* This function determines if filtering needs to be performed. Excludes are
* ignored if Includes are used.
*/
public Set<Artifact> filter( Set<Artifact> artifacts )
throws ArtifactFilterException
{
Set<Artifact> results = artifacts;
if ( StringUtils.isNotEmpty( includeScope ) )
{
if ( !Artifact.SCOPE_COMPILE.equals( includeScope ) && !Artifact.SCOPE_TEST.equals( includeScope )
&& !Artifact.SCOPE_PROVIDED.equals( includeScope ) && !Artifact.SCOPE_RUNTIME.equals( includeScope )
&& !Artifact.SCOPE_SYSTEM.equals( includeScope ) )
{
throw new ArtifactFilterException( "Invalid Scope in includeScope: " + includeScope );
}
results = new LinkedHashSet<>();
if ( Artifact.SCOPE_PROVIDED.equals( includeScope ) || Artifact.SCOPE_SYSTEM.equals( includeScope ) )
{
results = includeSingleScope( artifacts, includeScope );
}
else
{
ArtifactFilter saf = new ScopeArtifactFilter( includeScope );
for ( Artifact artifact : artifacts )
{
if ( saf.include( artifact ) )
{
results.add( artifact );
}
}
}
}
else if ( StringUtils.isNotEmpty( excludeScope ) )
{
if ( !Artifact.SCOPE_COMPILE.equals( excludeScope ) && !Artifact.SCOPE_TEST.equals( excludeScope )
&& !Artifact.SCOPE_PROVIDED.equals( excludeScope ) && !Artifact.SCOPE_RUNTIME.equals( excludeScope )
&& !Artifact.SCOPE_SYSTEM.equals( excludeScope ) )
{
throw new ArtifactFilterException( "Invalid Scope in excludeScope: " + excludeScope );
}
results = new LinkedHashSet<>();
// plexus ScopeArtifactFilter doesn't handle the provided scope so
// we
// need special handling for it.
if ( Artifact.SCOPE_TEST.equals( excludeScope ) )
{
throw new ArtifactFilterException( " Can't exclude Test scope, this will exclude everything." );
}
else if ( !Artifact.SCOPE_PROVIDED.equals( excludeScope ) && !Artifact.SCOPE_SYSTEM.equals( excludeScope ) )
{
ArtifactFilter saf = new ScopeArtifactFilter( excludeScope );
for ( Artifact artifact : artifacts )
{
if ( !saf.include( artifact ) )
{
results.add( artifact );
}
}
}
else
{
results = excludeSingleScope( artifacts, excludeScope );
}
}
return results;
}
private Set<Artifact> includeSingleScope( Set<Artifact> artifacts, String scope )
{
Set<Artifact> results = new LinkedHashSet<>();
for ( Artifact artifact : artifacts )
{
if ( scope.equals( artifact.getScope() ) )
{
results.add( artifact );
}
}
return results;
}
private Set<Artifact> excludeSingleScope( Set<Artifact> artifacts, String scope )
{
Set<Artifact> results = new LinkedHashSet<>();
for ( Artifact artifact : artifacts )
{
if ( !scope.equals( artifact.getScope() ) )
{
results.add( artifact );
}
}
return results;
}
/**
* <p>Getter for the field <code>includeScope</code>.</p>
*
* @return Returns the includeScope.
*/
public String getIncludeScope()
{
return this.includeScope;
}
/**
* <p>Setter for the field <code>includeScope</code>.</p>
*
* @param scope
* The includeScope to set.
*/
public void setIncludeScope( String scope )
{
this.includeScope = scope;
}
/**
* <p>Getter for the field <code>excludeScope</code>.</p>
*
* @return Returns the excludeScope.
*/
public String getExcludeScope()
{
return this.excludeScope;
}
/**
* <p>Setter for the field <code>excludeScope</code>.</p>
*
* @param scope
* The excludeScope to set.
*/
public void setExcludeScope( String scope )
{
this.excludeScope = scope;
}
} |
Java | @Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InlineCustomDocumentEnrichmentConfiguration implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* Configuration of the condition used for the target document attribute or metadata field when ingesting documents
* into Amazon Kendra.
* </p>
*/
private DocumentAttributeCondition condition;
/**
* <p>
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon Kendra. You
* can also include a value.
* </p>
*/
private DocumentAttributeTarget target;
/**
* <p>
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* </p>
*/
private Boolean documentContentDeletion;
/**
* <p>
* Configuration of the condition used for the target document attribute or metadata field when ingesting documents
* into Amazon Kendra.
* </p>
*
* @param condition
* Configuration of the condition used for the target document attribute or metadata field when ingesting
* documents into Amazon Kendra.
*/
public void setCondition(DocumentAttributeCondition condition) {
this.condition = condition;
}
/**
* <p>
* Configuration of the condition used for the target document attribute or metadata field when ingesting documents
* into Amazon Kendra.
* </p>
*
* @return Configuration of the condition used for the target document attribute or metadata field when ingesting
* documents into Amazon Kendra.
*/
public DocumentAttributeCondition getCondition() {
return this.condition;
}
/**
* <p>
* Configuration of the condition used for the target document attribute or metadata field when ingesting documents
* into Amazon Kendra.
* </p>
*
* @param condition
* Configuration of the condition used for the target document attribute or metadata field when ingesting
* documents into Amazon Kendra.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InlineCustomDocumentEnrichmentConfiguration withCondition(DocumentAttributeCondition condition) {
setCondition(condition);
return this;
}
/**
* <p>
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon Kendra. You
* can also include a value.
* </p>
*
* @param target
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon
* Kendra. You can also include a value.
*/
public void setTarget(DocumentAttributeTarget target) {
this.target = target;
}
/**
* <p>
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon Kendra. You
* can also include a value.
* </p>
*
* @return Configuration of the target document attribute or metadata field when ingesting documents into Amazon
* Kendra. You can also include a value.
*/
public DocumentAttributeTarget getTarget() {
return this.target;
}
/**
* <p>
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon Kendra. You
* can also include a value.
* </p>
*
* @param target
* Configuration of the target document attribute or metadata field when ingesting documents into Amazon
* Kendra. You can also include a value.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InlineCustomDocumentEnrichmentConfiguration withTarget(DocumentAttributeTarget target) {
setTarget(target);
return this;
}
/**
* <p>
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* </p>
*
* @param documentContentDeletion
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
*/
public void setDocumentContentDeletion(Boolean documentContentDeletion) {
this.documentContentDeletion = documentContentDeletion;
}
/**
* <p>
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* </p>
*
* @return <code>TRUE</code> to delete content if the condition used for the target attribute is met.
*/
public Boolean getDocumentContentDeletion() {
return this.documentContentDeletion;
}
/**
* <p>
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* </p>
*
* @param documentContentDeletion
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InlineCustomDocumentEnrichmentConfiguration withDocumentContentDeletion(Boolean documentContentDeletion) {
setDocumentContentDeletion(documentContentDeletion);
return this;
}
/**
* <p>
* <code>TRUE</code> to delete content if the condition used for the target attribute is met.
* </p>
*
* @return <code>TRUE</code> to delete content if the condition used for the target attribute is met.
*/
public Boolean isDocumentContentDeletion() {
return this.documentContentDeletion;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCondition() != null)
sb.append("Condition: ").append(getCondition()).append(",");
if (getTarget() != null)
sb.append("Target: ").append(getTarget()).append(",");
if (getDocumentContentDeletion() != null)
sb.append("DocumentContentDeletion: ").append(getDocumentContentDeletion());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof InlineCustomDocumentEnrichmentConfiguration == false)
return false;
InlineCustomDocumentEnrichmentConfiguration other = (InlineCustomDocumentEnrichmentConfiguration) obj;
if (other.getCondition() == null ^ this.getCondition() == null)
return false;
if (other.getCondition() != null && other.getCondition().equals(this.getCondition()) == false)
return false;
if (other.getTarget() == null ^ this.getTarget() == null)
return false;
if (other.getTarget() != null && other.getTarget().equals(this.getTarget()) == false)
return false;
if (other.getDocumentContentDeletion() == null ^ this.getDocumentContentDeletion() == null)
return false;
if (other.getDocumentContentDeletion() != null && other.getDocumentContentDeletion().equals(this.getDocumentContentDeletion()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCondition() == null) ? 0 : getCondition().hashCode());
hashCode = prime * hashCode + ((getTarget() == null) ? 0 : getTarget().hashCode());
hashCode = prime * hashCode + ((getDocumentContentDeletion() == null) ? 0 : getDocumentContentDeletion().hashCode());
return hashCode;
}
@Override
public InlineCustomDocumentEnrichmentConfiguration clone() {
try {
return (InlineCustomDocumentEnrichmentConfiguration) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.kendra.model.transform.InlineCustomDocumentEnrichmentConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller);
}
} |
Java | public class GeoPointWidget extends QuestionWidget {
private final Button mGetLocationButton;
private final Button mViewButton;
private final TextView mStringAnswer;
private final TextView mAnswerDisplay;
private boolean mUseMaps;
public static final String LOCATION = "gp";
private final PendingCalloutInterface pendingCalloutInterface;
public GeoPointWidget(Context context, final FormEntryPrompt prompt, PendingCalloutInterface pic) {
super(context, prompt);
this.pendingCalloutInterface = pic;
mUseMaps = false;
String appearance = prompt.getAppearanceHint();
if ("maps".equalsIgnoreCase(appearance)) {
try {
// use google maps it exists on the device
Class.forName("com.google.android.maps.MapActivity");
mUseMaps = true;
} catch (ClassNotFoundException e) {
mUseMaps = false;
}
}
setOrientation(LinearLayout.VERTICAL);
mStringAnswer = new TextView(getContext());
mAnswerDisplay = new TextView(getContext());
mAnswerDisplay.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontSize);
mAnswerDisplay.setGravity(Gravity.CENTER);
Spannable locButtonText;
boolean viewButtonEnabled;
String s = prompt.getAnswerText();
if (s != null && !("".equals(s))) {
setBinaryData(s);
locButtonText = StringUtils.getStringSpannableRobust(getContext(),
R.string.replace_location);
viewButtonEnabled = true;
} else {
locButtonText = StringUtils.getStringSpannableRobust(getContext(),
R.string.get_location);
viewButtonEnabled = false;
}
mGetLocationButton = new Button(getContext());
WidgetUtils.setupButton(mGetLocationButton,
locButtonText,
mAnswerFontSize,
!prompt.isReadOnly());
mGetLocationButton.setOnClickListener(v -> {
Intent i;
if (mUseMaps) {
i = new Intent(getContext(), GeoPointMapActivity.class);
} else {
i = new Intent(getContext(), GeoPointActivity.class);
}
((Activity)getContext()).startActivityForResult(i, FormEntryConstants.LOCATION_CAPTURE);
pendingCalloutInterface.setPendingCalloutFormIndex(prompt.getIndex());
});
// setup 'view location' button
mViewButton = new Button(getContext());
WidgetUtils.setupButton(mViewButton,
StringUtils.getStringSpannableRobust(getContext(), R.string.show_location),
mAnswerFontSize,
viewButtonEnabled);
// launch appropriate map viewer
mViewButton.setOnClickListener(v -> {
String s1 = mStringAnswer.getText().toString();
String[] sa = s1.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]);
gp[1] = Double.valueOf(sa[1]);
gp[2] = Double.valueOf(sa[2]);
gp[3] = Double.valueOf(sa[3]);
Intent i = new Intent(getContext(), GeoPointMapActivity.class);
i.putExtra(LOCATION, gp);
getContext().startActivity(i);
});
addView(mGetLocationButton);
if (mUseMaps) {
addView(mViewButton);
}
addView(mAnswerDisplay);
}
@Override
public void clearAnswer() {
mStringAnswer.setText(null);
mAnswerDisplay.setText(null);
mGetLocationButton.setText(StringUtils.getStringSpannableRobust(getContext(), R.string.get_location));
}
@Override
public IAnswerData getAnswer() {
String s = mStringAnswer.getText().toString();
if (s == null || s.equals("")) {
return null;
} else {
try {
// segment lat and lon
String[] sa = s.split(" ");
double gp[] = new double[4];
gp[0] = Double.valueOf(sa[0]);
gp[1] = Double.valueOf(sa[1]);
gp[2] = Double.valueOf(sa[2]);
gp[3] = Double.valueOf(sa[3]);
return new GeoPointData(gp);
} catch (Exception NumberFormatException) {
return null;
}
}
}
private String truncateDouble(String s) {
DecimalFormat df = new DecimalFormat("#.##");
return df.format(Double.valueOf(s));
}
private String formatGps(double coordinates, String type) {
String location = Double.toString(coordinates);
String degreeSign = "\u00B0";
String degree = location.substring(0, location.indexOf(".")) + degreeSign;
location = "0." + location.substring(location.indexOf(".") + 1);
double temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String mins = location.substring(0, location.indexOf(".")) + "'";
location = "0." + location.substring(location.indexOf(".") + 1);
temp = Double.valueOf(location) * 60;
location = Double.toString(temp);
String secs = location.substring(0, location.indexOf(".")) + '"';
if (type.equalsIgnoreCase("lon")) {
if (degree.startsWith("-")) {
degree = "W " + degree.replace("-", "") + mins + secs;
} else
degree = "E " + degree.replace("-", "") + mins + secs;
} else {
if (degree.startsWith("-")) {
degree = "S " + degree.replace("-", "") + mins + secs;
} else
degree = "N " + degree.replace("-", "") + mins + secs;
}
return degree;
}
@Override
public void setFocus(Context context) {
// Hide the soft keyboard if it's showing.
InputMethodManager inputManager =
(InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
}
@Override
public void setBinaryData(Object answer) {
String s = (String)answer;
mStringAnswer.setText(s);
String[] sa = s.split(" ");
mAnswerDisplay.setText(
StringUtils.getStringSpannableRobust(getContext(), R.string.latitude) +
": " + formatGps(Double.parseDouble(sa[0]), "lat") + "\n" +
StringUtils.getStringSpannableRobust(getContext(), R.string.longitude) +
": " + formatGps(Double.parseDouble(sa[1]), "lon") + "\n" +
StringUtils.getStringSpannableRobust(getContext(), R.string.altitude) +
": " + truncateDouble(sa[2]) + "m\n" +
StringUtils.getStringSpannableRobust(getContext(), R.string.accuracy) +
": " + truncateDouble(sa[3]) + "m");
// update form relevancies and such
widgetEntryChanged();
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mViewButton.setOnLongClickListener(l);
mGetLocationButton.setOnLongClickListener(l);
mStringAnswer.setOnLongClickListener(l);
mAnswerDisplay.setOnLongClickListener(l);
}
@Override
public void unsetListeners() {
super.unsetListeners();
mViewButton.setOnLongClickListener(null);
mGetLocationButton.setOnLongClickListener(null);
mStringAnswer.setOnLongClickListener(null);
mAnswerDisplay.setOnLongClickListener(null);
}
@Override
public void cancelLongPress() {
super.cancelLongPress();
mViewButton.cancelLongPress();
mGetLocationButton.cancelLongPress();
mStringAnswer.cancelLongPress();
mAnswerDisplay.cancelLongPress();
}
} |
Java | public class BrokerReport {
// topic, channelReport
ConcurrentHashMap<String, ChannelReport> map;
String brokerID;
double loadRatio;
double bandWidthBytes;
private static final Logger logger = LogManager.getLogger(BrokerReport.class.getName());
public BrokerReport(String brokerID) {
this.map = new ConcurrentHashMap<>();
this.brokerID = brokerID;
}
public BrokerReport(TypesBrokerReport typesBrokerReport) {
this.brokerID = typesBrokerReport.brokerID();
this.loadRatio = typesBrokerReport.loadRatio();
this.bandWidthBytes = typesBrokerReport.bandWidthBytes();
this.map = new ConcurrentHashMap<>();
// typesBrokerReport -> brokerReport
for (int i = 0; i < typesBrokerReport.channelReportsLength(); i++) {
// TypesChannelReport -> channelReport
this.addChannelReport(new ChannelReport(typesBrokerReport.channelReports(i)));
}
}
public String getBrokerID() {
return brokerID;
}
public double getBandWidthBytes() {
return bandWidthBytes;
}
private void setLoadRatio(double loadRatio) {
this.loadRatio = loadRatio;
}
// bytes can be positive and negative
private void changeLoadRatioByBytes(double bytes) {
this.setLoadRatio((loadRatio * bandWidthBytes + bytes) / bandWidthBytes);
}
public void updateBytes(String topic, long bytes) {
if (!map.containsKey(topic)) {
Long[] i1000 = new Long[1000];
for(int i = 0; i< 1000; i++){
i1000[i] = new Long(1);
}
String a = new String(topic);
ChannelReport newChannelReport = new ChannelReport(topic);
map.put(topic, newChannelReport);
}
map.get(topic).numIOBytes += bytes;
}
public void updateMsgs(String topic, long msgs) {
if (!map.containsKey(topic)) {
map.put(topic, new ChannelReport(topic));
}
map.get(topic).numIOMsgs += msgs;
}
public void updatePublications(String topic, long publications) {
if (!map.containsKey(topic)) {
map.put(topic, new ChannelReport(topic));
}
map.get(topic).numPublications += publications;
}
public void updateSubscribers(String topic, long subscribers) {
if (!map.containsKey(topic)) {
map.put(topic, new ChannelReport(topic));
}
map.get(topic).numSubscribers += subscribers;
}
public Set<Map.Entry<String, ChannelReport>> entrySet() {
return map.entrySet();
}
public int size() {
return map.size();
}
public void reset() {
this.map = new ConcurrentHashMap<>();
}
// calculations
public double getLoadRatio() {
long cumulativeIOBytes = 0;
for (Map.Entry<String, ChannelReport> entry : map.entrySet()) {
cumulativeIOBytes += entry.getValue().getNumIOBytes();
}
return (double) cumulativeIOBytes / LoadAnalyzer.getBandWidthBytes();
}
public ChannelReport getMostBusyChannel() {
ChannelReport res = null;
for (Map.Entry<String, ChannelReport> entry : map.entrySet()) {
if (res == null || entry.getValue().getNumIOBytes() > res.getNumIOBytes()) {
res = entry.getValue();
}
}
return res;
}
public void addChannelReport(ChannelReport channelReport) {
map.put(channelReport.getTopic(), channelReport);
changeLoadRatioByBytes(-channelReport.getNumIOBytes());
}
public void removeChannelReport(String topic) {
if (!map.containsKey(topic)) return;
changeLoadRatioByBytes(-(map.get(topic).getNumIOBytes()));
map.remove(topic);
}
} |
Java | public class SubmissionServiceHttp {
public static com.liferay.training.gradebook.model.Submission addSubmission(
HttpPrincipal httpPrincipal,
com.liferay.training.gradebook.model.Submission submission,
com.liferay.portal.kernel.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "addSubmission",
_addSubmissionParameterTypes0);
MethodHandler methodHandler = new MethodHandler(
methodKey, submission, serviceContext);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
if (exception instanceof
com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)
exception;
}
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (com.liferay.training.gradebook.model.Submission)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static com.liferay.training.gradebook.model.Submission
createSubmission(HttpPrincipal httpPrincipal) {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "createSubmission",
_createSubmissionParameterTypes1);
MethodHandler methodHandler = new MethodHandler(methodKey);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (com.liferay.training.gradebook.model.Submission)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static com.liferay.training.gradebook.model.Submission
deleteSubmission(HttpPrincipal httpPrincipal, long submissionId)
throws com.liferay.portal.kernel.exception.PortalException {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "deleteSubmission",
_deleteSubmissionParameterTypes2);
MethodHandler methodHandler = new MethodHandler(
methodKey, submissionId);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
if (exception instanceof
com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)
exception;
}
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (com.liferay.training.gradebook.model.Submission)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static com.liferay.training.gradebook.model.Submission getSubmission(
HttpPrincipal httpPrincipal, long submissionId)
throws com.liferay.portal.kernel.exception.PortalException {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "getSubmission",
_getSubmissionParameterTypes3);
MethodHandler methodHandler = new MethodHandler(
methodKey, submissionId);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
if (exception instanceof
com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)
exception;
}
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (com.liferay.training.gradebook.model.Submission)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static com.liferay.training.gradebook.model.Submission
updateSubmission(
HttpPrincipal httpPrincipal,
com.liferay.training.gradebook.model.Submission submission,
com.liferay.portal.kernel.service.ServiceContext serviceContext)
throws com.liferay.portal.kernel.exception.PortalException {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "updateSubmission",
_updateSubmissionParameterTypes4);
MethodHandler methodHandler = new MethodHandler(
methodKey, submission, serviceContext);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
if (exception instanceof
com.liferay.portal.kernel.exception.PortalException) {
throw (com.liferay.portal.kernel.exception.PortalException)
exception;
}
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (com.liferay.training.gradebook.model.Submission)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static java.util.List
<com.liferay.training.gradebook.model.Submission>
getSubmissionsByKeywords(
HttpPrincipal httpPrincipal, long groupId, long assignmentId,
String keywords, int start, int end,
com.liferay.portal.kernel.util.OrderByComparator
<com.liferay.training.gradebook.model.Submission>
orderByComparator) {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "getSubmissionsByKeywords",
_getSubmissionsByKeywordsParameterTypes5);
MethodHandler methodHandler = new MethodHandler(
methodKey, groupId, assignmentId, keywords, start, end,
orderByComparator);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return (java.util.List
<com.liferay.training.gradebook.model.Submission>)returnObj;
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
public static long getSubmissionsCountByKeywords(
HttpPrincipal httpPrincipal, long groupId, long assignmentId,
String keywords) {
try {
MethodKey methodKey = new MethodKey(
SubmissionServiceUtil.class, "getSubmissionsCountByKeywords",
_getSubmissionsCountByKeywordsParameterTypes6);
MethodHandler methodHandler = new MethodHandler(
methodKey, groupId, assignmentId, keywords);
Object returnObj = null;
try {
returnObj = TunnelUtil.invoke(httpPrincipal, methodHandler);
}
catch (Exception exception) {
throw new com.liferay.portal.kernel.exception.SystemException(
exception);
}
return ((Long)returnObj).longValue();
}
catch (com.liferay.portal.kernel.exception.SystemException
systemException) {
_log.error(systemException, systemException);
throw systemException;
}
}
private static Log _log = LogFactoryUtil.getLog(
SubmissionServiceHttp.class);
private static final Class<?>[] _addSubmissionParameterTypes0 =
new Class[] {
com.liferay.training.gradebook.model.Submission.class,
com.liferay.portal.kernel.service.ServiceContext.class
};
private static final Class<?>[] _createSubmissionParameterTypes1 =
new Class[] {};
private static final Class<?>[] _deleteSubmissionParameterTypes2 =
new Class[] {long.class};
private static final Class<?>[] _getSubmissionParameterTypes3 =
new Class[] {long.class};
private static final Class<?>[] _updateSubmissionParameterTypes4 =
new Class[] {
com.liferay.training.gradebook.model.Submission.class,
com.liferay.portal.kernel.service.ServiceContext.class
};
private static final Class<?>[] _getSubmissionsByKeywordsParameterTypes5 =
new Class[] {
long.class, long.class, String.class, int.class, int.class,
com.liferay.portal.kernel.util.OrderByComparator.class
};
private static final Class<?>[]
_getSubmissionsCountByKeywordsParameterTypes6 = new Class[] {
long.class, long.class, String.class
};
} |
Java | public class MaterialesFrame extends javax.swing.JInternalFrame {
MaterialLog material;
boolean presionado=false;
ModeloTablaMaterial modeloTabla;
Material mat;
/**
* Creates new form Computadoras
*/
public MaterialesFrame() { //Constructor el cual incializa el Frame,los botones con sus atributos y todo el pex
initComponents();
material = new MaterialLog(); // Creo la instancia de inventario
ListarMaterial(); //Listo las computadoras
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jBtnBuscar = new javax.swing.JButton();
jTextBuscar = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 255, 255));
setBorder(null);
setForeground(java.awt.Color.white);
setTitle("Articulos");
setVisible(true);
getContentPane().setLayout(null);
jScrollPane2.setBackground(new java.awt.Color(255, 255, 255));
jTable1.setDefaultRenderer(Object.class,new Table_Img());
jTable1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.setRowHeight(80);
/*jTable1.getSelectionModel().addListSelectionListener(
new ListSelectionListener(){
public void valueChanged(ListSelectionEvent event){
if(!event.getValueIsAdjusting() && (jTable1.getSelectedRow()>=0)){
int filaSeleccionada = jTable1.getSelectedRow();
pc = (modeloTabla.DamePc(filaSeleccionada);
setPc(pc);
}
}
}
);*/
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane2.setViewportView(jTable1);
getContentPane().add(jScrollPane2);
jScrollPane2.setBounds(8, 0, 1140, 550);
jBtnBuscar.setText("Buscar");
jBtnBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtnBuscarActionPerformed(evt);
}
});
getContentPane().add(jBtnBuscar);
jBtnBuscar.setBounds(620, 660, 80, 30);
jTextBuscar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jTextBuscarKeyTyped(evt);
}
});
getContentPane().add(jTextBuscar);
jTextBuscar.setBounds(440, 660, 170, 25);
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/orig_506983.jpg"))); // NOI18N
jLabel2.setText("jLabel2");
getContentPane().add(jLabel2);
jLabel2.setBounds(0, 0, 1988, 1200);
pack();
}// </editor-fold>//GEN-END:initComponents
private void ListarMaterial(){
List<Material> listas = material.ListarMaterial(); //Buscar las computadoras en la base de datos y regresa la lista de todas las que esten
modeloTabla = new ModeloTablaMaterial(listas);// Crea el modelo dependiendo la lista regresada
jTable1.setModel(modeloTabla); // Y lo desppliega en el JText
}
private void jBtnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnBuscarActionPerformed
if(jTextBuscar.getText().isEmpty()){//Si se presiona buscar y el Jtext de buscar esta vacio entra
List<Material> listas = material.ListarMaterial(); //hace la consulta que traes todos las pc en la BD
modeloTabla = new ModeloTablaMaterial(listas);// crea el modelo
jTable1.setModel(modeloTabla); // y lo ingresa al Jtable
}else
{
List<Material> listas = material.BuscarMaterial(jTextBuscar.getText()); //Sino Bucar el texto ingresado en la base de datos
modeloTabla = new ModeloTablaMaterial(listas); // Crea el modelo dependiendo la lista regresada
jTable1.setModel(modeloTabla); // Y lo ingresa en el Jtable
}
}//GEN-LAST:event_jBtnBuscarActionPerformed
private void jTextBuscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextBuscarKeyTyped
char cTeclaPresionada = evt.getKeyChar(); //Optiene las teclas presionadas
if(cTeclaPresionada == KeyEvent.VK_ENTER)
jBtnBuscar.doClick();//Si la tecla fue enter .doClick(); Simula que se presiono el boton
}//GEN-LAST:event_jTextBuscarKeyTyped
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
int column = jTable1.getColumnModel().getColumnIndexAtX(evt.getX());
int row = evt.getY()/jTable1.getRowHeight();
if(row< jTable1.getRowCount() && row >=0 && column< jTable1.getColumnCount() && column >=0)
{
Object value = jTable1.getValueAt(row,column);
int idMat=Integer.parseInt(jTable1.getValueAt(row, 0).toString());
if(value instanceof JButton)
{
((JButton)value).doClick();
PreCotizacion addCont = new PreCotizacion(null,true,idMat);
addCont.setVisible(true);
addCont.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
addCont.setAlwaysOnTop(true);
}
}
}//GEN-LAST:event_jTable1MouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBtnBuscar;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextBuscar;
// End of variables declaration//GEN-END:variables
} |
Java | public class LoVPropertyDecorator extends BasePropertyDecorator implements InitializingBean
{
protected DictionaryService dictionaryService;
/**
*
* {@inheritDoc}
*/
@Override
public void afterPropertiesSet()
{
PropertyCheck.mandatory(this, "namespaceService", this.namespaceService);
PropertyCheck.mandatory(this, "dictionaryService", this.dictionaryService);
PropertyCheck.mandatory(this, "nodeService", this.nodeService);
PropertyCheck.mandatory(this, "permissionService", this.permissionService);
PropertyCheck.mandatory(this, "jsonConversionComponent", this.jsonConversionComponent);
this.init();
}
/**
* @param dictionaryService
* the dictionaryService to set
*/
public void setDictionaryService(final DictionaryService dictionaryService)
{
this.dictionaryService = dictionaryService;
}
/**
* {@inheritDoc}
*/
@Override
public JSONAware decorate(final QName propertyName, final NodeRef nodeRef, final Serializable value)
{
final QName type = this.nodeService.getType(nodeRef);
final Set<QName> allAspects = this.nodeService.getAspects(nodeRef);
final Set<QName> aspects = this.filterAspectParentClasses(allAspects);
final TypeDefinition typeDefinition = this.dictionaryService.getAnonymousType(type, aspects);
final PropertyDefinition propertyDefinition = typeDefinition.getProperties().get(propertyName);
final JSONAware result;
if (propertyDefinition != null)
{
if (value instanceof Collection<?>)
{
@SuppressWarnings("unchecked")
final List<Object> list = new JSONArray();
for (final Object element : (Collection<?>) value)
{
final String valueText = DefaultTypeConverter.INSTANCE.convert(String.class, element);
@SuppressWarnings("unchecked")
final Map<String, String> map = new JSONObject();
map.put("value", valueText);
this.retrieveDisplayLabel(valueText, propertyDefinition, map);
list.add(map);
}
result = (JSONArray) list;
}
else
{
final String valueText = DefaultTypeConverter.INSTANCE.convert(String.class, value);
@SuppressWarnings("unchecked")
final Map<String, String> map = new JSONObject();
map.put("value", valueText);
result = (JSONObject) map;
this.retrieveDisplayLabel(valueText, propertyDefinition, map);
}
}
else
{
result = null;
}
return result;
}
protected Set<QName> filterAspectParentClasses(final Set<QName> aspects)
{
final Set<QName> result = new HashSet<>(aspects);
for (final QName qName : aspects)
{
final AspectDefinition aspect = this.dictionaryService.getAspect(qName);
ClassDefinition parent = aspect.getParentClassDefinition();
while (parent != null)
{
result.remove(parent.getName());
parent = parent.getParentClassDefinition();
}
}
return result;
}
protected void retrieveDisplayLabel(final String value, final PropertyDefinition propertyDefinition, final Map<String, String> map)
{
final List<ConstraintDefinition> constraints = propertyDefinition.getConstraints();
if (constraints != null)
{
String label = null;
for (final ConstraintDefinition constraint : constraints)
{
Constraint actualConstraint = constraint.getConstraint();
if (actualConstraint instanceof RegisteredConstraint)
{
actualConstraint = ((RegisteredConstraint) actualConstraint).getRegisteredConstraint();
}
if (actualConstraint instanceof ListOfValuesConstraint)
{
label = ((ListOfValuesConstraint) actualConstraint).getDisplayLabel(value, this.dictionaryService);
if (label != null)
{
break;
}
}
}
if (label != null)
{
map.put("displayName", label);
}
}
}
} |
Java | public final class PrintParserUtils {
/** Prevent instantiation. */
private PrintParserUtils() {
throw new AssertionError();
}
/**
* Create a new {@link BeanDefinitionBuilder} for the class {@link PrintServiceExecutor}.
* @param element Must not be null
* @param parserContext Must not be null
* @return The BeanDefinitionBuilder for the {@link PrintServiceExecutor}
*/
public static BeanDefinitionBuilder getPrintServiceExecutorBuilder(final Element element,
final ParserContext parserContext) {
Assert.notNull(element, "The provided element must not be null.");
Assert.notNull(parserContext, "The provided parserContext must not be null.");
final Object source = parserContext.extractSource(element);
final BeanDefinitionBuilder printServiceExecutorBuilder = BeanDefinitionBuilder.genericBeanDefinition(PrintServiceExecutor.class);
final String printServiceRef = element.getAttribute("print-service-ref");
final String printerName = element.getAttribute("printer-name");
if (StringUtils.hasText(printServiceRef)
&& StringUtils.hasText(printerName)) {
parserContext.getReaderContext().error("Exactly only one of the attributes 'print-service-ref' or " +
"'printer-name' must be be set.", source);
}
if (StringUtils.hasText(printServiceRef)) {
printServiceExecutorBuilder.addConstructorArgReference(printServiceRef);
}
if (StringUtils.hasText(printerName)) {
printServiceExecutorBuilder.addConstructorArgReference(printerName);
}
return printServiceExecutorBuilder;
}
} |
Java | @ExtendWith(MockitoExtension.class)
class DefaultBambooClientTest {
private static final String FOO = "foo";
private static final String BAR = "bar";
@Mock
private InstanceValues instanceValues;
@Mock
private WebTarget webTarget;
@Mock
private Invocation.Builder invocationBuilder;
@Mock
private ApiCallRepeatable<ProjectsResponse> projectsCaller;
@Mock
private ApiCallRepeatable<PlansResponse> plansCaller;
@Mock
private ApiCallRepeatable<ResultsResponse> resultsCaller;
@Mock
private ApiCallable<Result> resultCaller;
@Mock
private ApiCallable<Info> infoCaller;
@Mock
private ApiCallable postCaller;
@Mock
private ApiCallerFactory apiCallerFactory;
private DefaultBambooClient classUnderTest;
private Plan plan;
private Plans plans;
private Result result;
private Info info;
private ProjectsResponse projectsResponse;
private PlansResponse plansResponse;
private ResultsResponse resultsResponse;
@BeforeEach
void setUp() {
classUnderTest = new DefaultBambooClient(instanceValues);
ReflectionTestUtils.setField(classUnderTest, "apiCallerFactory", apiCallerFactory);
plan = new Plan();
plan.setKey(FOO);
Plan barPlan = new Plan();
barPlan.setKey(BAR);
plans = new Plans();
List<Plan> planList = new ArrayList<>(2);
planList.add(plan);
planList.add(barPlan);
plans.setPlan(planList);
projectsResponse = new ProjectsResponse();
Project project = new Project();
project.setPlans(plans);
Projects projects = new Projects();
projects.setProject(singletonList(project));
projectsResponse.setProjects(projects);
plansResponse = new PlansResponse();
plansResponse.setPlans(plans);
resultsResponse = new ResultsResponse();
Results results = new Results();
result = new Result();
result.setPlan(plan);
results.setResult(singletonList(result));
resultsResponse.setResults(results);
info = new Info();
info.setBuildDate("2014-12-02T07:43:02.000+01:00");
}
private void trainApiCallerFactory() {
given(apiCallerFactory.newCaller(eq(ProjectsResponse.class), eq(PROJECTS), any(
Map.class))).willReturn(
projectsCaller);
given(apiCallerFactory.newRepeatCaller(eq(PlansResponse.class), eq(PLANS))).willReturn(
plansCaller);
given(apiCallerFactory.newRepeatCaller(eq(ResultsResponse.class), eq(RESULTS),
any(Map.class))).willReturn(
resultsCaller);
}
private void trainForProjectResponse() {
given(plansCaller.createTarget()).willReturn(of(webTarget));
given(plansCaller.doGet(webTarget)).willReturn(of(plansResponse));
given(plansCaller.repeat(plansResponse)).willReturn(of(plansResponse));
given(projectsCaller.createTarget()).willReturn(of(webTarget));
given(projectsCaller.doGet(webTarget)).willReturn(of(projectsResponse));
}
/**
* Test of getProjects method, of class DefaultBambooClient.
*/
@Test
void testGetProjects_ExpectNotEmpty() {
trainApiCallerFactory();
trainForProjectResponse();
Collection<ProjectVo> buildProjects = classUnderTest.getProjects();
assertFalse(buildProjects.isEmpty());
}
/**
* Test of getProjects method, of class DefaultBambooClient.
*/
@Test
void testGetProjects_ExpectNoParent() {
trainApiCallerFactory();
trainForProjectResponse();
Collection<ProjectVo> buildProjects = classUnderTest.getProjects();
buildProjects.forEach(pr -> {
assertFalse(pr.getParent().isPresent());
});
}
/**
* Test of getProjects method, of class DefaultBambooClient.
*/
@Test
void testGetProjects_TwoPlans() {
trainApiCallerFactory();
trainForProjectResponse();
Collection<ProjectVo> buildProjects = classUnderTest.getProjects();
Collection<PlanVo> result = buildProjects.iterator().next().getChildren();
assertEquals(2, result.size());
}
/**
* Test of getProjects method, of class DefaultBambooClient.
*/
@Test
void testGetProjects_Equal() {
trainApiCallerFactory();
trainForProjectResponse();
Collection<ProjectVo> first = classUnderTest.getProjects();
Collection<ProjectVo> second = classUnderTest.getProjects();
assertEquals(first, second);
}
@Test
void testUpdate() {
trainApiCallerFactory();
trainForProjectResponse();
List<ProjectVo> toBeUpdated = new ArrayList<>();
classUnderTest.updateProjects(toBeUpdated);
assertFalse(toBeUpdated.isEmpty());
}
@Test
void testGetVersion() {
given(apiCallerFactory.newCaller(eq(Info.class), eq(INFO))).willReturn(
infoCaller);
given(infoCaller.createTarget()).willReturn(of(webTarget));
given(infoCaller.doGet(webTarget)).willReturn(of(info));
assertNotNull(classUnderTest.getVersionInfo().getBuildDate());
}
@Test
void testQueue_TargetPresent_Expect200() {
given(apiCallerFactory.newCaller(eq(Object.class), anyString())).willReturn(postCaller);
int code = 200;
PlanVo planVo = new PlanVo(FOO);
planVo.setParent(new ProjectVo(FOO));
given(postCaller.createTarget()).willReturn(of(webTarget));
given(postCaller.doPost(webTarget)).willReturn(Response.ok().build());
Response response = classUnderTest.queue(planVo);
assertEquals(code, response.getStatus());
verify(postCaller).doPost(webTarget);
}
@Test
void testQueue_TargetEmpty_ExpectNotFound() {
given(apiCallerFactory.newCaller(eq(Object.class), anyString())).willReturn(postCaller);
final int code = 404;
PlanVo planVo = new PlanVo(FOO);
planVo.setParent(new ProjectVo(FOO));
given(postCaller.createTarget()).willReturn(empty());
Response response = classUnderTest.queue(planVo);
assertEquals(code, response.getStatus());
verify(postCaller, never()).doPost(webTarget);
}
@Test
void testAttach_ChangesNoResult_ShouldNotHaveChanges() {
given(apiCallerFactory.newCaller(eq(Result.class), anyString(), any(Map.class))).willReturn(
resultCaller);
ResultVo vo = new ResultVo();
classUnderTest.attach(vo, ResultExpandParameter.Changes);
assertFalse(vo.getChanges().isPresent());
}
@Test
void testAttach_Changes_ShouldHaveChanges() {
trainResultCaller();
Changes changes = new Changes();
Change change = new Change();
changes.setChanges(singletonList(change));
result.setChanges(changes);
ResultVo vo = new ResultVo();
classUnderTest.attach(vo, ResultExpandParameter.Changes);
assertFalse(vo.getChanges().get().isEmpty());
}
private void trainResultCaller() {
given(apiCallerFactory.newCaller(eq(Result.class), anyString(), any(Map.class))).willReturn(
resultCaller);
given(resultCaller.createTarget()).willReturn(of(webTarget));
given(resultCaller.doGet(webTarget)).willReturn(of(result));
}
@Test
void testAttach_IssuesNoResult_ShouldNotHaveIssues() {
given(apiCallerFactory.newCaller(eq(Result.class), anyString(), any(Map.class))).willReturn(
resultCaller);
ResultVo vo = new ResultVo();
classUnderTest.attach(vo, ResultExpandParameter.Jira);
assertFalse(vo.getIssues().isPresent());
}
@Test
void testAttach_IssuesResult_ShouldHaveIssues() {
trainResultCaller();
JiraIssues issues = new JiraIssues();
Issue issue = new Issue();
issues.setIssues(singletonList(issue));
result.setJiraIssues(issues);
ResultVo vo = new ResultVo();
classUnderTest.attach(vo, ResultExpandParameter.Jira);
assertFalse(vo.getIssues().get().isEmpty());
}
} |
Java | @RedirectScoped
@Named("flashMessage")
public class AlertMessage implements Serializable {
private static final long serialVersionUID = 1L;
public enum Type {
success, warning, danger, info;
}
private Type type = Type.info;
private String text;
private String code;
public AlertMessage() {
}
public AlertMessage(Type type, String text) {
this.type = type;
this.text = text;
}
public AlertMessage(Type type, String code, String message) {
this.type = type;
this.code = code;
this.text = message;
}
public String getText() {
return text;
}
public Type getType() {
return type;
}
public String getCode() {
return code;
}
public void notify(Type type, String text) {
this.type = type;
this.text = text;
}
public static AlertMessage success(String text) {
return new AlertMessage(Type.success, text);
}
public static AlertMessage warning(String text) {
return new AlertMessage(Type.warning, text);
}
public static AlertMessage danger(String text) {
return new AlertMessage(Type.danger, text);
}
public static AlertMessage info(String text) {
return new AlertMessage(Type.info, text);
}
private List<Error> errors = new ArrayList<>();
public List<Error> getErrors() {
return errors;
}
public void setErrors(List<Error> errors) {
this.errors = errors;
}
public void addError(String field, String code, String message) {
this.errors.add(new Error(field, code, message));
}
public static class Error {
private String code;
private String message;
private String field;
public Error(){}
private Error(String field, String code, String message) {
this.field = field;
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
}
} |
Java | public class AppointmentCommandParser implements Parser<AppointmentCommand> {
/**
* Parses the given {@code String} of arguments in the context of the AppointmentCommand
* and returns an AppointmentCommand object for execution.
* @throws ParseException if the user input does not conform the expected format.
*/
public AppointmentCommand parse(String args) throws ParseException {
requireNonNull(args);
ArgumentMultimap argMultimap = ArgumentTokenizer.tokenize(args,
PREFIX_APPOINTMENT_DATE_TIME, PREFIX_APPOINTMENT_LOCATION, PREFIX_CLEAR);
Index index;
Boolean isClearPresent = argMultimap.getValue(PREFIX_CLEAR).isPresent();
Boolean areDateTimeAndLocationPresent = arePrefixesPresent(argMultimap,
PREFIX_APPOINTMENT_DATE_TIME, PREFIX_APPOINTMENT_LOCATION);
if (isClearPresent && !areDateTimeAndLocationPresent) {
Appointment clearAppointment = new Appointment();
index = ParserUtil.parseIndex(argMultimap.getPreamble());
return new AppointmentCommand(index, clearAppointment);
} else if (areDateTimeAndLocationPresent && !isClearPresent) {
LocalDateTime dateTime = ParserUtil.parseAppointmentDateTime(
argMultimap.getValue(PREFIX_APPOINTMENT_DATE_TIME).get());
String location = argMultimap.getValue(PREFIX_APPOINTMENT_LOCATION).get();
Appointment appointment = new Appointment(dateTime, location);
index = ParserUtil.parseIndex(argMultimap.getPreamble());
return new AppointmentCommand(index, appointment);
} else {
throw new ParseException(String.format(MESSAGE_INVALID_COMMAND_FORMAT,
AppointmentCommand.MESSAGE_USAGE));
}
}
/**
* Returns true if none of the prefixes contains empty {@code Optional} values in the given
* {@code ArgumentMultimap}.
*/
private static boolean arePrefixesPresent(ArgumentMultimap argumentMultimap, Prefix... prefixes) {
return Stream.of(prefixes).allMatch(prefix -> argumentMultimap.getValue(prefix).isPresent());
}
} |
Java | public abstract class MessageDigestUtils {
/** the standard {@code MessageDigest} algorithms: */
public static final String
ALGORITHM_MD5 = "MD5",
ALGORITHM_SHA1 = "SHA-1",
ALGORITHM_SHA256 = "SHA-256";
/**
* get the instance of {@link MessageDigest}
*
* @param algorithm the message digest algorithm
* @return the MessageDigest
*/
public static MessageDigest getInstance(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new IllegalArgumentException(algorithm + " not supported", e);
}
}
/**
* get MD5 MessageDigest
*
* @return MD5 MessageDigest
*/
public static MessageDigest getMD5() {
return getInstance(ALGORITHM_MD5);
}
/**
* get SHA1 MessageDigest
*
* @return get SHA1 MessageDigest
*/
public static MessageDigest getSHA1() {
return getInstance(ALGORITHM_SHA1);
}
/**
* get SHA256 MessageDigest
*
* @return get SHA256 MessageDigest
*/
public static MessageDigest getSHA256() {
return getInstance(ALGORITHM_SHA256);
}
/**
* encode a string to string
*
* @param messageDigest the messageDigest
* @param string the string needed encode
* @return the encoded string
*/
public static String encode(MessageDigest messageDigest, String string) {
byte[] digest = messageDigest.digest(string.getBytes());
return DatatypeConverter.printHexBinary(digest);
}
} |
Java | @SuppressWarnings("serial")
public class WARCRecordFormat implements RecordFormat {
protected static final String WARC_VERSION = "WARC/1.0";
protected static final String CRLF = "\r\n";
protected static final byte[] CRLF_BYTES = { 13, 10 };
private static final Logger LOG = LoggerFactory
.getLogger(WARCRecordFormat.class);
/**
* Date formatter format the WARC-Date.
*
* Note: to meet the WARC 1.0 standard the precision is in seconds.
*/
public static final DateTimeFormatter WARC_DF = new DateTimeFormatterBuilder()
.appendInstant(0).toFormatter(Locale.ROOT);
protected static final Pattern PROBLEMATIC_HEADERS = Pattern
.compile("(?i)(?:Content-(?:Encoding|Length)|Transfer-Encoding)");
protected static final String X_HIDE_HEADER = "X-Crawler-";
private static final Base32 base32 = new Base32();
private static final String digestNoContent = getDigestSha1(new byte[0]);
public static String getDigestSha1(byte[] bytes) {
return "sha1:" + base32.encodeAsString(DigestUtils.sha1(bytes));
}
public static String getDigestSha1(byte[] bytes1, byte[] bytes2) {
MessageDigest sha1 = DigestUtils.getSha1Digest();
sha1.update(bytes1);
return "sha1:" + base32.encodeAsString(sha1.digest(bytes2));
}
/**
* Generates a WARC info entry which can be stored at the beginning of each
* WARC file.
**/
public static byte[] generateWARCInfo(Map<String, String> fields) {
StringBuffer buffer = new StringBuffer();
buffer.append(WARC_VERSION);
buffer.append(CRLF);
buffer.append("WARC-Type: warcinfo").append(CRLF);
String mainID = UUID.randomUUID().toString();
// retrieve the date and filename from the map
String date = fields.get("WARC-Date");
buffer.append("WARC-Date: ").append(date).append(CRLF);
String filename = fields.get("WARC-Filename");
buffer.append("WARC-Filename: ").append(filename).append(CRLF);
buffer.append("WARC-Record-ID").append(": ").append("<urn:uuid:")
.append(mainID).append(">").append(CRLF);
buffer.append("Content-Type").append(": ")
.append("application/warc-fields").append(CRLF);
StringBuilder fieldsBuffer = new StringBuilder();
// add WARC fields
// http://bibnum.bnf.fr/warc/WARC_ISO_28500_version1_latestdraft.pdf
Iterator<Entry<String, String>> iter = fields.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
if (key.startsWith("WARC-"))
continue;
fieldsBuffer.append(key).append(": ").append(entry.getValue())
.append(CRLF);
}
buffer.append("Content-Length")
.append(": ")
.append(fieldsBuffer.toString()
.getBytes(StandardCharsets.UTF_8).length).append(CRLF);
buffer.append(CRLF);
buffer.append(fieldsBuffer.toString());
buffer.append(CRLF);
buffer.append(CRLF);
return buffer.toString().getBytes(StandardCharsets.UTF_8);
}
/**
* Modify verbatim HTTP response headers: remove or replace headers
* <code>Content-Length</code>, <code>Content-Encoding</code> and
* <code>Transfer-Encoding</code> which may confuse WARC readers. Ensure
* that the header end with a single empty line (<code>\r\n\r\n</code>).
*
* @param headers
* HTTP 1.1 or 1.0 response header string, CR-LF-separated lines,
* first line is status line
* @return safe HTTP response header
*/
public static String fixHttpHeaders(String headers, int contentLength) {
int start = 0, lineEnd = 0, last = 0, trailingCrLf = 0;
StringBuilder replace = new StringBuilder();
while (start < headers.length()) {
lineEnd = headers.indexOf(CRLF, start);
trailingCrLf = 1;
if (lineEnd == -1) {
lineEnd = headers.length();
trailingCrLf = 0;
}
int colonPos = -1;
for (int i = start; i < lineEnd; i++) {
if (headers.charAt(i) == ':') {
colonPos = i;
break;
}
}
if (colonPos == -1) {
boolean valid = true;
if (start == 0) {
// status line (without colon)
} else if ((lineEnd + 4) == headers.length()
&& headers.endsWith(CRLF + CRLF)) {
// ok, trailing empty line
trailingCrLf = 2;
} else if (start == lineEnd) {
// skip/remove empty line
valid = false;
} else {
LOG.warn("Invalid header line: {}",
headers.substring(start, lineEnd));
valid = false;
}
if (!valid) {
if (last < start) {
replace.append(headers.substring(last, start));
}
last = lineEnd + 2 * trailingCrLf;
}
start = lineEnd + 2 * trailingCrLf;
/*
* skip over invalid header line, no further check for
* problematic headers required
*/
continue;
}
String name = headers.substring(start, colonPos);
if (PROBLEMATIC_HEADERS.matcher(name).matches()) {
boolean needsFix = true;
if (name.equalsIgnoreCase("content-length")) {
String value = headers.substring(colonPos + 1, lineEnd)
.trim();
try {
int l = Integer.parseInt(value);
if (l == contentLength) {
needsFix = false;
}
} catch (NumberFormatException e) {
// needs to be fixed
}
}
if (needsFix) {
if (last < start) {
replace.append(headers.substring(last, start));
}
last = lineEnd + 2 * trailingCrLf;
replace.append(X_HIDE_HEADER)
.append(headers.substring(start, lineEnd + 2
* trailingCrLf));
if (trailingCrLf == 0) {
replace.append(CRLF);
trailingCrLf = 1;
}
if (name.equalsIgnoreCase("content-length")) {
// add effective uncompressed and unchunked length of
// content
replace.append("Content-Length").append(": ")
.append(contentLength).append(CRLF);
}
}
}
start = lineEnd + 2 * trailingCrLf;
}
if (last > 0 || trailingCrLf != 2) {
if (last < headers.length()) {
// append trailing headers
replace.append(headers.substring(last));
}
while (trailingCrLf < 2) {
replace.append(CRLF);
trailingCrLf++;
}
return replace.toString();
}
return headers;
}
/**
* Get the actual fetch time from metadata and format it as required by the
* WARC-Date field. If no fetch time is found in metadata (key
* {@link REQUEST_TIME_KEY}), the current time is taken.
*/
protected static String getCaptureTime(Metadata metadata) {
String captureTimeMillis = metadata.getFirstValue(REQUEST_TIME_KEY);
Instant capturedAt = Instant.now();
if (captureTimeMillis != null) {
try {
long millis = Long.parseLong(captureTimeMillis);
capturedAt = Instant.ofEpochMilli(millis);
} catch (NumberFormatException | DateTimeException e) {
LOG.warn("Failed to parse capture time:", e);
}
}
return WARC_DF.format(capturedAt);
}
@Override
public byte[] format(Tuple tuple) {
byte[] content = tuple.getBinaryByField("content");
String url = tuple.getStringByField("url");
Metadata metadata = (Metadata) tuple.getValueByField("metadata");
// were the headers stored as is? Can write a response element then
String headersVerbatim = metadata.getFirstValue(RESPONSE_HEADERS_KEY);
byte[] httpheaders = new byte[0];
if (StringUtils.isNotBlank(headersVerbatim)) {
headersVerbatim = fixHttpHeaders(headersVerbatim, content.length);
httpheaders = headersVerbatim.getBytes();
}
StringBuilder buffer = new StringBuilder();
buffer.append(WARC_VERSION);
buffer.append(CRLF);
String mainID = UUID.randomUUID().toString();
buffer.append("WARC-Record-ID").append(": ").append("<urn:uuid:")
.append(mainID).append(">").append(CRLF);
String warcRequestId = metadata
.getFirstValue("_request.warc_record_id_");
if (warcRequestId != null) {
buffer.append("WARC-Concurrent-To").append(": ")
.append("<urn:uuid:").append(warcRequestId).append(">")
.append(CRLF);
}
int contentLength = 0;
String payloadDigest = digestNoContent;
String blockDigest;
if (content != null) {
contentLength = content.length;
payloadDigest = getDigestSha1(content);
blockDigest = getDigestSha1(httpheaders, content);
} else {
blockDigest = getDigestSha1(httpheaders);
}
// add the length of the http header
contentLength += httpheaders.length;
buffer.append("Content-Length").append(": ")
.append(Integer.toString(contentLength)).append(CRLF);
String captureTime = getCaptureTime(metadata);
buffer.append("WARC-Date").append(": ").append(captureTime)
.append(CRLF);
// check if http headers have been stored verbatim
// if not generate a response instead
String WARCTypeValue = "resource";
if (StringUtils.isNotBlank(headersVerbatim)) {
WARCTypeValue = "response";
}
buffer.append("WARC-Type").append(": ").append(WARCTypeValue)
.append(CRLF);
// "WARC-IP-Address" if present
String IP = metadata.getFirstValue(RESPONSE_IP_KEY);
if (StringUtils.isNotBlank(IP)) {
buffer.append("WARC-IP-Address").append(": ").append(IP)
.append(CRLF);
}
// must be a valid URI
try {
String normalised = url.replaceAll(" ", "%20");
String targetURI = URI.create(normalised).toASCIIString();
buffer.append("WARC-Target-URI").append(": ").append(targetURI)
.append(CRLF);
} catch (Exception e) {
LOG.warn("Incorrect URI: {}", url);
return new byte[] {};
}
// provide a ContentType if type response
if (WARCTypeValue.equals("response")) {
buffer.append("Content-Type: application/http; msgtype=response")
.append(CRLF);
}
// for resources just use the content type provided by the server if any
else {
String ct = metadata.getFirstValue(HttpHeaders.CONTENT_TYPE);
if (StringUtils.isBlank(ct)) {
ct = "application/octet-stream";
}
buffer.append("Content-Type: ").append(ct).append(CRLF);
}
String truncated = metadata.getFirstValue("http.trimmed");
if (truncated != null) {
// content is truncated
truncated = metadata.getFirstValue("http.trimmed.reason");
if (truncated == null) {
truncated = ProtocolResponse.TrimmedContentReason.UNSPECIFIED
.toString().toLowerCase(Locale.ROOT);
}
buffer.append("WARC-Truncated").append(": ").append(truncated)
.append(CRLF);
}
buffer.append("WARC-Payload-Digest").append(": ").append(payloadDigest)
.append(CRLF);
buffer.append("WARC-Block-Digest").append(": ").append(blockDigest)
.append(CRLF);
byte[] buffasbytes = buffer.toString().getBytes(StandardCharsets.UTF_8);
// work out the *exact* length of the bytebuffer - do not add any extra
// bytes which are appended as trailing zero bytes causing invalid WARC
// files
int capacity = 6 + buffasbytes.length + httpheaders.length;
if (content != null) {
capacity += content.length;
}
ByteBuffer bytebuffer = ByteBuffer.allocate(capacity);
bytebuffer.put(buffasbytes);
bytebuffer.put(CRLF_BYTES);
bytebuffer.put(httpheaders);
// the binary content itself
if (content != null) {
bytebuffer.put(content);
}
bytebuffer.put(CRLF_BYTES);
bytebuffer.put(CRLF_BYTES);
return bytebuffer.array();
}
} |
Java | class MapifyTests extends TestBase {
@Data
@NoArgsConstructor
private static class Thing {
String name;
Long weight;
Thing(String name, Long weight) {
this.name = name;
this.weight = weight;
}
}
@Subclass
@Data
@EqualsAndHashCode(callSuper = true)
@NoArgsConstructor
private static class ThingSubclass extends Thing {
ThingSubclass(String name, Long weight) {
super(name, weight);
}
}
private static class ThingMapper implements Mapper<Long, Thing> {
@Override
public Long getKey(Thing value) {
return value.weight;
}
}
@Entity
@Data
private static class HasMapify {
@Id Long id;
@Mapify(ThingMapper.class)
Map<Long, Thing> things = new LinkedHashMap<>();
}
@Test
void basicMapify() throws Exception {
factory().register(HasMapify.class);
final HasMapify hasMap = new HasMapify();
final Thing thing0 = new Thing("foo", 123L);
hasMap.things.put(thing0.weight, thing0);
final Thing thing1 = new Thing("bar", 456L);
hasMap.things.put(thing1.weight, thing1);
checkTestMapify(hasMap);
}
@Test
void mapifyPolymorphic() throws Exception {
factory().register(HasMapify.class);
factory().register(ThingSubclass.class);
HasMapify hasMap = new HasMapify();
Thing thing0 = new ThingSubclass("foo", 123L);
hasMap.things.put(thing0.weight, thing0);
Thing thing1 = new ThingSubclass("bar", 456L);
hasMap.things.put(thing1.weight, thing1);
checkTestMapify(hasMap);
}
private void checkTestMapify(final HasMapify hasMap) {
final HasMapify fetched = saveClearLoad(hasMap);
assertThat(fetched).isEqualTo(hasMap);
assertThat(fetched.things).isInstanceOf(LinkedHashMap.class);
}
/** */
@Entity
@Data
@NoArgsConstructor
private static class Top {
@Id long id;
@Mapify(BottomMapper.class)
Map<String, Bottom> bottoms = new HashMap<>();
Top(long id) { this.id = id; }
}
/** */
@Data
private static class Bottom {
@Load Ref<Top> top;
String name;
}
private static class BottomMapper implements Mapper<String, Bottom> {
@Override
public String getKey(Bottom value) {
assertThat(value.top).isNotNull(); // this is the problem place
return value.name;
}
}
/**
*/
@Test
void bidirectionalMapify() throws Exception {
factory().register(Top.class);
final Top top = new Top(123);
final Bottom bot = new Bottom();
bot.name = "foo";
bot.top = Ref.create(top);
top.bottoms.put(bot.name, bot);
final Top topFetched = saveClearLoad(top);
assertThat(topFetched).isEqualTo(top);
final Bottom bottomFetched = topFetched.bottoms.get(bot.name);
assertThat(bottomFetched.top.get()).isSameInstanceAs(topFetched);
assertThat(bottomFetched).isEqualTo(bot);
}
/** */
private static class TrivialMapper implements Mapper<Key<Trivial>, Ref<Trivial>> {
@Override
public Key<Trivial> getKey(Ref<Trivial> value) {
return value.key();
}
}
@Entity
@Data
private static class HasMapifyTrivial {
@Id Long id;
@Mapify(TrivialMapper.class)
@Load
Map<Key<Trivial>, Ref<Trivial>> trivials = new HashMap<>();
}
/** Tests using mapify on refs */
@Test
void mapifyTrivialRefs() throws Exception {
factory().register(Trivial.class);
factory().register(HasMapifyTrivial.class);
final Trivial triv = new Trivial("foo", 123L);
final Key<Trivial> trivKey = ofy().save().entity(triv).now();
final HasMapifyTrivial hasMap = new HasMapifyTrivial();
hasMap.trivials.put(trivKey, Ref.create(triv));
final HasMapifyTrivial fetched = saveClearLoad(hasMap);
assertThat(fetched).isEqualTo(hasMap);
}
} |
Java | public static class AgedBrie implements UpdateRule {
@Override
public boolean update(Item item) {
if (item.name.equals("Aged Brie")) {
item.sellIn = item.sellIn - 1;
if (item.sellIn < 0) {
item.quality = Math.min(MAX_QUALITY, item.quality + 2);
} else {
item.quality = Math.min(MAX_QUALITY, item.quality + 1);
}
return true;
}
return false;
}
} |
Java | public static class Sulfuras implements UpdateRule {
@Override
public boolean update(Item item) {
if (item.name.equals("Sulfuras, Hand of Ragnaros")) {
return true;
}
return false;
}
} |
Java | public static class BackstagePass implements UpdateRule {
@Override
public boolean update(Item item) {
if (item.name.equals("Backstage passes to a TAFKAL80ETC concert")) {
item.sellIn = item.sellIn - 1;
if (item.sellIn < 0) {
item.quality = 0;
} else if (item.sellIn < 6) {
item.quality = Math.min(MAX_QUALITY, item.quality + 3);
} else if (item.sellIn < 11) {
item.quality = Math.min(MAX_QUALITY, item.quality + 2);
} else {
item.quality = Math.min(MAX_QUALITY, item.quality + 1);
}
return true;
}
return false;
}
} |
Java | public static class OtherItem implements UpdateRule {
@Override
public boolean update(Item item) {
item.sellIn = item.sellIn - 1;
if (item.sellIn < 0) {
item.quality = Math.max(0, item.quality - 2);
} else {
item.quality = Math.max(0, item.quality - 1);
}
return true;
}
} |
Java | public final class LateWildcardType implements WildcardType {
private static final Type[] OBJECT_TYPE_ARRAY = new Type[] {Object.class};
private final Type[] upperBounds; // ? extends T & U
private final Type[] lowerBounds; // ? super T & U
private LateWildcardType(Type[] upperBounds, Type[] lowerBounds) {
this.upperBounds = upperBounds;
this.lowerBounds = lowerBounds;
}
/**
* Constructs a wildcard type having the given bounds. The keyword specifies what kind of bounds the wildcard
* type should have. Valid values are the exact strings {@code "?"}, {@code "? extends"}, and {@code "? super"}.
* The default upper bound (used when no upper bounds are explicitly specified) is Object.class.
*
* Examples:
* <pre>
* new LateWildcardType("?")
* - a wildcard with an implicit upper bound of Object
*
* new LateWildcardType("? extends", Number.class)
* - a wildcard with an upper bound of Number
*
* new LateWildcardType("? super", Comparable.class)
* - a wildcard with a lower bound of Comparable
* </pre>
*
* @param keyword the kind of wildcard to construct.
* @param bounds the wildcard bounds.
* @throws NullPointerException if bounds is null or keyword is null.
* @throws IllegalArgumentException if keyword is not one of {@code "?"}, {@code "? extends"}, and
* {@code "? super"}, or if bounds are provided when using keyword {@code "?"},
* or if any bound is not suitable for use as a wildcard bound.
*/
public LateWildcardType(String keyword, Type... bounds) {
for (Type bound : bounds) {
if (bound == null || bound instanceof WildcardType) {
throw new IllegalArgumentException("not suitable as wildcard bound: " + bound);
}
}
switch (keyword) {
case "?":
if (bounds.length != 0) {
throw new IllegalArgumentException("bounds not expected");
}
upperBounds = OBJECT_TYPE_ARRAY;
lowerBounds = EMPTY_TYPE_ARRAY;
break;
case "? extends":
if (bounds.length == 0) {
throw new IllegalArgumentException("upper bounds expected");
}
upperBounds = bounds.clone();
lowerBounds = EMPTY_TYPE_ARRAY;
break;
case "? super":
if (bounds.length == 0) {
throw new IllegalArgumentException("lower bounds expected");
}
upperBounds = OBJECT_TYPE_ARRAY;
lowerBounds = bounds.clone();
break;
default:
throw new IllegalArgumentException("unknown keyword: " + keyword);
}
}
/**
* Builds a LateWildcardType representation of the specified WildcardType.
*
* @param wt the wildcard type to copy.
* @return a LateWildcardType copy of the provided type.
* @throws NullPointerException if the argument is null or its bounds are null.
* @throws IllegalArgumentException if any bound is not suitable for use as a wildcard bound.
*/
public static LateWildcardType copyOf(WildcardType wt) {
return new LateWildcardType(wt.getUpperBounds().clone(), wt.getLowerBounds().clone());
}
/**
* Returns this wildcard's upper bound(s). If no upper bound is explicitly defined, the upper bound
* is {@code Object}.
*
* @return this wildcard's upper bound(s).
*/
@Override public Type[] getUpperBounds() {
return upperBounds.clone();
}
/**
* Returns this wildcard type's lower bound(s). If no lower bound is explicitly defined, this method returns
* an empty array.
*
* @return this wildcard's lower bound(s).
*/
@Override public Type[] getLowerBounds() {
return lowerBounds.clone();
}
private boolean equals(WildcardType that) {
return
Arrays.equals(this.upperBounds, that.getUpperBounds()) &&
Arrays.equals(this.lowerBounds, that.getLowerBounds());
}
/**
* Returns true if the specific object is a WildcardType and its bounds equal this wildcard's bounds.
*/
@Override public boolean equals(Object that) {
return this == that || that instanceof WildcardType && equals((WildcardType)that);
}
/**
* The hash code for a wildcard type is defined to be the XOR'd hash codes of its bound arrays, as per
* Oracle's implementation.
*/
@Override public int hashCode() {
return Arrays.hashCode(upperBounds) ^ Arrays.hashCode(lowerBounds);
}
/**
* Returns a string representation of this wildcard type having the format "? extends" + upper bounds,
* "? super" + lower bounds, or "?" as appropriate.
*/
@Override public String toString() {
return print(this);
}
} |
Java | @XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "BinnenlandsAdresType", propOrder = {
"straatnaam",
"aanduidingBijHuisnummer",
"huisnummer",
"huisnummerToevoeging",
"huisletter",
"postbusnummer",
"postcode",
"plaats",
"bagId"
})
public class BinnenlandsAdresType
extends MetExtraElementenMogenlijkheidType
{
protected String straatnaam;
protected EnumeratieType aanduidingBijHuisnummer;
protected BigInteger huisnummer;
protected String huisnummerToevoeging;
protected String huisletter;
protected BigInteger postbusnummer;
protected PostcodeType postcode;
protected String plaats;
protected BagIdType bagId;
/**
* Gets the value of the straatnaam property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStraatnaam() {
return straatnaam;
}
/**
* Sets the value of the straatnaam property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStraatnaam(String value) {
this.straatnaam = value;
}
/**
* Gets the value of the aanduidingBijHuisnummer property.
*
* @return
* possible object is
* {@link EnumeratieType }
*
*/
public EnumeratieType getAanduidingBijHuisnummer() {
return aanduidingBijHuisnummer;
}
/**
* Sets the value of the aanduidingBijHuisnummer property.
*
* @param value
* allowed object is
* {@link EnumeratieType }
*
*/
public void setAanduidingBijHuisnummer(EnumeratieType value) {
this.aanduidingBijHuisnummer = value;
}
/**
* Gets the value of the huisnummer property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getHuisnummer() {
return huisnummer;
}
/**
* Sets the value of the huisnummer property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setHuisnummer(BigInteger value) {
this.huisnummer = value;
}
/**
* Gets the value of the huisnummerToevoeging property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHuisnummerToevoeging() {
return huisnummerToevoeging;
}
/**
* Sets the value of the huisnummerToevoeging property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHuisnummerToevoeging(String value) {
this.huisnummerToevoeging = value;
}
/**
* Gets the value of the huisletter property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getHuisletter() {
return huisletter;
}
/**
* Sets the value of the huisletter property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setHuisletter(String value) {
this.huisletter = value;
}
/**
* Gets the value of the postbusnummer property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getPostbusnummer() {
return postbusnummer;
}
/**
* Sets the value of the postbusnummer property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setPostbusnummer(BigInteger value) {
this.postbusnummer = value;
}
/**
* Gets the value of the postcode property.
*
* @return
* possible object is
* {@link PostcodeType }
*
*/
public PostcodeType getPostcode() {
return postcode;
}
/**
* Sets the value of the postcode property.
*
* @param value
* allowed object is
* {@link PostcodeType }
*
*/
public void setPostcode(PostcodeType value) {
this.postcode = value;
}
/**
* Gets the value of the plaats property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPlaats() {
return plaats;
}
/**
* Sets the value of the plaats property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlaats(String value) {
this.plaats = value;
}
/**
* Gets the value of the bagId property.
*
* @return
* possible object is
* {@link BagIdType }
*
*/
public BagIdType getBagId() {
return bagId;
}
/**
* Sets the value of the bagId property.
*
* @param value
* allowed object is
* {@link BagIdType }
*
*/
public void setBagId(BagIdType value) {
this.bagId = value;
}
} |
Java | @WebServlet("/covid-data")
public class CovidDataServlet extends HttpServlet {
ArrayList<DateEntry> covidData = new ArrayList();
/*
* Object to hold COVID cases for each state for given day
*/
private final class DateEntry {
// date represented as YYYY-MM-DD
private String date;
// contains keys of full state name and values of cases in that state for given day
private LinkedHashMap<String, Integer> cases = new LinkedHashMap();
public DateEntry(String date) {
this.date = date;
this.cases = cases;
}
public void addEntry(String state, Integer cases) {
this.cases.put(state, cases);
}
}
@Override
public void init() {
Scanner scanner = new Scanner(getServletContext().getResourceAsStream(
"/WEB-INF/us-states.csv"));
String currDate = "";
DateEntry temp = null;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] cells = line.split(",");
String date = cells[0];
String state = cells[1];
Integer cases = Integer.valueOf(cells[3]);
// create new date entry if data changed
if (!currDate.equals(date)) {
// put old entry into arr, first entry is null
if (temp != null) {
covidData.add(temp);
}
temp = new DateEntry(date);
currDate = date;
}
temp.addEntry(state, cases);
}
scanner.close();
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
Gson gson = new Gson();
String json = gson.toJson(covidData);
response.getWriter().println(json);
}
} |
Java | private final class DateEntry {
// date represented as YYYY-MM-DD
private String date;
// contains keys of full state name and values of cases in that state for given day
private LinkedHashMap<String, Integer> cases = new LinkedHashMap();
public DateEntry(String date) {
this.date = date;
this.cases = cases;
}
public void addEntry(String state, Integer cases) {
this.cases.put(state, cases);
}
} |
Java | public class BnfIntroduceRulePopup extends InplaceVariableIntroducer<BnfExpression> {
private static final String PRIVATE = "private ";
private final JPanel myPanel = new JPanel(new GridBagLayout());
private final JCheckBox myCheckBox = new NonFocusableCheckBox("Declare private");
public BnfIntroduceRulePopup(Project project, Editor editor, BnfRule rule, BnfExpression expr) {
super(rule, editor, project, "Introduce Rule", GrammarUtil.EMPTY_EXPRESSIONS_ARRAY, expr);
myCheckBox.setSelected(true);
myCheckBox.setMnemonic('p');
myPanel.setBorder(null);
myPanel.add(myCheckBox, new GridBagConstraints(0, 1, 1, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, JBUI.insets(5), 0, 0));
myPanel.add(Box.createVerticalBox(), new GridBagConstraints(0, 2, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, JBUI.emptyInsets(), 0, 0));
}
@Override
protected void moveOffsetAfter(boolean success) {
RangeMarker exprMarker = getExprMarker();
WriteAction.run(() -> {
Document document = myEditor.getDocument();
// todo restore original expression if not success
PsiDocumentManager.getInstance(myProject).commitDocument(document);
if (exprMarker != null && exprMarker.isValid()) {
myEditor.getCaretModel().moveToOffset(exprMarker.getStartOffset());
myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
exprMarker.dispose();
}
});
}
@Override
protected JComponent getComponent() {
myCheckBox.addActionListener(e -> WriteCommandAction.writeCommandAction(myProject)
.withName(BnfIntroduceRuleHandler.REFACTORING_NAME)
.run(() -> perform(myCheckBox.isSelected())));
return myPanel;
}
public void perform(boolean generatePrivate) {
final Runnable runnable = () -> {
final DocumentEx document = (DocumentEx) myEditor.getDocument();
int exprOffset = myExprMarker.getStartOffset();
final int lineOffset = getLineOffset(document, exprOffset);
if (generatePrivate) {
final Collection<RangeMarker> leftGreedyMarker = new ArrayList<>();
final Collection<RangeMarker> emptyMarkers = new ArrayList<>();
for (RangeHighlighter rangeHighlighter : myEditor.getMarkupModel().getAllHighlighters()) {
collectRangeMarker(rangeHighlighter, lineOffset, leftGreedyMarker, emptyMarkers);
}
document.processRangeMarkers(rangeMarker -> {
collectRangeMarker(rangeMarker, lineOffset, leftGreedyMarker, emptyMarkers);
return true;
});
setLeftGreedy(leftGreedyMarker, false);
setRightGreedy(emptyMarkers, true);
// workaround for shifting empty ranges to the left
document.insertString(lineOffset, " ");
document.insertString(lineOffset, PRIVATE);
document.deleteString(lineOffset + PRIVATE.length(), lineOffset + PRIVATE.length() + 1);
setLeftGreedy(leftGreedyMarker, true);
setRightGreedy(emptyMarkers, false);
} else {
int idx = document.getText().indexOf(PRIVATE, lineOffset);
if (idx > -1 && idx < exprOffset) {
document.deleteString(idx, idx + PRIVATE.length());
}
}
PsiDocumentManager.getInstance(myProject).commitDocument(document);
};
final LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor);
if (lookup != null) {
lookup.performGuardedChange(runnable);
} else {
runnable.run();
}
}
private static void setRightGreedy(Collection<RangeMarker> rightRestore, boolean greedyToRight) {
for (RangeMarker rangeMarker : rightRestore) {
rangeMarker.setGreedyToRight(greedyToRight);
}
}
private static void setLeftGreedy(Collection<RangeMarker> leftRestore, boolean greedyToLeft) {
for (RangeMarker rangeMarker : leftRestore) {
rangeMarker.setGreedyToLeft(greedyToLeft);
}
}
private static void collectRangeMarker(RangeMarker rangeMarker, int lineOffset,
Collection<RangeMarker> leftGreedyMarkers, Collection<RangeMarker> emptyMarkers) {
if (rangeMarker.getStartOffset() == lineOffset && rangeMarker.isGreedyToLeft()) {
leftGreedyMarkers.add(rangeMarker);
}
if (rangeMarker.getStartOffset() == lineOffset && rangeMarker.getEndOffset() == lineOffset && !rangeMarker.isGreedyToRight()) {
emptyMarkers.add(rangeMarker);
}
}
private static int getLineOffset(Document document, final int offset) {
return 0 <= offset && offset < document.getTextLength()
? document.getLineStartOffset(document.getLineNumber(offset))
: 0;
}
} |
Java | public class UnregisterStaffCommandParser implements Parser<ReversibleActionPairCommand> {
private List<Person> lastShownList;
public UnregisterStaffCommandParser(Model model) {
this.lastShownList = model.getFilteredStaffList();
}
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns an ReversibleActionPairCommand object containing an DeleteCommand for execution.
*
* @throws ParseException if the user input does not conform the expected format
*/
public ReversibleActionPairCommand parse(String args) throws ParseException {
Index index;
try {
index = ParserUtil.parseIndex(args);
} catch (ParseException pe) {
throw new ParseException(
String.format(pe.getMessage(), UnregisterStaffCommand.MESSAGE_USAGE), pe);
}
Person personToDelete = ParserUtil.getEntryFromList(lastShownList, index);
return new ReversibleActionPairCommand(
new UnregisterStaffCommand(personToDelete),
new RegisterStaffCommand(personToDelete));
}
} |
Java | @Path("/")
public class MyResource {
@GET
@Path("/command/{code}")
public String getStateWithCommand(@PathParam("code") String stateCode) throws Exception {
return this.getStateWithCommandRepeated(stateCode, 1);
}
@GET
@Path("/command/{code}/{repeat}")
public String getStateWithCommandRepeated(@PathParam("code") String stateCode, @PathParam("repeat") int times) throws Exception {
HystrixRequestContext context = HystrixRequestContext.initializeContext();
try {
String output = "";
for (int i=0; i < times; i++) {
output += new StateCommand(stateCode).execute() + "\n\r";
}
return output;
} finally {
context.shutdown();
}
}
} |
Java | @Mojo(name = "opear-plan",
requiresDependencyResolution = ResolutionScope.RUNTIME_PLUS_SYSTEM,
configurator = OakpalComponentConfigurator.HINT,
defaultPhase = LifecyclePhase.PREPARE_PACKAGE)
public class OpearPlanMojo extends AbstractCommonMojo implements MojoWithPlanParams {
/**
* Specify the output file for the serialized opear plan.
*/
@Parameter(name = "planFile", defaultValue = "${project.build.directory}/oakpal-plugin/opear-plans/plan.json", required = true)
File planFile;
/**
* Specify the plan parameters.
*/
@Parameter(name = "planParams")
PlanParams planParams;
@Override
public void execute() throws MojoFailureException {
planFile.getParentFile().mkdirs();
final JsonWriterFactory writerFactory =
Json.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(planFile), StandardCharsets.UTF_8);
JsonWriter writer = writerFactory.createWriter(osw)) {
Thread.currentThread().setContextClassLoader(createContainerClassLoader());
OakpalPlan plan = buildPlan();
writer.writeObject(plan.toJson());
} catch (IOException e) {
throw new MojoFailureException("Failed to write plan json to file " + planFile.getAbsolutePath(), e);
} finally {
Thread.currentThread().setContextClassLoader(oldCl);
}
}
@Override
public PlanBuilderParams getPlanBuilderParams() {
return Optional.ofNullable(planParams).orElse(new PlanParams());
}
} |
Java | public class AppConfig {
String configFile = Configuration.sourceDirPrefix+"/"+Configuration.projectDirInSourceFolder+"/defaultProject/appConfig.xml";
boolean configExists = false;
public int projectSelectorWindowWidth = 600;
public int projectSelectorWindowHeight= 400;
public int projectSelectorWindowPosX= 50;
public int projectSelectorWindowPosY= 50;
public boolean projectSelectorIsMaximized = false;
public int projectSelectorSelectedTab = 1; // 1 = description, 2 = config
public String lastChosenProject = "";
public int guiWindowWidth = 800;
public int guiWindowHeight = 600;
public int guiWindowPosX = 50;
public int guiWindowPosY = 50;
public boolean guiIsMaximized = false;
public long seedFromLastRun = 0;
public int helpWindowWidth = 500;
public int helpWindowHeight = 500;
public int helpWindowPosX = 200;
public int helpWindowPosY = 200;
public boolean helpWindowIsMaximized = false;
public boolean guiControlPanelExpandSimulation = true;
public boolean guiControlPanelShowFullViewPanel = true;
public boolean guiControlPanelShowTextPanel = true;
public boolean guiControlPanelShowProjectControl = true;
public boolean guiRunOperationIsLimited = true; // infinite many (rounds/events) or the specified amount?
public String lastSelectedFileDirectory = ""; // where the user pointed last to open a file
public boolean checkForSinalgoUpdate = true; // check for updates
public long timeStampOfLastUpdateCheck = 0; // machine time when Sinalgo checked last for an update
public int generateNodesDlgNumNodes = 100; // # of nodes to generate
public String previousRunCmdLineArgs = ""; // cmd line args of the previous call to 'Run'
private static AppConfig singletonInstance = null; // the singleton instance
/**
* @return The singleton instance of AppConfig.
*/
public static AppConfig getAppConfig() {
if(singletonInstance == null) {
singletonInstance = new AppConfig();
}
return singletonInstance;
}
/**
* @return A file describing the directory that was chosen last,
* if this directory does not exist anymore, the directory of the
* current project.
*/
public File getLastSelectedFileDirectory() {
File f = new File(lastSelectedFileDirectory);
if(!f.exists()) {
f = new File(Global.getProjectSrcDir());
}
return f;
}
/**
* Singleton constructor
*/
private AppConfig() {
File file= new File(configFile);
if(file.exists()){
configExists = true;
} else {
return;
}
try {
Document doc = new SAXBuilder().build(configFile);
Element root = doc.getRootElement();
// Read the entries for the Project Selector
Element e = root.getChild("ProjectSelector");
if(e != null) {
String v = e.getAttributeValue("windowWidth");
if(v != null) {
try {
projectSelectorWindowWidth = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowHeight");
if(v != null) {
try {
projectSelectorWindowHeight= Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowPosX");
if(v != null) {
try {
projectSelectorWindowPosX= Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowPosY");
if(v != null) {
try {
projectSelectorWindowPosY= Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("lastChosenProject");
if(v != null) {
lastChosenProject = v;
}
v = e.getAttributeValue("isMaximized");
if(v != null) {
projectSelectorIsMaximized = v.equals("true");
}
v = e.getAttributeValue("selectedTab");
if(v != null) {
try {
projectSelectorSelectedTab = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
}
// Read the entries for the GUI
e = root.getChild("GUI");
if(e != null) {
String v = e.getAttributeValue("windowWidth");
if(v != null) {
try {
guiWindowWidth = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowHeight");
if(v != null) {
try {
guiWindowHeight = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowPosX");
if(v != null) {
try {
guiWindowPosX = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("windowPosY");
if(v != null) {
try {
guiWindowPosY = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("isMaximized");
if(v != null) {
guiIsMaximized = v.equals("true");
}
v = e.getAttributeValue("ControlPanelExpandSimulation");
if(v != null) {
guiControlPanelExpandSimulation = v.equals("true");
}
v = e.getAttributeValue("ControlPanelShowFullViewPanel");
if(v != null) {
guiControlPanelShowFullViewPanel = v.equals("true");
}
v = e.getAttributeValue("ControlPanelShowTextPanel");
if(v != null) {
guiControlPanelShowTextPanel = v.equals("true");
}
v = e.getAttributeValue("ControlPanelShowProjectControl");
if(v != null) {
guiControlPanelShowProjectControl = v.equals("true");
}
v = e.getAttributeValue("RunOperationIsLimited");
if(v != null) {
guiRunOperationIsLimited = v.equals("true");
}
v = e.getAttributeValue("helpWindowWidth");
if(v != null) {
try {
helpWindowWidth = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("helpWindowHeight");
if(v != null) {
try {
helpWindowHeight= Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("helpWindowPosX");
if(v != null) {
try {
helpWindowPosX = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("helpWindowPosY");
if(v != null) {
try {
helpWindowPosY = Integer.parseInt(v);
} catch(NumberFormatException ex) {
}
}
v = e.getAttributeValue("helpWindowIsMaximized");
if(v != null) {
try {
helpWindowIsMaximized = v.equals("true");
} catch(NumberFormatException ex) {
}
}
}
// read the seed from the last run
e = root.getChild("RandomSeed");
if(e != null) {
String s = e.getAttributeValue("seedFromPreviousRun");
if(s != null) {
try {
seedFromLastRun = Long.parseLong(s);
} catch(NumberFormatException ex) {
}
}
}
// Diverse App specific configs
e = root.getChild("App");
if(e != null) {
String s = e.getAttributeValue("lastSelectedFileDirectory");
if(s != null) {
lastSelectedFileDirectory = s;
}
s = e.getAttributeValue("checkForUpdatesAtStartup");
if(s != null) {
checkForSinalgoUpdate = s.equals("true");
}
s = e.getAttributeValue("updateCheckTimeStamp");
if(s != null) {
try {
timeStampOfLastUpdateCheck = Long.parseLong(s);
} catch(NumberFormatException ex) {
}
}
s = e.getAttributeValue("runCmdLineArgs");
if(s != null) {
previousRunCmdLineArgs = s;
}
}
// Generate Nodes Dlg
e = root.getChild("GenNodesDlg");
if(e != null) {
String s = e.getAttributeValue("numNodes");
if(s != null) {
try {
generateNodesDlgNumNodes = Integer.parseInt(s);
} catch(NumberFormatException ex) {
}
}
}
} catch (JDOMException e1) {
} catch (IOException e1) {
}
} // end of constructor
/**
* Writes the application wide config
*/
public void writeConfig() {
File file= new File(configFile);
Document doc = new Document();
Element root = new Element("sinalgo");
doc.setRootElement(root);
Element ps = new Element("ProjectSelector");
root.addContent(ps);
ps.setAttribute("windowWidth", Integer.toString(projectSelectorWindowWidth));
ps.setAttribute("windowHeight", Integer.toString(projectSelectorWindowHeight));
ps.setAttribute("lastChosenProject", lastChosenProject);
ps.setAttribute("windowPosX", Integer.toString(projectSelectorWindowPosX));
ps.setAttribute("windowPosY", Integer.toString(projectSelectorWindowPosY));
ps.setAttribute("isMaximized", projectSelectorIsMaximized ? "true" : "false");
ps.setAttribute("selectedTab", Integer.toString(projectSelectorSelectedTab));
Element gui = new Element("GUI");
root.addContent(gui);
gui.setAttribute("windowWidth", Integer.toString(guiWindowWidth));
gui.setAttribute("windowHeight", Integer.toString(guiWindowHeight));
gui.setAttribute("windowPosX", Integer.toString(guiWindowPosX));
gui.setAttribute("windowPosY", Integer.toString(guiWindowPosY));
gui.setAttribute("isMaximized", guiIsMaximized ? "true" : "false");
gui.setAttribute("ControlPanelExpandSimulation", guiControlPanelExpandSimulation ? "true" : "false");
gui.setAttribute("ControlPanelShowFullViewPanel", guiControlPanelShowFullViewPanel ? "true" : "false");
gui.setAttribute("ControlPanelShowTextPanel", guiControlPanelShowTextPanel ? "true" : "false");
gui.setAttribute("ControlPanelShowProjectControl", guiControlPanelShowProjectControl ? "true" : "false");
gui.setAttribute("RunOperationIsLimited", guiRunOperationIsLimited ? "true" : "false");
gui.setAttribute("helpWindowWidth", Integer.toString(helpWindowWidth));
gui.setAttribute("helpWindowHeight", Integer.toString(helpWindowHeight));
gui.setAttribute("helpWindowPosX", Integer.toString(helpWindowPosX));
gui.setAttribute("helpWindowPosY", Integer.toString(helpWindowPosY));
gui.setAttribute("helpWindowIsMaximized", helpWindowIsMaximized ? "true" : "false");
Element seed = new Element("RandomSeed");
root.addContent(seed);
seed.setAttribute("seedFromPreviousRun", Long.toString(Distribution.getSeed()));
Element app= new Element("App");
root.addContent(app);
app.setAttribute("lastSelectedFileDirectory", lastSelectedFileDirectory);
app.setAttribute("checkForUpdatesAtStartup", checkForSinalgoUpdate ? "true" : "false");
app.setAttribute("updateCheckTimeStamp", Long.toString(timeStampOfLastUpdateCheck));
app.setAttribute("runCmdLineArgs", previousRunCmdLineArgs);
Element genNodes = new Element("GenNodesDlg");
root.addContent(genNodes);
genNodes.setAttribute("numNodes", Integer.toString(generateNodesDlgNumNodes));
//write the xml
XMLOutputter outputter = new XMLOutputter();
Format f = Format.getPrettyFormat();
f.setIndent("\t");
outputter.setFormat(f);
try {
FileWriter fW = new FileWriter(file);
outputter.output(doc, fW);
} catch (IOException ex) {
}
}
} |
Java | public class Task
implements Serializable
{
// ---- data members ----------------------------------------------------
/**
* The creation time.
*/
private long createdAt;
/**
* The completion status.
*/
private Boolean completed;
/**
* The task ID.
*/
@Id
private String id;
/**
* The task description.
*/
private String description;
// ---- constructors ----------------------------------------------------
/**
* Deserialization constructor.
*/
public Task()
{
}
/**
* Construct Task instance.
*
* @param description task description
*/
public Task(String description)
{
this.id = UUID.randomUUID().toString().substring(0, 6);
this.createdAt = System.currentTimeMillis();
this.description = description;
this.completed = false;
}
// ---- accessors -------------------------------------------------------
/**
* Get the creation time.
*
* @return the creation time
*/
public Long getCreatedAt()
{
return createdAt;
}
/**
* Get the task ID.
*
* @return the task ID
*/
public String getId()
{
return id;
}
/**
* Get the task description.
*
* @return the task description
*/
public String getDescription()
{
return description;
}
/**
* Set the task description.
*
* @param description the task description
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* Get the completion status.
*
* @return true if it is completed, false otherwise.
*/
public Boolean getCompleted()
{
return completed;
}
/**
* Sets the completion status.
*
* @param completed the completion status
*/
public void setCompleted(Boolean completed)
{
this.completed = completed;
}
/**
* Returns the created date as a {@link LocalDateTime}.
*
* @return the created date as a {@link LocalDateTime}.
*/
public LocalDateTime getCreatedAtDate()
{
return LocalDateTime.ofInstant(Instant.ofEpochMilli(createdAt), ZoneId.systemDefault());
}
// ---- Object methods --------------------------------------------------
@Override
public String toString()
{
return "Task{"
+ "id=" + id
+ ", description=" + description
+ ", completed=" + completed
+ '}';
}
} |
Java | public class PatientProfileUtilTest {
/*
* Tests methods that converts patient's parameters into String.
* We have a total of 3 equivalence partitions.
* We partitioned null values as one invalid equivalence partition (EP1).
* Valid parameters as one valid equivalence partition (EP2).
* Empty (but not null) values as one valid equivalence partition (EP3).
* EP3 is only designed for parameters that can be empty.
*/
//-------------------- Tests for convertNameToString --------------------
// EP 1 - Null values
@Test
public void convertNameToString_nullName_throwsNullPointerException() {
Name patientName = null;
Assert.assertThrows(NullPointerException.class, "Patient's name cannot be null.", ()
-> PatientProfileUtil.convertNameToString(patientName));
}
// EP 2 - Valid parameters
@Test
public void convertNameToString_validNameInput_correctResult() {
Name name = new Name("Bob the Builder");
Assertions.assertEquals("Bob the Builder", PatientProfileUtil.convertNameToString(name));
}
//-------------------- Tests for convertAllergiesToString --------------------
// EP 1 - Null values
@Test
public void convertAllergiesToString_nullAllergySet_throwsNullPointerException() {
Set<Allergy> allergySet = null;
Assert.assertThrows(NullPointerException.class, "Patient's allergies set cannot be null.", ()
-> PatientProfileUtil.convertAllergiesToString(allergySet));
}
// EP 2 - Valid parameters
@Test
public void convertAllergiesToString_validAllergySet_correctResult() {
Set<Allergy> allergySet = new HashSet<>();
allergySet.add(new Allergy("Paracetamol"));
Assertions.assertEquals("Paracetamol; ", PatientProfileUtil.convertAllergiesToString(allergySet));
}
// EP 3 - Valid parameters that are empty
@Test
public void convertAllergiesToString_validEmptyAllergySet_correctResult() {
Set<Allergy> allergySet = new HashSet<>();
Assertions.assertEquals("-", PatientProfileUtil.convertAllergiesToString(allergySet));
}
//-------------------- Tests for convertPhoneToString --------------------
// EP 1 - Null values
@Test
public void convertPhoneToString_nullPhone_throwsNullPointerException() {
Phone patientPhone = null;
Assert.assertThrows(NullPointerException.class, "Patient's phone cannot be null.", ()
-> PatientProfileUtil.convertPhoneToString(patientPhone));
}
// EP 2 - Valid parameters
@Test
public void convertPhoneToString_validPhoneInput_correctResult() {
Phone patientPhone = new Phone("94214567");
Assertions.assertEquals("94214567", PatientProfileUtil.convertPhoneToString(patientPhone));
}
//-------------------- Tests for convertEmailToString --------------------
// EP 1 - Null values
@Test
public void convertEmailToString_nullEmail_throwsNullPointerException() {
Email patientEmail = null;
Assert.assertThrows(NullPointerException.class, "Patient's email cannot be null.", ()
-> PatientProfileUtil.convertEmailToString(patientEmail));
}
// EP 2 - Valid parameters
@Test
public void convertEmailToString_validEmailInput_correctResult() {
Email patientEmail = new Email("[email protected]");
Assertions.assertEquals("[email protected]",
PatientProfileUtil.convertEmailToString(patientEmail));
}
//-------------------- Tests for convertAddressToString --------------------
// EP 1 - Null values
@Test
public void convertAddressToString_nullAddress_throwsNullPointerException() {
Address patientAddress = null;
Assert.assertThrows(NullPointerException.class, "Patient's address cannot be null.", ()
-> PatientProfileUtil.convertAddressToString(patientAddress));
}
// EP 2 - Valid parameters
@Test
public void convertAddressToString_validAddressInput_correctResult() {
Address patientAddress = new Address("123 High Lane");
Assertions.assertEquals("123 High Lane", PatientProfileUtil.convertAddressToString(patientAddress));
}
//-------------------- Tests for convertIcToString --------------------
// EP 1 - Null values
@Test
public void convertIcToString_nullIc_throwsNullPointerException() {
IcNumber patientIc = null;
Assert.assertThrows(NullPointerException.class, "Patient's IC number cannot be null.", ()
-> PatientProfileUtil.convertIcToString(patientIc));
}
// EP 2 - Valid parameters
@Test
public void convertIcToString_validIcInput_correctResult() {
IcNumber patientIc = new IcNumber("S9822413E");
Assertions.assertEquals("S9822413E", PatientProfileUtil.convertIcToString(patientIc));
}
//-------------------- Tests for convertBloodTypeToString --------------------
// EP 1 - Null values
@Test
public void convertBloodTypeToString_nullBloodType_throwsNullPointerException() {
BloodType patientBloodType = null;
Assert.assertThrows(NullPointerException.class, "Patient's blood type cannot be null.", ()
-> PatientProfileUtil.convertBloodTypeToString(patientBloodType));
}
// EP 2 - Valid parameters
@Test
public void convertBloodTypeToString_validBloodTypeInput_correctResult() {
BloodType patientBloodType = new BloodType("A+");
Assertions.assertEquals("A+", PatientProfileUtil.convertBloodTypeToString(patientBloodType));
}
//-------------------- Tests for convertSexToString --------------------
// EP 1 - Null values
@Test
public void convertSexToString_nullSex_throwsNullPointerException() {
Sex patientSex = null;
Assert.assertThrows(NullPointerException.class, "Patient's sex cannot be null.", ()
-> PatientProfileUtil.convertSexToString(patientSex));
}
// EP 2 - Valid parameters
@Test
public void convertSexToString_validSexInput_correctResult() {
Sex patientSex = new Sex("F");
Assertions.assertEquals("F", PatientProfileUtil.convertSexToString(patientSex));
}
} |
Java | public class UserProfileHandler {
private static final String TYPE_GET_USER_PROFILE_DETAILS = "getUserProfileDetails";
private static final String TYPE_CREATE_PROFILE = "createProfile";
private static final String TYPE_GET_TENANT_INFO = "getTenantInfo";
private static final String TYPE_SEARCH_USER = "searchUser";
private static final String TYPE_GET_SKILLS = "getSkills";
private static final String TYPE_ENDORSE_OR_ADD_SKILL = "endorseOrAddSkill";
private static final String TYPE_SET_PROFILE_VISIBILITY = "setProfileVisibility";
private static final String TYPE_UPLOAD_FILE = "uploadFile";
private static final String TYPE_UPDATE_USER_INFO = "updateUserInfo";
private static final String TYPE_ACCEPT_TERMS_AND_CONDITIONS = "acceptTermsAndConditions";
public static void handle(JSONArray args, final CallbackContext callbackContext) {
try {
String type = args.getString(0);
if (type.equals(TYPE_GET_USER_PROFILE_DETAILS)) {
getUserProfileDetails(args, callbackContext);
} else if (type.equals(TYPE_GET_TENANT_INFO)) {
getTenantInfo(args, callbackContext);
} else if (type.equals(TYPE_SEARCH_USER)) {
searchUser(args, callbackContext);
} else if (type.equals(TYPE_GET_SKILLS)) {
getSkills(args, callbackContext);
} else if (type.equals(TYPE_ENDORSE_OR_ADD_SKILL)) {
endorseOrAddSkill(args, callbackContext);
} else if (type.equals(TYPE_SET_PROFILE_VISIBILITY)) {
setProfileVisibility(args, callbackContext);
} else if (type.equals(TYPE_UPLOAD_FILE)) {
uploadFile(args, callbackContext);
} else if (type.equalsIgnoreCase(TYPE_UPDATE_USER_INFO)) {
updateUserInfo(args, callbackContext);
} else if (type.equalsIgnoreCase(TYPE_ACCEPT_TERMS_AND_CONDITIONS)) {
acceptTermsAndConditions(args, callbackContext);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private static void updateUserInfo(JSONArray args, final CallbackContext callbackContext) throws JSONException {
String requestJson = args.getString(1);
UpdateUserInfoRequest.Builder request = GsonUtil.fromJson(requestJson, UpdateUserInfoRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().updateUserInfo(request.build(),
new IResponseHandler<Void>() {
@Override
public void onSuccess(GenieResponse<Void> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse));
}
@Override
public void onError(GenieResponse<Void> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse));
}
});
}
private static void getUserProfileDetails(JSONArray args, final CallbackContext callbackContext)
throws JSONException {
String requestJson = args.getString(1);
UserProfileDetailsRequest.Builder request = GsonUtil.fromJson(requestJson,
UserProfileDetailsRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().getUserProfileDetails(request.build(),
new IResponseHandler<UserProfile>() {
@Override
public void onSuccess(GenieResponse<UserProfile> genieResponse) {
String userProfile = genieResponse.getResult().getUserProfile();
try {
JSONObject jsonObject = new JSONObject(userProfile);
String channelId = jsonObject.getJSONObject("rootOrg").getString("hashTagId");
GenieService.getService().getKeyStore().putString("channelId", channelId);
SDKParams.setParams();
} catch (Exception e) {
e.printStackTrace();
}
callbackContext.success(userProfile);
}
@Override
public void onError(GenieResponse<UserProfile> genieResponse) {
callbackContext.error(genieResponse.getError());
}
});
}
/**
* get TenantInfo
*/
private static void getTenantInfo(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String requestJson = args.getString(1);
final Gson gson = new GsonBuilder().create();
TenantInfoRequest.Builder builder = gson.fromJson(requestJson, TenantInfoRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().getTenantInfo(builder.build(),
new IResponseHandler<TenantInfo>() {
@Override
public void onSuccess(GenieResponse<TenantInfo> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse.getResult()));
}
@Override
public void onError(GenieResponse<TenantInfo> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse.getError()));
}
});
}
/**
* searchUser
*/
private static void searchUser(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String requestJson = args.getString(1);
final Gson gson = new GsonBuilder().create();
UserSearchCriteria.SearchBuilder builder = gson.fromJson(requestJson, UserSearchCriteria.SearchBuilder.class);
GenieService.getAsyncService().getUserProfileService().searchUser(builder.build(),
new IResponseHandler<UserSearchResult>() {
@Override
public void onSuccess(GenieResponse<UserSearchResult> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse.getResult()));
}
@Override
public void onError(GenieResponse<UserSearchResult> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse.getError()));
}
});
}
/**
* getSkills
*/
private static void getSkills(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String requestJson = args.getString(1);
final Gson gson = new GsonBuilder().create();
UserProfileSkillsRequest.Builder builder = gson.fromJson(requestJson, UserProfileSkillsRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().getSkills(builder.build(),
new IResponseHandler<UserProfileSkill>() {
@Override
public void onSuccess(GenieResponse<UserProfileSkill> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse.getResult()));
}
@Override
public void onError(GenieResponse<UserProfileSkill> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse.getError()));
}
});
}
/**
* endorseOrAddSkill
*/
private static void endorseOrAddSkill(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String requestJson = args.getString(1);
final Gson gson = new GsonBuilder().create();
EndorseOrAddSkillRequest.Builder builder = gson.fromJson(requestJson, EndorseOrAddSkillRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().endorseOrAddSkill(builder.build(),
new IResponseHandler<Void>() {
@Override
public void onSuccess(GenieResponse<Void> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse));
}
@Override
public void onError(GenieResponse<Void> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse));
}
});
}
/**
* setProfileVisibility
*/
private static void setProfileVisibility(JSONArray args, final CallbackContext callbackContext)
throws JSONException {
final String requestJson = args.getString(1);
final Gson gson = new GsonBuilder().create();
ProfileVisibilityRequest.Builder builder = gson.fromJson(requestJson, ProfileVisibilityRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().setProfileVisibility(builder.build(),
new IResponseHandler<Void>() {
@Override
public void onSuccess(GenieResponse<Void> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse));
}
@Override
public void onError(GenieResponse<Void> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse));
}
});
}
/**
* uploadFile
*/
private static void uploadFile(JSONArray args, final CallbackContext callbackContext) throws JSONException {
final String requestJson = args.getString(1);
UploadFileRequest.Builder builder = GsonUtil.fromJson(requestJson, UploadFileRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().uploadFile(builder.build(),
new IResponseHandler<FileUploadResult>() {
@Override
public void onSuccess(GenieResponse<FileUploadResult> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse.getResult()));
}
@Override
public void onError(GenieResponse<FileUploadResult> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse.getError()));
}
});
}
/**
* acceptTermsAndConditions
*/
private static void acceptTermsAndConditions(JSONArray args, final CallbackContext callbackContext)
throws JSONException {
final String requestJson = args.getString(1);
AcceptTermsAndConditionsRequest.Builder builder = GsonUtil.fromJson(requestJson,
AcceptTermsAndConditionsRequest.Builder.class);
GenieService.getAsyncService().getUserProfileService().acceptTermsAndConditions(builder.build(),
new IResponseHandler<Void>() {
@Override
public void onSuccess(GenieResponse<Void> genieResponse) {
callbackContext.success(GsonUtil.toJson(genieResponse.getResult()));
}
@Override
public void onError(GenieResponse<Void> genieResponse) {
callbackContext.error(GsonUtil.toJson(genieResponse.getError()));
}
});
}
} |
Java | class NioServerSocketPipelineSink extends AbstractChannelSink {
static final InternalLogger logger =
InternalLoggerFactory.getInstance(NioServerSocketPipelineSink.class);
private final NioWorker[] workers;
private final AtomicInteger workerIndex = new AtomicInteger();
NioServerSocketPipelineSink(Executor workerExecutor, int workerCount) {
workers = new NioWorker[workerCount];
for (int i = 0; i < workers.length; i ++) {
workers[i] = new NioWorker(workerExecutor);
}
}
@Override
public void eventSunk(
ChannelPipeline pipeline, ChannelEvent e) throws Exception {
Channel channel = e.getChannel();
if (channel instanceof NioServerSocketChannel) {
handleServerSocket(e);
} else if (channel instanceof NioAcceptedSocketChannel) {
handleAcceptedSocket(e);
}
}
private void handleServerSocket(ChannelEvent e) {
if (!(e instanceof ChannelStateEvent)) {
return;
}
ChannelStateEvent event = (ChannelStateEvent) e;
NioServerSocketChannel channel =
(NioServerSocketChannel) event.getChannel();
ChannelFuture future = event.getFuture();
ChannelState state = event.getState();
Object value = event.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
close(channel, future);
}
break;
case BOUND:
if (value != null) {
bind(channel, future, (SocketAddress) value);
} else {
close(channel, future);
}
break;
}
}
private void handleAcceptedSocket(ChannelEvent e) {
if (e instanceof ChannelStateEvent) {
ChannelStateEvent event = (ChannelStateEvent) e;
NioAcceptedSocketChannel channel = (NioAcceptedSocketChannel) event.getChannel();
ChannelFuture future = event.getFuture();
ChannelState state = event.getState();
Object value = event.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
channel.worker.close(channel, future);
}
break;
case BOUND:
case CONNECTED:
if (value == null) {
channel.worker.close(channel, future);
}
break;
case INTEREST_OPS:
channel.worker.setInterestOps(channel, future, ((Integer) value).intValue());
break;
}
} else if (e instanceof MessageEvent) {
MessageEvent event = (MessageEvent) e;
NioAcceptedSocketChannel channel = (NioAcceptedSocketChannel) event.getChannel();
boolean offered = channel.writeBuffer.offer(event);
assert offered;
channel.worker.writeFromUserCode(channel);
}
}
private void bind(
NioServerSocketChannel channel, ChannelFuture future,
SocketAddress localAddress) {
boolean bound = false;
boolean bossStarted = false;
try {
channel.socket.socket().bind(localAddress, channel.getConfig().getBacklog());
bound = true;
future.setSuccess();
fireChannelBound(channel, channel.getLocalAddress());
Executor bossExecutor =
((NioServerSocketChannelFactory) channel.getFactory()).bossExecutor;
DeadLockProofWorker.start(bossExecutor, new Boss(channel));
bossStarted = true;
} catch (Throwable t) {
future.setFailure(t);
fireExceptionCaught(channel, t);
} finally {
if (!bossStarted && bound) {
close(channel, future);
}
}
}
private void close(NioServerSocketChannel channel, ChannelFuture future) {
boolean bound = channel.isBound();
try {
if (channel.socket.isOpen()) {
channel.socket.close();
Selector selector = channel.selector;
if (selector != null) {
selector.wakeup();
}
}
// Make sure the boss thread is not running so that that the future
// is notified after a new connection cannot be accepted anymore.
// See NETTY-256 for more information.
channel.shutdownLock.lock();
try {
if (channel.setClosed()) {
future.setSuccess();
if (bound) {
fireChannelUnbound(channel);
}
fireChannelClosed(channel);
} else {
future.setSuccess();
}
} finally {
channel.shutdownLock.unlock();
}
} catch (Throwable t) {
future.setFailure(t);
fireExceptionCaught(channel, t);
}
}
NioWorker nextWorker() {
return workers[Math.abs(
workerIndex.getAndIncrement() % workers.length)];
}
private final class Boss implements Runnable {
private final Selector selector;
private final NioServerSocketChannel channel;
Boss(NioServerSocketChannel channel) throws IOException {
this.channel = channel;
selector = Selector.open();
boolean registered = false;
try {
channel.socket.register(selector, SelectionKey.OP_ACCEPT);
registered = true;
} finally {
if (!registered) {
closeSelector();
}
}
channel.selector = selector;
}
@Override
public void run() {
final Thread currentThread = Thread.currentThread();
channel.shutdownLock.lock();
try {
for (;;) {
try {
if (selector.select(1000) > 0) {
selector.selectedKeys().clear();
}
SocketChannel acceptedSocket = channel.socket.accept();
if (acceptedSocket != null) {
registerAcceptedChannel(acceptedSocket, currentThread);
}
} catch (SocketTimeoutException e) {
// Thrown every second to get ClosedChannelException
// raised.
} catch (CancelledKeyException e) {
// Raised by accept() when the server socket was closed.
} catch (ClosedSelectorException e) {
// Raised by accept() when the server socket was closed.
} catch (ClosedChannelException e) {
// Closed as requested.
break;
} catch (Throwable e) {
logger.warn(
"Failed to accept a connection.", e);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// Ignore
}
}
}
} finally {
channel.shutdownLock.unlock();
closeSelector();
}
}
private void registerAcceptedChannel(SocketChannel acceptedSocket, Thread currentThread) {
try {
ChannelPipeline pipeline =
channel.getConfig().getPipelineFactory().getPipeline();
NioWorker worker = nextWorker();
worker.register(new NioAcceptedSocketChannel(
channel.getFactory(), pipeline, channel,
NioServerSocketPipelineSink.this, acceptedSocket,
worker, currentThread));
} catch (Exception e) {
logger.warn(
"Failed to initialize an accepted socket.", e);
try {
acceptedSocket.close();
} catch (IOException e2) {
logger.warn(
"Failed to close a partially accepted socket.",
e2);
}
}
}
private void closeSelector() {
channel.selector = null;
try {
selector.close();
} catch (Exception e) {
logger.warn("Failed to close a selector.", e);
}
}
}
} |
Java | @ConvertAsProperties(
dtd = "-//org.cobi.kgg.ui.dialog//ShowGeneResult//EN",
autostore = false)
@TopComponent.Description(
preferredID = "ShowGeneResultTopComponent",
iconBase = "org/cobi/kgg/ui/png/16x16/Eye.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Gene", id = "org.cobi.kgg.ui.dialog.ShowGeneResultTopComponent")
@ActionReference(path = "Menu/Gene", position = 333)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_ShowGeneResultAction",
preferredID = "ShowGeneResultTopComponent")
@Messages({
"CTL_ShowGeneResultAction=View Genes",
"CTL_ShowGeneResultTopComponent=View Genes",
"HINT_ShowGeneResultTopComponent=This is a ShowResult window"
})
public final class ShowGeneResultTopComponent extends TopComponent implements LookupListener, Constants, ChartMouseListener {
private final static Logger LOG = Logger.getLogger(ShowGeneResultTopComponent.class.getName());
private String name;
private List<PValueGene> pValueGeneList;
private Lookup.Result<GeneBasedAssociation> result = null;
private String[] strGeneTerm = {"Symbol", "NominalP", "CorrectedP", "Chromosome", "Start_Position", "Group"};
private final String[] strSNPTerm = {"SNP", "Gene_Feature", "P"};
private final String[] strOutput = {"Symbol", "PValue", "IsSignificant", "Chromosome", "Start_Position", "SNP", "Gene_Feature", "P"};
ArrayListStringArrayTableModel aomGeneTermModel = null;
ArrayListStringArrayTableModel aomSNPTermModel = null;
List<String[]> lstGeneTerm = null;
List<String[]> lstSNPTerm = null;
//List<Gene> altGeneSet = new ArrayList();
DoubleArrayList dalPValues = new DoubleArrayList();
CorrelationBasedByteLDSparseMatrix ldRsMatrix = null;
GeneBasedAssociation event = null;
Genome gmeTerm = null;
Map<String, int[]> mapG2C = null;
Chromosome[] chrTerms = null;
ChartPanel cplCanvas = null;
double[][] dblData2D = null;
double[][] dblData = null;
LiftOver liftOver = null;
Gene gneTerm;
boolean boolTest = false;
Map<String, Gene> mapSymbol2Gene = null;
private final static RequestProcessor RP = new RequestProcessor("Loading analysis genome tas", 1, true);
private RequestProcessor.Task theTask = null;
public ShowGeneResultTopComponent() {
lstGeneTerm = new ArrayList<String[]>();
aomGeneTermModel = new ArrayListStringArrayTableModel();
aomGeneTermModel.setTitle(strGeneTerm);
aomGeneTermModel.setDataList(lstGeneTerm);
lstSNPTerm = new ArrayList<String[]>();
aomSNPTermModel = new ArrayListStringArrayTableModel();
aomSNPTermModel.setTitle(strSNPTerm);
//aomSNPTermModel.setDataList(lstSNPTerm);
mapSymbol2Gene = new HashMap<String, Gene>();
initComponents();
setName(Bundle.CTL_ShowGeneResultTopComponent());
setToolTipText(Bundle.HINT_ShowGeneResultTopComponent());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
jPanel3 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jScrollPane2 = new javax.swing.JScrollPane();
jTable2 = new javax.swing.JTable();
jPanel5 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
formatComboBox = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
contentComboBox = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
genePValueCutTextField = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
variantPValueCutTextField = new javax.swing.JTextField();
jPanel4 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
multiMethodComboBox = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jTextField2 = new javax.swing.JTextField();
jButton2 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jScrollPane3 = new javax.swing.JScrollPane();
jTextPane1 = new javax.swing.JTextPane();
jButton3 = new javax.swing.JButton();
jSplitPane1.setDividerLocation(286);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jPanel1.border.title"))); // NOI18N
jPanel1.setToolTipText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jPanel1.toolTipText")); // NOI18N
jPanel1.setPreferredSize(new java.awt.Dimension(979, 250));
jPanel1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
jPanel1MouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
jPanel1MouseExited(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 953, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 0, Short.MAX_VALUE)
);
jSplitPane1.setBottomComponent(jPanel1);
jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jScrollPane1.border.title"))); // NOI18N
jTable1.setModel(aomGeneTermModel);
jTable1.setToolTipText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jTable1.toolTipText")); // NOI18N
jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jScrollPane2.border.title"))); // NOI18N
jTable2.setAutoCreateRowSorter(true);
jTable2.setModel(aomSNPTermModel);
jTable2.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
jScrollPane2.setViewportView(jTable2);
jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jPanel2.border.title"))); // NOI18N
formatComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Excel(.xlsx)", "Excel(.xls)", "Text(.txt)" }));
org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel2.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel5, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel5.text")); // NOI18N
contentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Variants inside genes", "Only genes", "All variants + genes" }));
contentComboBox.setToolTipText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.contentComboBox.toolTipText")); // NOI18N
contentComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
contentComboBoxActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(jButton1, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jButton1.text")); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.openide.awt.Mnemonics.setLocalizedText(jLabel6, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel6.text")); // NOI18N
genePValueCutTextField.setText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.genePValueCutTextField.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel7, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel7.text")); // NOI18N
variantPValueCutTextField.setText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.variantPValueCutTextField.text")); // NOI18N
javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(formatComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addComponent(genePValueCutTextField))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(variantPValueCutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(contentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 38, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(contentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(formatComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2)
.addComponent(jButton1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(genePValueCutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(variantPValueCutTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jPanel4.border.title"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel3.text")); // NOI18N
jLabel3.setToolTipText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel3.toolTipText")); // NOI18N
multiMethodComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Benjamini & Hochberg (1995)", "Benjamini & Yekutieli (2001)", "Standard Bonferroni" }));
org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel4.text")); // NOI18N
jLabel4.setToolTipText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel4.toolTipText")); // NOI18N
jTextField2.setText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jTextField2.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jButton2, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jButton2.text")); // NOI18N
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
jPanel4.setLayout(jPanel4Layout);
jPanel4Layout.setHorizontalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(43, 43, 43)
.addComponent(jButton2))
.addComponent(multiMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
jPanel4Layout.setVerticalGroup(
jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel4Layout.createSequentialGroup()
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(multiMethodComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING))
.addContainerGap())
);
jLabel3.getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel3.AccessibleContext.accessibleName")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jLabel1.text")); // NOI18N
jTextPane1.setText(org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jTextPane1.text")); // NOI18N
jScrollPane3.setViewportView(jTextPane1);
org.openide.awt.Mnemonics.setLocalizedText(jButton3, org.openide.util.NbBundle.getMessage(ShowGeneResultTopComponent.class, "ShowGeneResultTopComponent.jButton3.text")); // NOI18N
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jButton3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane3))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3))
.addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 445, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addContainerGap())
);
jSplitPane1.setLeftComponent(jPanel3);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 967, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 620, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// TODO add your handling code here:
int intRow = jTable1.getSelectedRow();
if (intRow < 0) {
return;
}
if (evt.getClickCount() == 1) {
showSNPsofGene(intRow);
} else {
String strTarget = (String) jTable1.getValueAt(intRow, 0);
URLOpener.openURL("http://www.genecards.org/cgi-bin/carddisp.pl?gene=" + strTarget);
}
}//GEN-LAST:event_jTable1MouseClicked
private void showSNPsofGene(int intRow) {
if (jTable1.getRowCount() <= 0) {
String infor = "The selected gene has no SNP!";
JOptionPane.showMessageDialog(this, infor, "Warnning", JOptionPane.WARNING_MESSAGE);
return;
}
String pStr = (String) jTable1.getValueAt(intRow, 1);
Double dblPValue = null;
if (!pStr.equals("NA") && !pStr.equals("NaN")) {
dblPValue = Double.valueOf(pStr);
}
String strTarget = (String) jTable1.getValueAt(intRow, 0);
String chrom = (String) jTable1.getValueAt(intRow, 3);
lstSNPTerm.clear();
gneTerm = mapSymbol2Gene.get(strTarget);
//gneTerm = altGeneSet.get(intRow);
try {
int intVary = 0;
Iterator<SNP> itrSNP = gneTerm.snps.iterator();
String[] names = gmeTerm.getpValueNames();
List<String> vfns = gmeTerm.getVariantFeatureNames();
String[] strVFNS = vfns.toArray(new String[vfns.size()]);
int offSetValue = 3;
Map<String, Double> tastPValues = event.loadTASTESNPPValuesfromDisk("TASTE");
boolean hasMultipleTraits = false;
if (tastPValues != null) {
hasMultipleTraits = true;
offSetValue++;
}
while (itrSNP.hasNext()) {
SNP snpTerm = itrSNP.next();
String[] strConst = null;
if (hasMultipleTraits) {
Double tp = tastPValues.get(chrom + ":" + snpTerm.getPhysicalPosition());
strConst = new String[]{snpTerm.getRsID(), String.valueOf(snpTerm.getPhysicalPosition()), VAR_FEATURE_NAMES[snpTerm.getGeneFeature()], String.valueOf(tp)};
} else {
strConst = new String[]{snpTerm.getRsID(), String.valueOf(snpTerm.getPhysicalPosition()), VAR_FEATURE_NAMES[snpTerm.getGeneFeature()]};
}
String[] strVary = Util.formatePValues(snpTerm.getpValues());
String[] strRow = new String[strConst.length + strVary.length + strVFNS.length];
System.arraycopy(strConst, 0, strRow, 0, strConst.length);
System.arraycopy(strVary, 0, strRow, strConst.length, strVary.length);
if (!vfns.isEmpty()) {
DoubleArrayList dalVF = snpTerm.getAFeatureValue();
double[] dblVF = dalVF.elements();
String[] strVF = new String[dblVF.length];
for (int i = 0; i < dblVF.length; i++) {
strVF[i] = String.valueOf(dblVF[i]);
}
System.arraycopy(strVF, 0, strRow, strConst.length + strVary.length, strVF.length);
}
// if(Double.valueOf(strRow[2])<=Double.valueOf(variantPValueCutTextField.getText()))
lstSNPTerm.add(strRow);
}
intVary = names.length + strVFNS.length;
String[] strTitles = new String[intVary + offSetValue];
strTitles[0] = "SNP";
strTitles[1] = "Position";
strTitles[2] = "Gene_Feature";
if (hasMultipleTraits) {
strTitles[3] = "TATES_P";
}
if (lstSNPTerm.isEmpty()) {
String strNULL[] = new String[intVary + offSetValue];
for (int i = 0; i < intVary + offSetValue; i++) {
strNULL[i] = "null";
}
lstSNPTerm.add(strNULL);
}
System.arraycopy(names, 0, strTitles, offSetValue, names.length);
if (!vfns.isEmpty()) {
System.arraycopy(strVFNS, 0, strTitles, names.length + offSetValue, strVFNS.length);
}
aomSNPTermModel.setTitle(strTitles);
aomSNPTermModel.setDataList(lstSNPTerm);
aomSNPTermModel.fireTableStructureChanged();
aomSNPTermModel.fireTableDataChanged();
ShowSNPChart sscPlot = null;
int[] posIndex = mapG2C.get(gneTerm.getSymbol());
if (gmeTerm.getLdSourceCode() == -2) {
ldRsMatrix = GlobalManager.currentProject.getGenomeByName(gmeTerm.getSameLDGenome()).readChromosomeLDfromDisk(posIndex[0]);
} else {
ldRsMatrix = gmeTerm.readChromosomeLDfromDisk(posIndex[0]);
}
sscPlot = new ShowSNPChart(gneTerm, ldRsMatrix, dblPValue);
JFreeChart jfcPlot = sscPlot.getChart();
cplCanvas = new ChartPanel(jfcPlot);
cplCanvas.addChartMouseListener(this);
jPanel1.removeAll();
jPanel1.setLayout(new java.awt.BorderLayout());
jPanel1.add(cplCanvas, BorderLayout.CENTER);
jPanel1.validate();
dblData2D = new double[2][gneTerm.snps.size()];
dblData = sscPlot.getData();
boolTest = false;
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}
private void jPanel1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseEntered
// TODO add your handling code here:
jPanel1.setCursor(new Cursor(Cursor.HAND_CURSOR));
}//GEN-LAST:event_jPanel1MouseEntered
private void jPanel1MouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPanel1MouseExited
// TODO add your handling code here:
jPanel1.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}//GEN-LAST:event_jPanel1MouseExited
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
String strPValueInfo = multiMethodComboBox.getSelectedItem().toString();
String strContent = contentComboBox.getSelectedItem().toString();
String strFormat = formatComboBox.getSelectedItem().toString();
String strErrorRate = jTextField2.getText();
double genePCutOff = Double.parseDouble(genePValueCutTextField.getText());
double snpPCutOff = Double.parseDouble(variantPValueCutTextField.getText());
double geneP = 1;
boolean noPass = false;
int snpFeatureNum = gmeTerm.getVariantFeatureNames().size();
int pNum = gmeTerm.getpValueNames().length;
List<String[]> lstOutput = new ArrayList();
List<String[]> lstOutput2 = new ArrayList();
if (pValueGeneList == null) {
return;
}
try {
int geneNum = pValueGeneList.size();
Map<String, IntArrayList> geneKeySNPPostMap = new HashMap<String, IntArrayList>();
for (int i = 0; i < geneNum; i++) {
PValueGene pvalueGene = pValueGeneList.get(i);
if (pvalueGene.pValue <= genePCutOff) {
pvalueGene.keySNPPositions.quickSort();
geneKeySNPPostMap.put(pvalueGene.getSymbol(), pvalueGene.keySNPPositions);
}
}
Map<String, Double> tastPValues = event.loadTASTESNPPValuesfromDisk("TASTE");
int tastNum = 0;
boolean hasMultipleTraits = false;
if (tastPValues != null) {
hasMultipleTraits = true;
tastNum = 1;
}
SNPPValueIndexComparator snpPVCompar = new SNPPValueIndexComparator(0);
int keySNPIndex = 0;
if (contentComboBox.getSelectedIndex() == 0) {
List<String[]> lstCurrentGene = aomGeneTermModel.getDataList();
for (String[] strGenes : lstCurrentGene) {
gneTerm = mapSymbol2Gene.get(strGenes[0]);
if (!strGenes[1].equals("NA")) {
geneP = Double.parseDouble(strGenes[1]);
if (geneP > genePCutOff) {
continue;
}
}
String chrom = strGenes[3];
Collections.sort(gneTerm.snps, snpPVCompar);
Iterator<SNP> itrSNP = gneTerm.snps.iterator();
int snpNum = 0;
IntArrayList keySNPPoss = geneKeySNPPostMap.get(strGenes[0]);
while (itrSNP.hasNext()) {
SNP snpTerm = itrSNP.next();
String[] strSub = new String[snpFeatureNum + 4 + tastNum + pNum];
strSub[0] = snpTerm.getRsID();
strSub[1] = String.valueOf(snpTerm.getPhysicalPosition());
strSub[2] = VAR_FEATURE_NAMES[snpTerm.getGeneFeature()];
if (hasMultipleTraits) {
Double tp = tastPValues.get(chrom + ":" + snpTerm.getPhysicalPosition());
strSub[3] = String.valueOf(tp);
}
if (keySNPPoss != null) {
keySNPIndex = keySNPPoss.binarySearch(snpTerm.physicalPosition);
if (keySNPIndex >= 0) {
strSub[3 + tastNum] = "Y";
} else {
strSub[3 + tastNum] = "N";
}
} else {
strSub[3 + tastNum] = "-";
}
DoubleArrayList values = snpTerm.getAFeatureValue();// Has the function of outputing variant feature been finished?
for (int t = 0; t < snpFeatureNum; t++) {
strSub[t + 4 + tastNum] = String.valueOf(values.getQuick(t));
}
// strSub[snpFeatureNum + 2] = String.valueOf(snpTerm.getpValues()[0]);
noPass = true;
for (int t = 0; t < pNum; t++) {
if (snpPCutOff > snpTerm.getpValues()[t]) {
noPass = false;
}
strSub[snpFeatureNum + 4 + tastNum + t] = String.valueOf(snpTerm.getpValues()[t]);
}
if (noPass) {
continue;
}
String[] strRow = new String[strGenes.length + strSub.length];
if (snpNum == 0) {
System.arraycopy(strGenes, 0, strRow, 0, strGenes.length);
System.arraycopy(strSub, 0, strRow, strGenes.length, strSub.length);
} else {
System.arraycopy(strSub, 0, strRow, strGenes.length, strSub.length);
}
snpNum++;
lstOutput.add(strRow);
}
}
String[] strTitle = new String[strGeneTerm.length + snpFeatureNum + 4 + tastNum + pNum];
System.arraycopy(strGeneTerm, 0, strTitle, 0, strGeneTerm.length);
System.arraycopy(gmeTerm.getpValueNames(), 0, strTitle, snpFeatureNum + 4 + tastNum + strGeneTerm.length, pNum);
List<String> vfns = gmeTerm.getVariantFeatureNames();
String[] strVFNS = vfns.toArray(new String[vfns.size()]);
strTitle[strGeneTerm.length] = "SNP";
strTitle[strGeneTerm.length + 1] = "Position";
strTitle[strGeneTerm.length + 2] = "GeneFeature";
if (hasMultipleTraits) {
strTitle[strGeneTerm.length + 3] = "TATES_P";
}
strTitle[strGeneTerm.length + 3 + tastNum] = "IsGATESKeySNP";
System.arraycopy(strVFNS, 0, strTitle, strGeneTerm.length + 4 + tastNum, strVFNS.length);
lstOutput.add(0, strTitle);
} else if (contentComboBox.getSelectedIndex() == 1) {
lstOutput.add(strGeneTerm);
lstOutput.addAll(aomGeneTermModel.getDataList());
} else {
List<String[]> lstCurrentGene = aomGeneTermModel.getDataList();
int snpNum = 0;
for (String[] strGenes : lstCurrentGene) {
gneTerm = mapSymbol2Gene.get(strGenes[0]);
if (!strGenes[1].equals("NA")) {
geneP = Double.parseDouble(strGenes[1]);
if (geneP > genePCutOff) {
continue;
}
}
String chrom = strGenes[3];
Collections.sort(gneTerm.snps, snpPVCompar);
Iterator<SNP> itrSNP = gneTerm.snps.iterator();
snpNum = 0;
IntArrayList keySNPPoss = geneKeySNPPostMap.get(strGenes[0]);
while (itrSNP.hasNext()) {
SNP snpTerm = itrSNP.next();
String[] strSub = new String[snpFeatureNum + 4 + tastNum + pNum];
strSub[0] = snpTerm.getRsID();
strSub[1] = String.valueOf(snpTerm.getPhysicalPosition());
strSub[2] = VAR_FEATURE_NAMES[snpTerm.getGeneFeature()];
if (hasMultipleTraits) {
Double tp = tastPValues.get(chrom + ":" + snpTerm.getPhysicalPosition());
strSub[3] = String.valueOf(tp);
}
if (keySNPPoss != null) {
keySNPIndex = keySNPPoss.binarySearch(snpTerm.physicalPosition);
if (keySNPIndex >= 0) {
strSub[3 + tastNum] = "Y";
} else {
strSub[3 + tastNum] = "N";
}
} else {
strSub[3 + tastNum] = "-";
}
DoubleArrayList values = snpTerm.getAFeatureValue();// Has the function of outputing variant feature been finished?
for (int t = 0; t < snpFeatureNum; t++) {
strSub[t + tastNum + 4] = String.valueOf(values.getQuick(t));
}
// strSub[snpFeatureNum + 2] = String.valueOf(snpTerm.getpValues()[0]);
noPass = true;
for (int t = 0; t < pNum; t++) {
if (snpPCutOff > snpTerm.getpValues()[t]) {
noPass = false;
}
strSub[snpFeatureNum + 4 + tastNum + t] = String.valueOf(snpTerm.getpValues()[t]);
}
if (noPass) {
continue;
}
String[] strRow = new String[strGenes.length + strSub.length];
if (snpNum == 0) {
System.arraycopy(strGenes, 0, strRow, 0, strGenes.length);
System.arraycopy(strSub, 0, strRow, strGenes.length, strSub.length);
} else {
System.arraycopy(strSub, 0, strRow, strGenes.length, strSub.length);
}
snpNum++;
lstOutput.add(strRow);
}
}
String[] strTitle = new String[strGeneTerm.length + snpFeatureNum + 4 + tastNum + pNum];
System.arraycopy(strGeneTerm, 0, strTitle, 0, strGeneTerm.length);
System.arraycopy(gmeTerm.getpValueNames(), 0, strTitle, snpFeatureNum + 4 + tastNum + strGeneTerm.length, pNum);
List<String> vfns = gmeTerm.getVariantFeatureNames();
String[] strVFNS = vfns.toArray(new String[vfns.size()]);
strTitle[strGeneTerm.length] = "SNP";
strTitle[strGeneTerm.length + 1] = "Position";
strTitle[strGeneTerm.length + 2] = "GeneFeature";
if (hasMultipleTraits) {
strTitle[strGeneTerm.length + 3] = "TASTE_P";
}
strTitle[strGeneTerm.length + 3 + tastNum] = "IsGATESKeySNP";
System.arraycopy(strVFNS, 0, strTitle, strGeneTerm.length + 4 + tastNum, strVFNS.length);
lstOutput.add(0, strTitle);
for (Chromosome chrTerm : chrTerms) {
if (null == chrTerm) {
continue;
}
List lstSNP = chrTerm.snpsOutGenes;
Iterator<SNP> itrSNP = lstSNP.iterator();
while (itrSNP.hasNext()) {
SNP snpTerm = itrSNP.next();
String[] strSub = new String[snpFeatureNum + 3 + pNum];
strSub[0] = snpTerm.getRsID();
strSub[1] = String.valueOf(snpTerm.getPhysicalPosition());
strSub[2] = VAR_FEATURE_NAMES[snpTerm.getGeneFeature()];
DoubleArrayList values = snpTerm.getAFeatureValue();// Has the function of outputing variant feature been finished?
for (int t = 0; t < snpFeatureNum; t++) {
strSub[t + 3] = String.valueOf(values.getQuick(t));
}
noPass = true;
for (int t = 0; t < pNum; t++) {
if (snpPCutOff > snpTerm.getpValues()[t]) {
noPass = false;
}
strSub[snpFeatureNum + 3 + t] = String.valueOf(snpTerm.getpValues()[t]);
}
if (noPass) {
continue;
}
lstOutput2.add(strSub);
}
}
strTitle = new String[snpFeatureNum + 3 + pNum];
System.arraycopy(gmeTerm.getpValueNames(), 0, strTitle, snpFeatureNum + 3, pNum);
vfns = gmeTerm.getVariantFeatureNames();
strVFNS = vfns.toArray(new String[vfns.size()]);
strTitle[0] = "SNP";
strTitle[1] = "Position";
strTitle[2] = "GeneFeature";
System.arraycopy(strVFNS, 0, strTitle, 3, strVFNS.length);
lstOutput2.add(0, strTitle);
}//Add title!!!!
JFileChooser jfcSave = null;
if ((GlobalManager.lastAccessedPath != null) && (GlobalManager.lastAccessedPath.trim().length() > 0)) {
jfcSave = new JFileChooser(GlobalManager.lastAccessedPath);
} else {
jfcSave = new JFileChooser();
}
jfcSave.setDialogTitle("Save " + strContent);
FileNameExtensionFilter fnefFilter = null;
if (formatComboBox.getSelectedIndex() == 0) {
fnefFilter = new FileNameExtensionFilter("*.xlsx", "xlsx");
} else if (formatComboBox.getSelectedIndex() == 1) {
fnefFilter = new FileNameExtensionFilter("*.xls", "xls");
} else {
fnefFilter = new FileNameExtensionFilter("*.txt", "txt");
}
jfcSave.setFileFilter(fnefFilter);
int intResult = jfcSave.showSaveDialog(this);
if (intResult == JFileChooser.APPROVE_OPTION) {
File fleFile = jfcSave.getSelectedFile();
if (formatComboBox.getSelectedIndex() == 0) {
if (!fleFile.getPath().endsWith("xlsx")) {
fleFile = new File(fleFile.getPath() + ".xlsx");
}
if (contentComboBox.getSelectedIndex() == 0) {
LocalExcelFile.WriteArray2XLSXFile(fleFile.getCanonicalPath(), null, lstOutput);
} else if (contentComboBox.getSelectedIndex() == 1) {
LocalExcelFile.WriteArray2XLSXFile(fleFile.getCanonicalPath(), null, lstOutput);
} else {
LocalExcelFile.WriteArray2XLSXFile(fleFile.getCanonicalPath(), null, lstOutput, lstOutput2);
}
} else if (formatComboBox.getSelectedIndex() == 1) {
if (!fleFile.getPath().endsWith("xls")) {
fleFile = new File(fleFile.getPath() + ".xls");
}
if (contentComboBox.getSelectedIndex() == 0) {
LocalExcelFile.writeArray2ExcelFile(fleFile.getCanonicalPath(), null, lstOutput);
} else if (contentComboBox.getSelectedIndex() == 1) {
LocalExcelFile.writeArray2ExcelFile(fleFile.getCanonicalPath(), null, lstOutput);
} else {
LocalExcelFile.writeArray2ExcelFile(fleFile.getCanonicalPath(), null, lstOutput, lstOutput2);
}
} else {
if (!fleFile.getPath().endsWith("txt")) {
fleFile = new File(fleFile.getPath() + ".txt");
}
if (contentComboBox.getSelectedIndex() == 0) {
LocalFile.writeData(fleFile.getCanonicalPath(), lstOutput, "\t", false);
} else if (contentComboBox.getSelectedIndex() == 1) {
LocalFile.writeData(fleFile.getCanonicalPath(), lstOutput, "\t", false);
} else {
LocalFile.writeData(fleFile.getCanonicalPath(), lstOutput, lstOutput2, "\t", false);
}
}
String info = "The output are stored in " + fleFile.getCanonicalPath();
NotifyDescriptor nd = new NotifyDescriptor.Message(info, NotifyDescriptor.INFORMATION_MESSAGE);
DialogDisplayer.getDefault().notifyLater(nd);
StatusDisplayer.getDefault().setStatusText(info);
}
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}//GEN-LAST:event_jButton1ActionPerformed
private void contentComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_contentComboBoxActionPerformed
// TODO add your handling code here:
contentComboBox.hidePopup();
}//GEN-LAST:event_contentComboBoxActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
try {
// TODO add your handling code here:
int intFlag = multiMethodComboBox.getSelectedIndex();
double dblER = Double.valueOf(jTextField2.getText());
//List<String[]> lstCurrentGene = aomGeneTermModel.getDataList();
//List<String[]> lstCurrentGene=lstGeneTerm;
DoubleArrayList dalPVs = new DoubleArrayList();
for (String[] strTerm : lstGeneTerm) {
if (strTerm[1].equals("NA")) {
continue;
}
dalPVs.add(Double.valueOf(strTerm[1]));
}
DoubleArrayList adjustedP = new DoubleArrayList();
double dblCutoff = 0;
switch (intFlag) {
case 0:
dblCutoff = MultipleTestingMethod.BenjaminiHochbergFDR("Genes", dblER, dalPVs, adjustedP);
break;
case 1:
dblCutoff = MultipleTestingMethod.BenjaminiYekutieliFDR("Genes", dblER, dalPVs, adjustedP);
break;
case 2:
dblCutoff = dblER / dalPVs.size();
MultipleTestingMethod.logInfo("Genes", "Standard Bonferron", dblCutoff);
break;
}
int sigGeneNum = 0;
int i = 0;
double p;
for (String[] strTerm : lstGeneTerm) {
if (strTerm[1].equals("NA")) {
continue;
}
p = Double.valueOf(strTerm[1]);
boolean boolSignificant = p <= dblCutoff;
if (boolSignificant) {
sigGeneNum++;
}
switch (intFlag) {
case 0:
case 1:
strTerm[2] = String.valueOf(adjustedP.getQuick(i));
break;
case 2:
p = p * dalPVs.size();
strTerm[2] = String.valueOf(p > 1 ? 1 : p);
break;
default:
strTerm[2] = "-";
}
i++;
}
Logger logOutput = Logger.getRootLogger();
String strOutput1 = sigGeneNum + " genes pass the threshold!\n";
logOutput.info(strOutput1);
if (GlobalManager.aotcWindow != null) {
GlobalManager.aotcWindow.insertMessage(strOutput1);
}
aomGeneTermModel.fireTableDataChanged();
} catch (Exception ex) {
Exceptions.printStackTrace(ex);
}
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
String strText = jTextPane1.getText();
StringTokenizer st = new StringTokenizer(strText);
Set<String> strElements = new HashSet<String>();
while (st.hasMoreTokens()) {
strElements.add(st.nextToken().trim());
}
List<String[]> lstGeneSearchTerm = new ArrayList();
List<Integer> lstIndex = new ArrayList();
for (String strElement : strElements) {
for (int j = 0; j < lstGeneTerm.size(); j++) {
if (strElement.equals(lstGeneTerm.get(j)[0])) {
lstIndex.add(j);
break;
}
}
}
Collections.sort(lstIndex);
for (Integer lstIndex1 : lstIndex) {
lstGeneSearchTerm.add(lstGeneTerm.get(lstIndex1));
}
aomGeneTermModel.setDataList(lstGeneSearchTerm);
aomGeneTermModel.fireTableDataChanged();
if (lstGeneTerm.size() > 0) {
showSNPsofGene(0);
} else {
lstSNPTerm.clear();
aomSNPTermModel.setDataList(lstSNPTerm);
aomSNPTermModel.fireTableDataChanged();
}
}//GEN-LAST:event_jButton3ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox contentComboBox;
private javax.swing.JComboBox formatComboBox;
private javax.swing.JTextField genePValueCutTextField;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JTable jTable1;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextPane jTextPane1;
private javax.swing.JComboBox multiMethodComboBox;
private javax.swing.JTextField variantPValueCutTextField;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
// TODO add custom code on component opening
result = Utilities.actionsGlobalContext().lookupResult(GeneBasedAssociation.class);
result.addLookupListener(this);
}
@Override
public void componentClosed() {
// TODO add custom code on component closing
result.removeLookupListener(this);
result = null;
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
private boolean handleCancel() {
if (null == theTask) {
return false;
}
return theTask.cancel();
}
class LoadGenomeDataSwingWorker extends SwingWorker<Void, String> {
GeneBasedAssociation event;
boolean succeed = false;
ProgressHandle ph = ProgressHandleFactory.createHandle("Loading analysis genome task", new Cancellable() {
@Override
public boolean cancel() {
return handleCancel();
}
});
public LoadGenomeDataSwingWorker(GeneBasedAssociation event) {
this.event = event;
}
@Override
protected Void doInBackground() {
try {
ph.start(); //we must start the PH before we swith to determinate
ph.switchToIndeterminate();
GlobalManager.isLoadingGenome = true;
publish("Loading analysis genomes.... Please wait for a while!");
List<String> varWeighNames = new ArrayList<String>();
if (event.isMultVariateTest()) {
pValueGeneList = event.loadGenePValuesfromDisk("MulVar", null);
} else {
pValueGeneList = event.loadGenePValuesfromDisk(event.getPValueSources().get(0), varWeighNames);
}
Collections.sort(pValueGeneList, new PValueGeneComparator());
Iterator<PValueGene> itrTerm = pValueGeneList.iterator();
gmeTerm = event.getGenome();
mapG2C = gmeTerm.loadGeneGenomeIndexes2Buf();
chrTerms = gmeTerm.loadAllChromosomes2Buf();
int intNo = 0;
//altGeneSet.clear();
lstGeneTerm.clear();
dalPValues.clear();
mapSymbol2Gene.clear();
String strRows[][] = new String[pValueGeneList.size()][];
//Start with the second chrom
int weightNum = varWeighNames.size() - 2;
if (weightNum > 0) {
String[] newTitle = new String[6];
System.arraycopy(strGeneTerm, 0, newTitle, 0, newTitle.length);
strGeneTerm = new String[newTitle.length + weightNum];
System.arraycopy(newTitle, 0, strGeneTerm, 0, newTitle.length);
for (int i = 0; i < weightNum; i++) {
strGeneTerm[6 + i] = varWeighNames.get(i + 2);
}
aomGeneTermModel.setTitle(strGeneTerm);
}
while (itrTerm.hasNext()) {
PValueGene pvgTerm = itrTerm.next();
String strSymbol = pvgTerm.getSymbol();
double dblPValue = pvgTerm.getpValue();
int[] intPositions = mapG2C.get(strSymbol);
if (intPositions == null) {
continue;
}
Gene gneTerm1 = chrTerms[intPositions[0]].genes.get(intPositions[1]);
//Each weight has a different gene-based p-value
if (weightNum > 0) {
strRows[intNo] = new String[6 + weightNum];
strRows[intNo][0] = strSymbol;
strRows[intNo][1] = Util.formatPValue(dblPValue);
strRows[intNo][2] = String.valueOf(gneTerm1.getEntrezID());
strRows[intNo][3] = chrTerms[intPositions[0]].getName();
strRows[intNo][4] = String.valueOf(gneTerm1.getStart());
strRows[intNo][5] = geneGroups[gneTerm1.getGeneGroupID()];
for (int i = 0; i < weightNum; i++) {
strRows[intNo][6 + i] = String.valueOf(pvgTerm.pValues[i]);
}
} else {
strRows[intNo] = new String[]{strSymbol, Util.formatPValue(dblPValue), String.valueOf(gneTerm1.getEntrezID()), chrTerms[intPositions[0]].getName(), String.valueOf(gneTerm1.getStart()), geneGroups[gneTerm1.getGeneGroupID()]};
}
mapSymbol2Gene.put(strSymbol, gneTerm1);
//altGeneSet.add(gneTerm1);
dalPValues.add(dblPValue);
intNo++;
}
DoubleArrayList adjustedP = new DoubleArrayList();
double dblPValueFDR = MultipleTestingMethod.BenjaminiHochbergFDR("Genes", Double.valueOf(jTextField2.getText()), dalPValues, adjustedP);
for (int i = 0; i < dalPValues.size(); i++) {
// boolean boolSignificant = dalPValues.get(i) <= dblPValueFDR;
strRows[i][2] = String.valueOf(adjustedP.getQuick(i));
lstGeneTerm.add(strRows[i]);
}
String genomeVersion = gmeTerm.getFinalBuildGenomeVersion();
if (!genomeVersion.equals("hg19")) {
File CHAIN_FILE = new File(GlobalManager.RESOURCE_PATH + "liftOver/" + genomeVersion + "ToHg19.over.chain.gz");
if (!CHAIN_FILE.exists()) {
if (!CHAIN_FILE.getParentFile().exists()) {
CHAIN_FILE.getParentFile().mkdirs();
}
String url = "http://hgdownload.cse.ucsc.edu/goldenPath/" + genomeVersion + "/liftOver/" + CHAIN_FILE.getName();
//HttpClient4API.downloadAFile(url, CHAIN_FILE);
HttpClient4API.simpleRetriever(url, CHAIN_FILE.getCanonicalPath(), GlobalManager.proxyBean);
Zipper ziper = new Zipper();
ziper.extractTarGz(CHAIN_FILE.getCanonicalPath(), CHAIN_FILE.getParent());
}
CHAIN_FILE = new File(GlobalManager.RESOURCE_PATH + "liftOver/" + genomeVersion + "ToHg19.over.chain");
liftOver = new LiftOver(CHAIN_FILE);
}
publish("Analysis genome have been loaded!");
} catch (InterruptedException ex) {
StatusDisplayer.getDefault().setStatusText("Building analysis genome task was CANCELLED!");
java.util.logging.Logger.getLogger(ShowGeneResultTopComponent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (Exception ex) {
ex.printStackTrace();
StatusDisplayer.getDefault().setStatusText("Building analysis genome task was CANCELLED!");
java.util.logging.Logger.getLogger(ShowGeneResultTopComponent.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
succeed = true;
return null;
}
@Override
protected void process(List<String> chunks) {
// TODO Auto-generated method stub
for (String message : chunks) {
LOG.info(message);
StatusDisplayer.getDefault().setStatusText(message);
}
}
@Override
protected void done() {
try {
String message;
if (succeed) {
aomGeneTermModel.setDataList(lstGeneTerm);
aomGeneTermModel.fireTableStructureChanged();
if (lstGeneTerm.size() > 0) {
showSNPsofGene(0);
}
}
ph.finish();
GlobalManager.isLoadingGenome = false;
} catch (Exception e) {
ErrorManager.getDefault().notify(e);
}
}
}
@Override
public void resultChanged(LookupEvent le) {
Collection<? extends GeneBasedAssociation> allEvents = result.allInstances();
try {
if (!allEvents.isEmpty()) {
event = allEvents.iterator().next();
this.open();
this.requestActive();
if (event != null && event instanceof GeneBasedAssociation) {
if (GlobalManager.isLoadingGenome) {
String infor = "Be patient! I am loading the analysis genome!";
JOptionPane.showMessageDialog(this, infor, "Warnning", JOptionPane.WARNING_MESSAGE);
return;
}
TopComponent outputWindow = WindowManager.getDefault().findTopComponent("AnalysisOutputTopComponent");
//Determine if it is opened
if (outputWindow != null && !outputWindow.isOpened()) {
outputWindow.open();
}
LoadGenomeDataSwingWorker loader = new LoadGenomeDataSwingWorker(event);
theTask = RP.create(loader); //the task is not started yet
theTask.schedule(0); //start the task
}
}
} catch (Exception ex) {
ErrorManager.getDefault().notify(ex);
}
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void chartMouseClicked(ChartMouseEvent cme) {
try {
testData2D();
int intX = cme.getTrigger().getX();
int intY = cme.getTrigger().getY();
Point2D point2d = cplCanvas.translateScreenToJava2D(new Point(intX, intY));
List<Integer> altCandidates = testOverlap(point2d);
if (altCandidates.size() == 1) {
callURL(Integer.valueOf(altCandidates.get(0).toString()));
}
if (altCandidates.size() > 1) {
int intCandidate = testDistance(point2d, altCandidates);
callURL(intCandidate);
}
} catch (URISyntaxException ex) {
Exceptions.printStackTrace(ex);
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public void chartMouseMoved(ChartMouseEvent cme) {
jPanel1.setCursor(new Cursor(Cursor.HAND_CURSOR));
testData2D();
int intX = cme.getTrigger().getX();
int intY = cme.getTrigger().getY();
Point2D point2d = cplCanvas.translateScreenToJava2D(new Point(intX, intY));
List<Integer> altCandidates = testOverlap(point2d);
if (altCandidates.size() == 1) {
wowInfo(Integer.valueOf(altCandidates.get(0).toString()), intX, intY);
}
if (altCandidates.size() > 1) {
int intCandidate = testDistance(point2d, altCandidates);
wowInfo(intCandidate, intX, intY);
}
}
public List<Integer> testOverlap(Point2D pnt) {
List<Integer> altCandidates = new ArrayList<Integer>();
for (int i = 0; i < dblData2D[0].length; i++) {
double dblXDiff = Math.abs(pnt.getX() - dblData2D[0][i]);
double dblYDiff = Math.abs(pnt.getY() - dblData2D[1][i]);
if (dblXDiff <= 4 && dblYDiff <= 4) {
altCandidates.add(i);
}
}
return altCandidates;
}
public int testDistance(Point2D pnt, List<Integer> altCandidates) {
double dblMin = Double.MAX_VALUE;
int intMin = 0;
for (int i = 0; i < altCandidates.size(); i++) {
double dblDistance = Math.sqrt(Math.pow(pnt.getX() - dblData2D[0][Integer.valueOf(altCandidates.get(i).toString())], 2) + Math.pow(pnt.getY() - dblData2D[1][Integer.valueOf(altCandidates.get(i).toString())], 2));
if (dblDistance < dblMin) {
dblMin = dblDistance;
intMin = altCandidates.get(i);
}
}
return intMin;
}
public void callURL(int intIndex) throws URISyntaxException, IOException {
String strURL = "http://jjwanglab.org/gwasrap/gwasrank/gwasrank/quickrap/";
int longPosition = gneTerm.snps.get(intIndex).getPhysicalPosition();
String strChr = chrTerms[mapG2C.get(gneTerm.getSymbol())[0]].getName();
if (liftOver != null && longPosition > 0) {
Interval interval = new Interval("chr" + strChr, longPosition, longPosition);
Interval int2 = liftOver.liftOver(interval);
if (int2 != null) {
longPosition = int2.getStart();
}
}
strURL = strURL + strChr + "/" + longPosition;
URLOpener.openURL(strURL);
}
public void wowInfo(int intIndex, int intX, int intY) {
if (intIndex >= gneTerm.snps.size()) {
return;
}
int longPosition = gneTerm.snps.get(intIndex).getPhysicalPosition();
String strChr = chrTerms[mapG2C.get(gneTerm.getSymbol())[0]].getName();
String strID = gneTerm.snps.get(intIndex).getRsID();
double dblPvalue = gneTerm.snps.get(intIndex).getpValues()[0];
JPopupMenu jpmSNPInfo = new JPopupMenu();
jpmSNPInfo.add("RsID: " + strID);
jpmSNPInfo.add("Chr: " + strChr);
jpmSNPInfo.add("Position: " + longPosition);
jpmSNPInfo.add("p-value: " + dblPvalue);
jpmSNPInfo.setBackground(new Color(248, 248, 255));
jpmSNPInfo.setBorderPainted(false);
jpmSNPInfo.setEnabled(false);
jpmSNPInfo.show(jPanel1, intX + 15, intY + 15);
}
private void testData2D() {
if (true == boolTest) {
return;
}
ChartRenderingInfo criChart = cplCanvas.getChartRenderingInfo();
java.awt.geom.Rectangle2D rectangle2d = criChart.getPlotInfo().getDataArea();
XYPlot xyplot = cplCanvas.getChart().getXYPlot();
ValueAxis vasX = xyplot.getDomainAxis();
ValueAxis vasY = xyplot.getRangeAxis();
for (int j = 0; j < dblData2D[0].length; j++) {
double dblFlag = vasX.valueToJava2D(dblData[0][j], rectangle2d, xyplot.getDomainAxisEdge());
if (dblFlag == dblData2D[0][j]) {
return;
}
dblData2D[0][j] = dblFlag;
dblData2D[1][j] = vasY.valueToJava2D(dblData[1][j], rectangle2d, xyplot.getRangeAxisEdge());
boolTest = true;
}
}
} |
Java | public class Travel implements Parcelable{
String name;
int image;
public Travel(String name, int image) {
this.name = name;
this.image = image;
}
protected Travel(Parcel in) {
name = in.readString();
image = in.readInt();
}
public static final Creator<Travel> CREATOR = new Creator<Travel>() {
@Override
public Travel createFromParcel(Parcel in) {
return new Travel(in);
}
@Override
public Travel[] newArray(int size) {
return new Travel[size];
}
};
public String getName() {
return name;
}
public int getImage() {
return image;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(image);
}
} |
Java | @Database(entities = {Session.class, Speaker.class, Location.class, Favourite.class}, version = 3
, exportSchema = true)
public abstract class AberConRoomDatabase extends RoomDatabase {
private static final String DB_NAME = "abercon_database"; // Constant that holds the name
// given to the database
/**
* Facilitates a migration from version 1 to version 2, that was used previously in the app's
* creation.
*/
private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
Log.d("migrate", "Doing a migrate from version 1 to 2");
// Explicit SQL was required to create a favourites table with a single primary key
// containing the ID of the session that the user added to their favourites.
database.execSQL("CREATE TABLE IF NOT EXISTS favourites (id TEXT NOT NULL, PRIMARY " +
"KEY(id))");
}
};
/**
* Migration final kept in the event of further changed to the database
*/
private static final Migration MIGRATION_2_3 = new Migration(2, 3) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
Log.d("migrate", "Doing a migrate from version 2 to 3");
}
};
private static AberConRoomDatabase INSTANCE;
/**
* Method to retrieve the database instance and create a database if required.
*
* @param context Context of the application
* @return An instance of this class that now has a generated database.
*/
public static AberConRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (AberConRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = createDatabase(context);
}
}
}
return INSTANCE;
}
/**
* Creates a database. This uses an SQLite package to build a database from any given data.
*
* @param context The context of this application
* @return An instance of this class that has a newly-created database.
*/
private static AberConRoomDatabase createDatabase(Context context) {
RoomDatabase.Builder<AberConRoomDatabase> builder = Room
.databaseBuilder(context.getApplicationContext(), AberConRoomDatabase.class,
DB_NAME);
return (builder.openHelperFactory(new AssetSQLiteOpenHelperFactory())
.allowMainThreadQueries()
.addMigrations(MIGRATION_1_2, MIGRATION_2_3)
.build());
}
/**
* Gets the session DAO.
*
* @return SessionDAO containing the session DAO.
*/
public abstract SessionDao getSessionDao();
/**
* Gets the location DAO.
*
* @return LocationDAO containing the location DAO.
*/
public abstract LocationDao getLocationDao();
/**
* Gets the speaker DAO.
*
* @return SpeakerDAO containing the speaker DAO.
*/
public abstract SpeakerDao getSpeakerDao();
/**
* Gets the favourites DAO.
*
* @return FavouritesDAO containing the favourites DAO.
*/
public abstract FavouritesDao getFavouritesDao();
} |
Java | public class AcquiringRequest {
public static final String TERMINAL_KEY = "TerminalKey";
public static final String PAYMENT_ID = "PaymentId";
public static final String SEND_EMAIL = "SendEmail";
public static final String TOKEN = "Token";
public static final String EMAIL = "InfoEmail";
public static final String CARD_DATA = "CardData";
public static final String LANGUAGE = "Language";
public static final String AMOUNT = "Amount";
public static final String ORDER_ID = "OrderId";
public static final String DESCRIPTION = "Description";
public static final String PAY_FORM = "PayForm";
public static final String CUSTOMER_KEY = "CustomerKey";
public static final String RECURRENT = "Recurrent";
public static final String REBILL_ID = "RebillId";
public static final String CARD_ID = "CardId";
public static final String CVV = "CVV";
public static final String PAY_TYPE = "PayType";
public static final String RECEIPT = "Receipt";
public static final String DATA = "DATA";
public static final String CHARGE_FLAG = "chargeFlag";
public static final String DATA_KEY_EMAIL = "Email";
public static final String[] IGNORED_FIELDS_VALUES = new String[]{DATA, RECEIPT};
public static final Set<String> IGNORED_FIELDS = new HashSet<>(Arrays.asList(IGNORED_FIELDS_VALUES));
private String terminalKey;
private String token;
private final String apiMethod;
AcquiringRequest(String apiMethod) {
this.apiMethod = apiMethod;
}
public Map<String, Object> asMap() {
Map<String, Object> map = new HashMap<>();
putIfNotNull(TERMINAL_KEY, terminalKey, map);
putIfNotNull(TOKEN, token, map);
return map;
}
public Set<String> getTokenIgnoreFields() {
return IGNORED_FIELDS;
}
public String getTerminalKey() {
return terminalKey;
}
void setTerminalKey(String terminalKey) {
this.terminalKey = terminalKey;
}
public String getToken() {
return token;
}
void setToken(String token) {
this.token = token;
}
public String getApiMethod() {
return apiMethod;
}
protected void putIfNotNull(final String key, final Object value, final Map<String, Object> map) {
if (key == null || value == null || map == null) {
return;
}
map.put(key, value);
}
} |
Java | public class LazySetterMethodTest {
private class A {
private B b;
public A(B b) {
this.b = b;
}
public B getB() {
return b;
}
@SuppressWarnings("unused")
public void setB(B b) {
this.b = b;
}
}
private class B {
private String s;
public B(String s) {
this.s = s;
}
public String getS() {
return s;
}
public void setS(String s) {
this.s = s;
}
}
private A a;
@Before
public void setUp() {
this.a = new A(new B(""));
}
/**
* Test of invoke method, of class LazySetterMethod.
*/
@Test
public void testInvoke() throws Exception {
new LazySetterMethod(a, "b.s", "value").invoke();
assertEquals(a.getB().getS(), "value");
a.getB().setS("test");
assertEquals(a.getB().getS(), "test");
new LazySetterMethod(a, "b.s", new LazyGetterMethod(new B("lazyValue"),
"s")).invoke();
assertEquals(a.getB().getS(), "lazyValue");
a.getB().setS(new B("lazyValue").getS());
assertEquals(a.getB().getS(), "lazyValue");
}
} |
Java | public class NavigationView extends RelativeLayout implements
AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener,
BreadcrumbListener, OnSelectionChangedListener, OnSelectionListener, OnRequestRefreshListener {
private static final String TAG = "NavigationView"; //$NON-NLS-1$
/**
* An interface to communicate selection changes events.
*/
public interface OnNavigationSelectionChangedListener {
/**
* Method invoked when the selection changed.
*
* @param navView The navigation view that generate the event
* @param selectedItems The new selected items
*/
void onSelectionChanged(NavigationView navView, List<FileSystemObject> selectedItems);
}
/**
* An interface to communicate a request for show the menu associated
* with an item.
*/
public interface OnNavigationRequestMenuListener {
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param navView The navigation view that generate the event
* @param item The item for which the request was started
*/
void onRequestMenu(NavigationView navView, FileSystemObject item);
}
/**
* An interface to communicate a request when the user choose a file.
*/
public interface OnFilePickedListener {
/**
* Method invoked when a request when the user choose a file.
*
* @param item The item choose
*/
void onFilePicked(FileSystemObject item);
}
/**
* The navigation view mode
* @hide
*/
public enum NAVIGATION_MODE {
/**
* The navigation view acts as a browser, and allow open files itself.
*/
BROWSABLE,
/**
* The navigation view acts as a picker of files
*/
PICKABLE,
}
/**
* A listener for flinging events from {@link FlingerListView}
*/
private final OnItemFlingerListener mOnItemFlingerListener = new OnItemFlingerListener() {
@Override
public boolean onItemFlingerStart(
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
if (fso instanceof ParentDirectory) {
return false;
}
return true;
}
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
}
return false;
}
@Override
public void onItemFlingerEnd(OnItemFlingerResponder responder,
AdapterView<?> parent, View view, int position, long id) {
try {
// Response if the item can be removed
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)parent.getAdapter();
FileSystemObject fso = adapter.getItem(position);
if (fso != null) {
DeleteActionPolicy.removeFileSystemObject(
getContext(),
fso,
NavigationView.this,
NavigationView.this,
responder);
return;
}
// Cancels the flinger operation
responder.cancel();
} catch (Exception e) {
ExceptionUtil.translateException(getContext(), e, true, false);
responder.cancel();
}
}
};
private int mId;
private String mCurrentDir;
private NavigationLayoutMode mCurrentMode;
/**
* @hide
*/
List<FileSystemObject> mFiles;
private FileSystemObjectAdapter mAdapter;
private final Object mSync = new Object();
private OnHistoryListener mOnHistoryListener;
private OnNavigationSelectionChangedListener mOnNavigationSelectionChangedListener;
private OnNavigationRequestMenuListener mOnNavigationRequestMenuListener;
private OnFilePickedListener mOnFilePickedListener;
private boolean mChRooted;
private NAVIGATION_MODE mNavigationMode;
// Restrictions
private Map<DisplayRestrictions, Object> mRestrictions;
/**
* @hide
*/
Breadcrumb mBreadcrumb;
/**
* @hide
*/
NavigationCustomTitleView mTitle;
/**
* @hide
*/
AdapterView<?> mAdapterView;
//The layout for icons mode
private static final int RESOURCE_MODE_ICONS_LAYOUT = R.layout.navigation_view_icons;
private static final int RESOURCE_MODE_ICONS_ITEM = R.layout.navigation_view_icons_item;
//The layout for simple mode
private static final int RESOURCE_MODE_SIMPLE_LAYOUT = R.layout.navigation_view_simple;
private static final int RESOURCE_MODE_SIMPLE_ITEM = R.layout.navigation_view_simple_item;
//The layout for details mode
private static final int RESOURCE_MODE_DETAILS_LAYOUT = R.layout.navigation_view_details;
private static final int RESOURCE_MODE_DETAILS_ITEM = R.layout.navigation_view_details_item;
//The current layout identifier (is shared for all the mode layout)
private static final int RESOURCE_CURRENT_LAYOUT = R.id.navigation_view_layout;
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public NavigationView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Navigable);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Constructor of <code>NavigationView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
*/
public NavigationView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.Navigable, defStyle, 0);
try {
init(a);
} finally {
a.recycle();
}
}
/**
* Invoked when the instance need to be saved.
*
* @return NavigationViewInfoParcelable The serialized info
*/
public NavigationViewInfoParcelable onSaveState() {
//Return the persistent the data
NavigationViewInfoParcelable parcel = new NavigationViewInfoParcelable();
parcel.setId(this.mId);
parcel.setCurrentDir(this.mCurrentDir);
parcel.setChRooted(this.mChRooted);
parcel.setSelectedFiles(this.mAdapter.getSelectedItems());
parcel.setFiles(this.mFiles);
return parcel;
}
/**
* Invoked when the instance need to be restored.
*
* @param info The serialized info
*/
public void onRestoreState(NavigationViewInfoParcelable info) {
//Restore the data
this.mId = info.getId();
this.mCurrentDir = info.getCurrentDir();
this.mChRooted = info.getChRooted();
this.mFiles = info.getFiles();
this.mAdapter.setSelectedItems(info.getSelectedFiles());
//Update the views
refresh();
}
/**
* Method that initializes the view. This method loads all the necessary
* information and create an appropriate layout for the view.
*
* @param tarray The type array
*/
private void init(TypedArray tarray) {
// Retrieve the mode
this.mNavigationMode = NAVIGATION_MODE.BROWSABLE;
int mode = tarray.getInteger(
R.styleable.Navigable_navigation,
NAVIGATION_MODE.BROWSABLE.ordinal());
if (mode >= 0 && mode < NAVIGATION_MODE.values().length) {
this.mNavigationMode = NAVIGATION_MODE.values()[mode];
}
// Initialize default restrictions (no restrictions)
this.mRestrictions = new HashMap<DisplayRestrictions, Object>();
//Initialize variables
this.mFiles = new ArrayList<FileSystemObject>();
// Is ChRooted environment?
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
// Pick mode is always ChRooted
this.mChRooted = true;
} else {
this.mChRooted =
FileManagerApplication.getAccessMode().compareTo(AccessMode.SAFE) == 0;
}
//Retrieve the default configuration
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
SharedPreferences preferences = Preferences.getSharedPreferences();
int viewMode = preferences.getInt(
FileManagerSettings.SETTINGS_LAYOUT_MODE.getId(),
((ObjectIdentifier)FileManagerSettings.
SETTINGS_LAYOUT_MODE.getDefaultValue()).getId());
changeViewMode(NavigationLayoutMode.fromId(viewMode));
} else {
// Pick mode has always a details layout
changeViewMode(NavigationLayoutMode.DETAILS);
}
}
/**
* Method that returns the display restrictions to apply to this view.
*
* @return Map<DisplayRestrictions, Object> The restrictions to apply
*/
public Map<DisplayRestrictions, Object> getRestrictions() {
return this.mRestrictions;
}
/**
* Method that sets the display restrictions to apply to this view.
*
* @param mRestrictions The restrictions to apply
*/
public void setRestrictions(Map<DisplayRestrictions, Object> mRestrictions) {
this.mRestrictions = mRestrictions;
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getFiles() {
if (this.mFiles == null) {
return null;
}
return new ArrayList<FileSystemObject>(this.mFiles);
}
/**
* Method that returns the current file list of the navigation view.
*
* @return List<FileSystemObject> The current file list of the navigation view
*/
public List<FileSystemObject> getSelectedFiles() {
if (this.mAdapter != null && this.mAdapter.getSelectedItems() != null) {
return new ArrayList<FileSystemObject>(this.mAdapter.getSelectedItems());
}
return null;
}
/**
* Method that returns the custom title fragment associated with this navigation view.
*
* @return NavigationCustomTitleView The custom title view fragment
*/
public NavigationCustomTitleView getCustomTitle() {
return this.mTitle;
}
/**
* Method that associates the custom title fragment with this navigation view.
*
* @param title The custom title view fragment
*/
public void setCustomTitle(NavigationCustomTitleView title) {
this.mTitle = title;
}
/**
* Method that returns the breadcrumb associated with this navigation view.
*
* @return Breadcrumb The breadcrumb view fragment
*/
public Breadcrumb getBreadcrumb() {
return this.mBreadcrumb;
}
/**
* Method that associates the breadcrumb with this navigation view.
*
* @param breadcrumb The breadcrumb view fragment
*/
public void setBreadcrumb(Breadcrumb breadcrumb) {
this.mBreadcrumb = breadcrumb;
this.mBreadcrumb.addBreadcrumbListener(this);
}
/**
* Method that sets the listener for communicate history changes.
*
* @param onHistoryListener The listener for communicate history changes
*/
public void setOnHistoryListener(OnHistoryListener onHistoryListener) {
this.mOnHistoryListener = onHistoryListener;
}
/**
* Method that sets the listener which communicates selection changes.
*
* @param onNavigationSelectionChangedListener The listener reference
*/
public void setOnNavigationSelectionChangedListener(
OnNavigationSelectionChangedListener onNavigationSelectionChangedListener) {
this.mOnNavigationSelectionChangedListener = onNavigationSelectionChangedListener;
}
/**
* Method that sets the listener for menu item requests.
*
* @param onNavigationRequestMenuListener The listener reference
*/
public void setOnNavigationOnRequestMenuListener(
OnNavigationRequestMenuListener onNavigationRequestMenuListener) {
this.mOnNavigationRequestMenuListener = onNavigationRequestMenuListener;
}
/**
* @return the mOnFilePickedListener
*/
public OnFilePickedListener getOnFilePickedListener() {
return this.mOnFilePickedListener;
}
/**
* Method that sets the listener for picked items
*
* @param onFilePickedListener The listener reference
*/
public void setOnFilePickedListener(OnFilePickedListener onFilePickedListener) {
this.mOnFilePickedListener = onFilePickedListener;
}
/**
* Method that sets if the view should use flinger gesture detection.
*
* @param useFlinger If the view should use flinger gesture detection
*/
public void setUseFlinger(boolean useFlinger) {
if (this.mCurrentMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
// Not supported
return;
}
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (this.mAdapterView instanceof FlingerListView) {
if (useFlinger) {
((FlingerListView)this.mAdapterView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
} else {
((FlingerListView)this.mAdapterView).setOnItemFlingerListener(null);
}
}
}
}
/**
* Method that forces the view to scroll to the file system object passed.
*
* @param fso The file system object
*/
public void scrollTo(FileSystemObject fso) {
if (fso != null) {
try {
int position = this.mAdapter.getPosition(fso);
this.mAdapterView.setSelection(position);
} catch (Exception e) {
this.mAdapterView.setSelection(0);
}
} else {
this.mAdapterView.setSelection(0);
}
}
/**
* Method that refresh the view data.
*/
public void refresh() {
refresh(false);
}
/**
* Method that refresh the view data.
*
* @param restore Restore previous position
*/
public void refresh(boolean restore) {
FileSystemObject fso = null;
// Try to restore the previous scroll position
if (restore) {
try {
if (this.mAdapterView != null && this.mAdapter != null) {
int position = this.mAdapterView.getFirstVisiblePosition();
fso = this.mAdapter.getItem(position);
}
} catch (Throwable _throw) {/**NON BLOCK**/}
}
refresh(fso);
}
/**
* Method that refresh the view data.
*
* @param scrollTo Scroll to object
*/
public void refresh(FileSystemObject scrollTo) {
//Check that current directory was set
if (this.mCurrentDir == null || this.mFiles == null) {
return;
}
//Reload data
changeCurrentDir(this.mCurrentDir, false, true, false, null, scrollTo);
}
/**
* Method that change the view mode.
*
* @param newMode The new mode
*/
@SuppressWarnings({ "unchecked", "null" })
public void changeViewMode(final NavigationLayoutMode newMode) {
synchronized (this.mSync) {
//Check that it is really necessary change the mode
if (this.mCurrentMode != null && this.mCurrentMode.compareTo(newMode) == 0) {
return;
}
// If we should set the listview to response to flinger gesture detection
boolean useFlinger =
Preferences.getSharedPreferences().getBoolean(
FileManagerSettings.SETTINGS_USE_FLINGER.getId(),
((Boolean)FileManagerSettings.
SETTINGS_USE_FLINGER.
getDefaultValue()).booleanValue());
//Creates the new layout
AdapterView<ListAdapter> newView = null;
int itemResourceId = -1;
if (newMode.compareTo(NavigationLayoutMode.ICONS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_ICONS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_ICONS_ITEM;
} else if (newMode.compareTo(NavigationLayoutMode.SIMPLE) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_SIMPLE_LAYOUT, null);
itemResourceId = RESOURCE_MODE_SIMPLE_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
} else if (newMode.compareTo(NavigationLayoutMode.DETAILS) == 0) {
newView = (AdapterView<ListAdapter>)inflate(
getContext(), RESOURCE_MODE_DETAILS_LAYOUT, null);
itemResourceId = RESOURCE_MODE_DETAILS_ITEM;
// Set the flinger listener (only when navigate)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
if (useFlinger && newView instanceof FlingerListView) {
((FlingerListView)newView).
setOnItemFlingerListener(this.mOnItemFlingerListener);
}
}
}
//Get the current adapter and its adapter list
List<FileSystemObject> files = new ArrayList<FileSystemObject>(this.mFiles);
final AdapterView<ListAdapter> current =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter =
new FileSystemObjectAdapter(
getContext(),
new ArrayList<FileSystemObject>(),
itemResourceId,
this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0);
adapter.setOnSelectionChangedListener(this);
//Remove current layout
if (current != null) {
if (current.getAdapter() != null) {
//Save selected items before dispose adapter
FileSystemObjectAdapter currentAdapter =
((FileSystemObjectAdapter)current.getAdapter());
adapter.setSelectedItems(currentAdapter.getSelectedItems());
currentAdapter.dispose();
}
removeView(current);
}
this.mFiles = files;
adapter.addAll(files);
adapter.notifyDataSetChanged();
//Set the adapter
this.mAdapter = adapter;
newView.setAdapter(this.mAdapter);
newView.setOnItemClickListener(NavigationView.this);
//Add the new layout
this.mAdapterView = newView;
addView(newView, 0);
this.mCurrentMode = newMode;
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
this.mAdapterView.setOnItemLongClickListener(this);
} else {
this.mAdapterView.setOnItemLongClickListener(null);
}
//Save the preference (only in navigation browse mode)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
try {
Preferences.savePreference(
FileManagerSettings.SETTINGS_LAYOUT_MODE, newMode, true);
} catch (Exception ex) {
Log.e(TAG, "Save of view mode preference fails", ex); //$NON-NLS-1$
}
}
}
}
/**
* Method that removes a {@link FileSystemObject} from the view
*
* @param fso The file system object
*/
public void removeItem(FileSystemObject fso) {
this.mAdapter.remove(fso);
// Delete also from internal list
if (fso != null) {
int cc = this.mFiles.size()-1;
for (int i = cc; i >= 0; i--) {
FileSystemObject f = this.mFiles.get(i);
if (f != null && f.compareTo(fso) == 0) {
this.mFiles.remove(i);
break;
}
}
}
this.mAdapter.notifyDataSetChanged();
}
/**
* Method that removes a file system object from his path from the view
*
* @param path The file system object path
*/
public void removeItem(String path) {
FileSystemObject fso = this.mAdapter.getItem(path);
if (fso != null) {
this.mAdapter.remove(fso);
this.mAdapter.notifyDataSetChanged();
}
}
/**
* Method that returns the current directory.
*
* @return String The current directory
*/
public String getCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
*/
public void changeCurrentDir(final String newDir) {
changeCurrentDir(newDir, true, false, false, null, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
*/
public void changeCurrentDir(final String newDir, SearchInfoParcelable searchInfo) {
changeCurrentDir(newDir, true, false, false, searchInfo, null);
}
/**
* Method that changes the current directory of the view.
*
* @param newDir The new directory location
* @param addToHistory Add the directory to history
* @param reload Force the reload of the data
* @param useCurrent If this method must use the actual data (for back actions)
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param scrollTo If not null, then listview must scroll to this item
*/
private void changeCurrentDir(
final String newDir, final boolean addToHistory,
final boolean reload, final boolean useCurrent,
final SearchInfoParcelable searchInfo, final FileSystemObject scrollTo) {
// Check navigation security (don't allow to go outside the ChRooted environment if one
// is created)
final String fNewDir = checkChRootedNavigation(newDir);
synchronized (this.mSync) {
//Check that it is really necessary change the directory
if (!reload && this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0) {
return;
}
final boolean hasChanged =
!(this.mCurrentDir != null && this.mCurrentDir.compareTo(fNewDir) == 0);
final boolean isNewHistory = (this.mCurrentDir != null);
//Execute the listing in a background process
AsyncTask<String, Integer, List<FileSystemObject>> task =
new AsyncTask<String, Integer, List<FileSystemObject>>() {
/**
* {@inheritDoc}
*/
@Override
protected List<FileSystemObject> doInBackground(String... params) {
try {
//Reset the custom title view and returns to breadcrumb
if (NavigationView.this.mTitle != null) {
NavigationView.this.mTitle.post(new Runnable() {
@Override
public void run() {
try {
NavigationView.this.mTitle.restoreView();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//Start of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.startLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
//Get the files, resolve links and apply configuration
//(sort, hidden, ...)
List<FileSystemObject> files = NavigationView.this.mFiles;
if (!useCurrent) {
files = CommandHelper.listFiles(getContext(), fNewDir, null);
}
return files;
} catch (final ConsoleAllocException e) {
//Show exception and exists
NavigationView.this.post(new Runnable() {
@Override
public void run() {
Context ctx = getContext();
Log.e(TAG, ctx.getString(
R.string.msgs_cant_create_console), e);
DialogHelper.showToast(ctx,
R.string.msgs_cant_create_console,
Toast.LENGTH_LONG);
((Activity)ctx).finish();
}
});
return null;
} catch (Exception ex) {
//End of loading data
if (NavigationView.this.mBreadcrumb != null) {
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex2) {
/**NON BLOCK**/
}
}
//Capture exception
ExceptionUtil.attachAsyncTask(
ex,
new AsyncTask<Object, Integer, Boolean>() {
@Override
@SuppressWarnings("unchecked")
protected Boolean doInBackground(Object... taskParams) {
final List<FileSystemObject> files =
(List<FileSystemObject>)taskParams[0];
NavigationView.this.mAdapterView.post(
new Runnable() {
@Override
public void run() {
onPostExecuteTask(
files, addToHistory,
isNewHistory, hasChanged,
searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
}
});
return Boolean.TRUE;
}
});
ExceptionUtil.translateException(getContext(), ex);
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
protected void onPreExecute() {
// Do animation
fadeEfect(true);
}
/**
* {@inheritDoc}
*/
@Override
protected void onPostExecute(List<FileSystemObject> files) {
if (files != null) {
onPostExecuteTask(
files, addToHistory, isNewHistory,
hasChanged, searchInfo, fNewDir, scrollTo);
// Do animation
fadeEfect(false);
}
}
/**
* Method that performs a fade animation.
*
* @param out Fade out (true); Fade in (false)
*/
void fadeEfect(boolean out) {
Animation fadeAnim = out ?
new AlphaAnimation(1, 0) :
new AlphaAnimation(0, 1);
fadeAnim.setDuration(50L);
fadeAnim.setFillAfter(true);
fadeAnim.setInterpolator(new AccelerateInterpolator());
NavigationView.this.startAnimation(fadeAnim);
}
};
task.execute(fNewDir);
}
}
/**
* Method invoked when a execution ends.
*
* @param files The files obtains from the list
* @param addToHistory If add path to history
* @param isNewHistory If is new history
* @param hasChanged If current directory was changed
* @param searchInfo The search information (if calling activity is {@link "SearchActivity"})
* @param newDir The new directory
* @param scrollTo If not null, then listview must scroll to this item
* @hide
*/
void onPostExecuteTask(
List<FileSystemObject> files, boolean addToHistory, boolean isNewHistory,
boolean hasChanged, SearchInfoParcelable searchInfo,
String newDir, final FileSystemObject scrollTo) {
try {
//Check that there is not errors and have some data
if (files == null) {
return;
}
//Apply user preferences
List<FileSystemObject> sortedFiles =
FileHelper.applyUserPreferences(files, this.mRestrictions, this.mChRooted);
//Remove parent directory if we are in the root of a chrooted environment
if (this.mChRooted && StorageHelper.isStorageVolume(newDir)) {
if (files.size() > 0 && files.get(0) instanceof ParentDirectory) {
files.remove(0);
}
}
//Load the data
loadData(sortedFiles);
this.mFiles = sortedFiles;
if (searchInfo != null) {
searchInfo.setSuccessNavigation(true);
}
//Add to history?
if (addToHistory && hasChanged && isNewHistory) {
if (this.mOnHistoryListener != null) {
//Communicate the need of a history change
this.mOnHistoryListener.onNewHistory(onSaveState());
}
}
//Change the breadcrumb
if (this.mBreadcrumb != null) {
this.mBreadcrumb.changeBreadcrumbPath(newDir, this.mChRooted);
}
//Scroll to object?
if (scrollTo != null) {
scrollTo(scrollTo);
}
//The current directory is now the "newDir"
this.mCurrentDir = newDir;
} finally {
//If calling activity is search, then save the search history
if (searchInfo != null) {
this.mOnHistoryListener.onNewHistory(searchInfo);
}
//End of loading data
try {
NavigationView.this.mBreadcrumb.endLoading();
} catch (Throwable ex) {
/**NON BLOCK**/
}
}
}
/**
* Method that loads the files in the adapter.
*
* @param files The files to load in the adapter
* @hide
*/
@SuppressWarnings("unchecked")
private void loadData(final List<FileSystemObject> files) {
//Notify data to adapter view
final AdapterView<ListAdapter> view =
(AdapterView<ListAdapter>)findViewById(RESOURCE_CURRENT_LAYOUT);
FileSystemObjectAdapter adapter = (FileSystemObjectAdapter)view.getAdapter();
adapter.clear();
adapter.addAll(files);
adapter.notifyDataSetChanged();
view.setSelection(0);
}
/**
* {@inheritDoc}
*/
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// Different actions depending on user preference
// Get the adapter and the fso
FileSystemObjectAdapter adapter = ((FileSystemObjectAdapter)parent.getAdapter());
FileSystemObject fso = adapter.getItem(position);
// Parent directory hasn't actions
if (fso instanceof ParentDirectory) {
return false;
}
// Pick mode doesn't implements the onlongclick
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.PICKABLE) == 0) {
return false;
}
onRequestMenu(fso);
return true; //Always consume the event
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
*/
public void open(FileSystemObject fso) {
open(fso, null);
}
/**
* Method that opens or navigates to the {@link FileSystemObject}
*
* @param fso The file system object
* @param searchInfo The search info
*/
public void open(FileSystemObject fso, SearchInfoParcelable searchInfo) {
// If is a folder, then navigate to
if (FileHelper.isDirectory(fso)) {
changeCurrentDir(fso.getFullPath(), searchInfo);
} else {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
FileSystemObject fso = ((FileSystemObjectAdapter)parent.getAdapter()).getItem(position);
if (fso instanceof ParentDirectory) {
changeCurrentDir(fso.getParent(), true, false, false, null, null);
return;
} else if (fso instanceof Directory) {
changeCurrentDir(fso.getFullPath(), true, false, false, null, null);
return;
} else if (fso instanceof Symlink) {
Symlink symlink = (Symlink)fso;
if (symlink.getLinkRef() != null && symlink.getLinkRef() instanceof Directory) {
changeCurrentDir(
symlink.getLinkRef().getFullPath(), true, false, false, null, null);
return;
}
// Open the link ref
fso = symlink.getLinkRef();
}
// Open the file (edit or pick)
if (this.mNavigationMode.compareTo(NAVIGATION_MODE.BROWSABLE) == 0) {
// Open the file with the preferred registered app
IntentsActionPolicy.openFileSystemObject(getContext(), fso, false, null, null);
} else {
// Request a file pick selection
if (this.mOnFilePickedListener != null) {
this.mOnFilePickedListener.onFilePicked(fso);
}
}
} catch (Throwable ex) {
ExceptionUtil.translateException(getContext(), ex);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRefresh(Object o, boolean clearSelection) {
if (o instanceof FileSystemObject) {
refresh((FileSystemObject)o);
} else if (o == null) {
refresh();
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onRequestRemove(Object o, boolean clearSelection) {
if (o != null && o instanceof FileSystemObject) {
removeItem((FileSystemObject)o);
} else {
onRequestRefresh(null, clearSelection);
}
if (clearSelection) {
onDeselectAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onNavigateTo(Object o) {
// Ignored
}
/**
* {@inheritDoc}
*/
@Override
public void onBreadcrumbItemClick(BreadcrumbItem item) {
changeCurrentDir(item.getItemPath(), true, true, false, null, null);
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectionChanged(final List<FileSystemObject> selectedItems) {
if (this.mOnNavigationSelectionChangedListener != null) {
this.mOnNavigationSelectionChangedListener.onSelectionChanged(this, selectedItems);
}
}
/**
* Method invoked when a request to show the menu associated
* with an item is started.
*
* @param item The item for which the request was started
*/
public void onRequestMenu(final FileSystemObject item) {
if (this.mOnNavigationRequestMenuListener != null) {
this.mOnNavigationRequestMenuListener.onRequestMenu(this, item);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onToggleSelection(FileSystemObject fso) {
if (this.mAdapter != null) {
this.mAdapter.toggleSelection(fso);
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAll() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAll();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onSelectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.selectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public void onDeselectAllVisibleItems() {
if (this.mAdapter != null) {
this.mAdapter.deselectedAllVisibleItems();
}
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestSelectedFiles() {
return this.getSelectedFiles();
}
/**
* {@inheritDoc}
*/
@Override
public List<FileSystemObject> onRequestCurrentItems() {
return this.getFiles();
}
/**
* {@inheritDoc}
*/
@Override
public String onRequestCurrentDir() {
return this.mCurrentDir;
}
/**
* Method that creates a ChRooted environment, protecting the user to break anything
* in the device
* @hide
*/
public void createChRooted() {
// If we are in a ChRooted environment, then do nothing
if (this.mChRooted) return;
this.mChRooted = true;
//Change to first storage volume
StorageVolume[] volumes =
StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
changeCurrentDir(volumes[0].getPath(), false, true, false, null, null);
}
}
/**
* Method that exits from a ChRooted environment
* @hide
*/
public void exitChRooted() {
// If we aren't in a ChRooted environment, then do nothing
if (!this.mChRooted) return;
this.mChRooted = false;
// Refresh
refresh();
}
/**
* Method that ensures that the user don't go outside the ChRooted environment
*
* @param newDir The new directory to navigate to
* @return String
*/
private String checkChRootedNavigation(String newDir) {
// If we aren't in ChRooted environment, then there is nothing to check
if (!this.mChRooted) return newDir;
// Check if the path is owned by one of the storage volumes
if (!StorageHelper.isPathInStorageVolume(newDir)) {
StorageVolume[] volumes = StorageHelper.getStorageVolumes(getContext());
if (volumes != null && volumes.length > 0) {
return volumes[0].getPath();
}
}
return newDir;
}
/**
* Method that applies the current theme to the activity
*/
public void applyTheme() {
//- Breadcrumb
if (getBreadcrumb() != null) {
getBreadcrumb().applyTheme();
}
//- Redraw the adapter view
Theme theme = ThemeManager.getCurrentTheme(getContext());
theme.setBackgroundDrawable(getContext(), this, "background_drawable"); //$NON-NLS-1$
if (this.mAdapter != null) {
this.mAdapter.notifyThemeChanged();
}
if (this.mAdapterView instanceof ListView) {
((ListView)this.mAdapterView).setDivider(
theme.getDrawable(getContext(), "horizontal_divider_drawable")); //$NON-NLS-1$
}
refresh();
}
} |
Java | public class Case {
public Address addr;
public byte[] mask;
public byte[] value;
public String textRep;
} |
Java | public class SLMaskControl {
boolean useMnemonic = true;
boolean useOp1 = false;
boolean useOp2 = false;
boolean useConst = false;
public SLMaskControl() {
}
public SLMaskControl(boolean mnemonic, boolean useop1, boolean useop2, boolean constant) {
useMnemonic = mnemonic;
useOp1 = useop1;
useOp2 = useop2;
useConst = constant;
}
} |
Java | @Data
@EqualsAndHashCode(callSuper = true)
public class ActionDocumentation extends BaseDocumentation {
/**
* The keys of the map are the names of one of the action's inputs, the values are a description for the input.
*/
private Map<@NotBlank String, @NotBlank String> inputs = Collections.emptyMap();
/**
* A description of the action's return value.
*/
private String returnValue = "";
} |
Java | @XmlRootElement( name = "item", namespace = "http://localhost:8080/bloom-test/rest/items" )
public class Item {
/**
* The Item id.
*/
private Long itemId;
/**
* The Item price.
*/
private Double itemPrice;
/**
* The Quantity.
*/
private Double quantity;
/**
* The Weight.
*/
private Double weight;
/**
* The Item price currency.
*/
private String itemPriceCurrency;
/**
* The Item name.
*/
private String itemName;
/**
* The Item Description.
*/
private String itemDescription;
/**
* The Item type.
*/
private String itemType;
/**
* The Item sub type.
*/
private String itemSubType;
/**
* The Bought from.
*/
private String boughtFrom;
/**
* The Quantity type.
*/
private String quantityType;
/**
* The Weighted unit.
*/
private String weightedUnit;
/**
* The Bought date.
*/
private Date boughtDate;
/**
* The Image count.
*/
private int imageCount;
private String itemOrigin;
/**
* The Item image list.
*/
private List< ItemImage > itemImageList;
/**
* The Item discount list.
*/
private List< ItemDiscount > itemDiscountList;
private List< Gemstone > gemstoneList;
/**
* Gets item id.
*
* @return the item id
*/
@XmlElement( name = "item_id", nillable = false )
public Long getItemId( ) {
return itemId;
}
/**
* Sets item id.
*
* @param itemId the item id
*/
public void setItemId( Long itemId ) {
this.itemId = itemId;
}
/**
* Gets item price.
*
* @return the item price
*/
@XmlElement( name = "item_price", defaultValue = "0.00", nillable = false )
public Double getItemPrice( ) {
return itemPrice;
}
/**
* Sets item price.
*
* @param itemPrice the item price
*/
public void setItemPrice( Double itemPrice ) {
this.itemPrice = itemPrice;
}
/**
* Gets item price currency.
*
* @return the item price currency
*/
@XmlElement( name = "item_price_currency", defaultValue = "Dollar", nillable = false )
public String getItemPriceCurrency( ) {
return itemPriceCurrency;
}
/**
* Sets item price currency.
*
* @param itemPriceCurrency the item price currency
*/
public void setItemPriceCurrency( String itemPriceCurrency ) {
this.itemPriceCurrency = itemPriceCurrency;
}
/**
* Gets item name.
*
* @return the item name
*/
@XmlElement( name = "item_name", defaultValue = "Unknown", nillable = false )
public String getItemName( ) {
return itemName;
}
/**
* Sets item name.
*
* @param itemName the item name
*/
public void setItemName( String itemName ) {
this.itemName = itemName;
}
@XmlElement( name = "item_description", defaultValue = "Not Available" )
public String getItemDescription( ) {
return itemDescription;
}
public void setItemDescription( final String itemDescription ) {
this.itemDescription = itemDescription;
}
/**
* Gets item type.
*
* @return the item type
*/
@XmlElement( name = "item_type", defaultValue = "Food", nillable = false )
public String getItemType( ) {
return itemType;
}
/**
* Sets item type.
*
* @param itemType the item type
*/
public void setItemType( String itemType ) {
this.itemType = itemType;
}
/**
* Gets item sub type.
*
* @return the item sub type
*/
@XmlElement( name = "item_sub_type", defaultValue = "None", nillable = false )
public String getItemSubType( ) {
return itemSubType;
}
/**
* Sets item sub type.
*
* @param itemSubType the item sub type
*/
public void setItemSubType( String itemSubType ) {
this.itemSubType = itemSubType;
}
/**
* Gets bought from.
*
* @return the bought from
*/
@XmlElement( name = "bought_from", defaultValue = "SomeStore", nillable = false )
public String getBoughtFrom( ) {
return boughtFrom;
}
/**
* Sets bought from.
*
* @param boughtFrom the bought from
*/
public void setBoughtFrom( String boughtFrom ) {
this.boughtFrom = boughtFrom;
}
/**
* Gets bought date.
*
* @return the bought date
*/
@XmlElement( name = "bought_date", nillable = false )
@XmlJavaTypeAdapter( value = DateFormatAdapter.class )
public Date getBoughtDate( ) {
return boughtDate;
}
/**
* Sets bought date.
*
* @param boughtDate the bought date
*/
public void setBoughtDate( final Date boughtDate ) {
this.boughtDate = boughtDate;
}
/**
* Gets quantity.
*
* @return the quantity
*/
@XmlElement( name = "quantity", defaultValue = "0", nillable = false )
public Double getQuantity( ) {
return quantity;
}
/**
* Sets quantity.
*
* @param quantity the quantity
*/
public void setQuantity( final Double quantity ) {
this.quantity = quantity;
}
/**
* Gets quantity type.
*
* @return the quantity type
*/
@XmlElement( name = "quantity_type", defaultValue = "units", nillable = false )
public String getQuantityType( ) {
return quantityType;
}
/**
* Sets quantity type.
*
* @param quantityType the quantity type
*/
public void setQuantityType( String quantityType ) {
this.quantityType = quantityType;
}
/**
* Gets weight.
*
* @return the weight
*/
@XmlElement( name = "weight", defaultValue = "0", nillable = false )
public Double getWeight( ) {
return weight;
}
/**
* Sets weight.
*
* @param weight the weight
*/
public void setWeight( final Double weight ) {
this.weight = weight;
}
/**
* Gets weighted unit.
*
* @return the weighted unit
*/
@XmlElement( name = "weighted_unit", defaultValue = "ounces", nillable = false )
public String getWeightedUnit( ) {
return weightedUnit;
}
/**
* Sets weighted unit.
*
* @param weightedUnit the weighted unit
*/
public void setWeightedUnit( final String weightedUnit ) {
this.weightedUnit = weightedUnit;
}
/**
* Gets image count.
*
* @return the image count
*/
@XmlElement( name = "image_count", defaultValue = "0", nillable = false )
public int getImageCount( ) {
return imageCount;
}
/**
* Sets image count.
*
* @param imageCount the image count
*/
public void setImageCount( final int imageCount ) {
this.imageCount = imageCount;
}
@XmlElementWrapper( name = "item_images" )
@XmlElement( name = "item_image", nillable = true )
public List< ItemImage > getItemImageList( ) {
return itemImageList;
}
public void setItemImageList( final List< ItemImage > itemImageList ) {
this.itemImageList = itemImageList;
}
@XmlElementWrapper( name = "item_discounts" )
@XmlElement( name = "item_discount", nillable = true )
public List< ItemDiscount > getItemDiscountList( ) {
return itemDiscountList;
}
public void setItemDiscountList( final List< ItemDiscount > itemDiscountList ) {
this.itemDiscountList = itemDiscountList;
}
@XmlElement( name = "item_origin", nillable = true )
public String getItemOrigin( ) {
return itemOrigin;
}
public void setItemOrigin( final String itemOrigin ) {
this.itemOrigin = itemOrigin;
}
@XmlElementWrapper( name = "gemstones" )
@XmlElement( name = "gemstone", nillable = true )
public List< Gemstone > getGemstoneList( ) {
return gemstoneList;
}
public void setGemstoneList( final List< Gemstone > gemstoneList ) {
this.gemstoneList = gemstoneList;
}
@Override
public boolean equals( final Object o ) {
if ( this == o ) return true;
if ( !( o instanceof Item ) ) return false;
Item item = ( Item ) o;
return Objects.equals( getItemId( ), item.getItemId( ) ) &&
Objects.equals( getItemPrice( ), item.getItemPrice( ) ) &&
Objects.equals( getQuantity( ), item.getQuantity( ) ) &&
Objects.equals( getWeight( ), item.getWeight( ) ) &&
Objects.equals( getItemPriceCurrency( ), item.getItemPriceCurrency( ) ) &&
Objects.equals( getItemName( ), item.getItemName( ) ) &&
Objects.equals( getItemDescription( ), item.getItemDescription( ) ) &&
Objects.equals( getItemType( ), item.getItemType( ) ) &&
Objects.equals( getItemSubType( ), item.getItemSubType( ) ) &&
Objects.equals( getBoughtFrom( ), item.getBoughtFrom( ) ) &&
Objects.equals( getQuantityType( ), item.getQuantityType( ) ) &&
Objects.equals( getWeightedUnit( ), item.getWeightedUnit( ) ) &&
Objects.equals( getBoughtDate( ), item.getBoughtDate( ) ) &&
Objects.equals( getItemImageList( ), item.getItemImageList( ) ) &&
Objects.equals( getItemDiscountList( ), item.getItemDiscountList( ) ) &&
Objects.equals( getGemstoneList( ), item.getGemstoneList( ) ) &&
Objects.equals( getItemOrigin( ), item.getItemOrigin( ) ) &&
Objects.equals( getImageCount( ), item.getImageCount( ) );
}
/**
* Returns a string representation of the object. In general, the {@code toString} method returns a string that
* "textually represents" this object. The result should be a concise but informative representation that is easy
* for a person to read.
*
* @return a string representation of the object.
*/
@Override
public String toString( ) {
return "Item{" +
"itemId=" + itemId +
", itemPrice=" + itemPrice +
", quantity=" + quantity +
", weight=" + weight +
", itemPriceCurrency='" + itemPriceCurrency + '\'' +
", itemName='" + itemName + '\'' +
", itemDescription='" + itemDescription + '\'' +
", itemType='" + itemType + '\'' +
", itemSubType='" + itemSubType + '\'' +
", boughtFrom='" + boughtFrom + '\'' +
", quantityType='" + quantityType + '\'' +
", weightedUnit='" + weightedUnit + '\'' +
", boughtDate=" + boughtDate +
", imageCount=" + imageCount +
", itemImageList=" + itemImageList +
", itemDiscountList=" + itemDiscountList +
'}';
}
} |
Java | public class PdfPage extends PdfObject {
final PdfIndirectObject page;
final PdfIndirectObject contents;
private final PdfStream contentsStream;
final PdfIndirectObject resources;
private final PdfExtGState extGState;
public PdfPage(PdfDocument document, double width, double height) {
PdfDictionary pageDict = new PdfDictionary();
pageDict.dict.put(new PdfName("Type"), new PdfName("Page"));
pageDict.dict.put(new PdfName("Parent"), new PdfIndirectReference(
document.pagesObject));
// PdfDictionary resDict = new PdfDictionary();
// PdfDictionary fontDict = new PdfDictionary();
// fontDict.dict.put(new PdfName("F1"), new
// PdfIndirectReference(fontDefObject));
// resDict.dict.put(new PdfName("Font"), fontDict);
// pageDict.dict.put(new PdfName("Resources"), resDict);
PdfArray mediaBoxArray = new PdfArray();
mediaBoxArray.elements.add(new PdfLong(0));
mediaBoxArray.elements.add(new PdfLong(0));
mediaBoxArray.elements.add(new PdfReal(width));
mediaBoxArray.elements.add(new PdfReal(height));
pageDict.dict.put(new PdfName("MediaBox"), mediaBoxArray);
page = document.constructIndirectObject(pageDict);
contentsStream = new PdfStream();
contents = document.constructIndirectObject(contentsStream);
PdfDictionary pageResources = new PdfDictionary();
extGState = new PdfExtGState();
pageResources.dict.put(new PdfName("ExtGState"), extGState);
resources = document.constructIndirectObject(pageResources);
pageDict.dict.put(new PdfName("Resources"), new PdfIndirectReference(
resources));
pageDict.dict.put(new PdfName("Contents"), new PdfIndirectReference(
contents));
setLineCap(1);
}
void drawLine(double x1, double y1, double x2, double y2) {
contentsStream.content.append(x1).append(" ").append(y1).append(" m ")
.append(x2).append(" ").append(y2).append(" l S\n");
}
void drawStroke(double[] x, double[] y) {
if (x.length != y.length) {
throw new IllegalArgumentException(
"x and y have to be of same length");
}
if (x.length < 2) {
throw new IllegalArgumentException(
"stroke has to have at least two points");
}
contentsStream.content.append(x[0]).append(" ").append(y[0])
.append(" m");
for (int i = 1; i < x.length; i++) {
contentsStream.content.append(" ").append(x[i]).append(" ")
.append(y[i]).append(" l");
}
contentsStream.content.append(" S\n");
}
void drawStrokeVaryingWidth(double[] x, double[] y, double[] widths) { // TODO
// doesn't
// look
// beautiful
if (x.length != y.length) {
throw new IllegalArgumentException(
"x and y have to be of same length");
}
if (x.length < 2) {
throw new IllegalArgumentException(
"stroke has to have at least two points");
}
for (int i = 1; i < x.length; i++) {
if (i - 1 < widths.length) {
setStrokeWidth(widths[i - 1]);
}
drawLine(x[i - 1], y[i - 1], x[i], y[i]);
}
}
void setStrokeWidth(double width) {
contentsStream.content.append(width).append(" w\n");
}
void setStrokeColor(Color color) {
contentsStream.content.append(color.getRed() / 255.0).append(" ")
.append(color.getGreen() / 255.0).append(" ")
.append(color.getBlue() / 255.0).append(" RG\n");
}
void setAlpha(double alpha) {
PdfName alphaName = extGState.getAlpha(alpha);
contentsStream.content.append(alphaName.getName()).append(" gs\n");
}
void setLineCap(int capStyle) {
contentsStream.content.append(capStyle).append(" J\n");
}
@Override
public void render(OutputStreamWriter out) throws IOException {
page.render(out);
out.write("\n");
resources.render(out);
out.write("\n");
contents.render(out);
}
} |
Java | class ConnectionManager {
private final int maxWaitQueueSize;
private final HttpClientMetrics metrics; // Shall be removed later combining the PoolMetrics with HttpClientMetrics
private final HttpClientImpl client;
private final Map<Channel, HttpClientConnection> connectionMap = new ConcurrentHashMap<>();
private final Map<EndpointKey, Endpoint> endpointMap = new ConcurrentHashMap<>();
private final HttpVersion version;
private final long maxSize;
private long timerID;
ConnectionManager(HttpClientImpl client,
HttpClientMetrics metrics,
HttpVersion version,
long maxSize,
int maxWaitQueueSize) {
this.client = client;
this.maxWaitQueueSize = maxWaitQueueSize;
this.metrics = metrics;
this.maxSize = maxSize;
this.version = version;
}
synchronized void start() {
long period = client.getOptions().getPoolCleanerPeriod();
this.timerID = period > 0 ? client.getVertx().setTimer(period, id -> checkExpired(period)) : -1;
}
private synchronized void checkExpired(long period) {
long timestamp = System.currentTimeMillis();
endpointMap.values().forEach(e -> e.pool.closeIdle(timestamp));
timerID = client.getVertx().setTimer(period, id -> checkExpired(period));
}
private static final class EndpointKey {
private final boolean ssl;
private final int port;
private final String peerHost;
private final String host;
EndpointKey(boolean ssl, int port, String peerHost, String host) {
if (host == null) {
throw new NullPointerException("No null host");
}
if (peerHost == null) {
throw new NullPointerException("No null peer host");
}
this.ssl = ssl;
this.peerHost = peerHost;
this.host = host;
this.port = port;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EndpointKey that = (EndpointKey) o;
return ssl == that.ssl && port == that.port && peerHost.equals(that.peerHost) && host.equals(that.host);
}
@Override
public int hashCode() {
int result = ssl ? 1 : 0;
result = 31 * result + peerHost.hashCode();
result = 31 * result + host.hashCode();
result = 31 * result + port;
return result;
}
}
class Endpoint {
private final Pool<HttpClientConnection> pool;
private final Object metric;
public Endpoint(Pool<HttpClientConnection> pool, Object metric) {
this.pool = pool;
this.metric = metric;
}
}
void getConnection(ContextInternal ctx, String peerHost, boolean ssl, int port, String host, Handler<AsyncResult<HttpClientConnection>> handler) {
EndpointKey key = new EndpointKey(ssl, port, peerHost, host);
while (true) {
Endpoint endpoint = endpointMap.computeIfAbsent(key, targetAddress -> {
int maxPoolSize = Math.max(client.getOptions().getMaxPoolSize(), client.getOptions().getHttp2MaxPoolSize());
Object metric = metrics != null ? metrics.createEndpoint(host, port, maxPoolSize) : null;
HttpChannelConnector connector = new HttpChannelConnector(client, metric, version, ssl, peerHost, host, port);
Pool<HttpClientConnection> pool = new Pool<>(connector, maxWaitQueueSize, connector.weight(), maxSize,
v -> {
if (metrics != null) {
metrics.closeEndpoint(host, port, metric);
}
endpointMap.remove(key);
},
connectionMap::put,
connectionMap::remove,
false);
return new Endpoint(pool, metric);
});
Object metric;
if (metrics != null) {
metric = metrics.enqueueRequest(endpoint.metric);
} else {
metric = null;
}
if (endpoint.pool.getConnection(ctx, ar -> {
if (ar.succeeded()) {
HttpClientConnection conn = ar.result();
if (metrics != null) {
metrics.dequeueRequest(endpoint.metric, metric);
}
handler.handle(Future.succeededFuture(conn));
} else {
if (metrics != null) {
metrics.dequeueRequest(endpoint.metric, metric);
}
handler.handle(Future.failedFuture(ar.cause()));
}
})) {
break;
}
}
}
public void close() {
synchronized (this) {
if (timerID >= 0) {
client.getVertx().cancelTimer(timerID);
timerID = -1;
}
}
endpointMap.clear();
for (HttpClientConnection conn : connectionMap.values()) {
conn.close();
}
}
} |
Java | public class ConfigParam implements Serializable {
private static final long serialVersionUID = 3015413596780362259L;
/**
* A name of the parameter
*/
private String name;
/**
* Default value
*/
private String def;
/**
* Parameter type
*/
private ConfigParamType type;
/**
* A short title to display in the configuration snippet
* <pre>
* If not provided <code>name</code> will be used
* </pre>
*/
private String title;
/**
* A help description to show it to the user in tool-tip
*/
private String description;
public ConfigParam() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ConfigParamType getType() {
return type;
}
public void setType(ConfigParamType type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((def == null) ? 0 : def.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ConfigParam other = (ConfigParam) obj;
if (def == null) {
if (other.def != null)
return false;
} else if (!def.equals(other.def))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
if (type != other.type)
return false;
return true;
}
@Override
public String toString() {
return "ConfigParam [name=" + name + ", def=" + def + ", type=" + type + ", title=" + title + ", description="
+ description + "]";
}
} |
Java | abstract class SolrClientFactoryBase implements SolrClientFactory, DisposableBean {
private SolrClient solrClient;
public SolrClientFactoryBase() {
}
SolrClientFactoryBase(SolrClient solrClient) {
this.solrClient = solrClient;
}
protected final boolean isHttpSolrClient(SolrClient solrClient) {
return (solrClient instanceof HttpSolrClient);
}
@Override
public SolrClient getSolrClient() {
return this.solrClient;
}
public void setSolrClient(SolrClient solrClient) {
this.solrClient = solrClient;
}
@Override
public void destroy() {
destroy(this.solrClient);
}
/**
* @param client
*/
protected void destroy(SolrClient client) {
if (client instanceof HttpSolrClient) {
((HttpSolrClient) client).shutdown();
} else if (client instanceof LBHttpSolrClient) {
((LBHttpSolrClient) client).shutdown();
} else {
if (VersionUtil.isSolr4XAvailable()) {
if (client instanceof CloudSolrClient) {
((CloudSolrClient) client).shutdown();
}
}
}
}
} |
Java | public class ServiceLocator implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = -9118735048187674303L;
private InitialContext ic;
public ServiceLocator() throws ServiceLocatorException {
try {
ic = new InitialContext();
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
}
/**
* will get the ejb Local home factory. clients need to cast to the type of
* EJBHome they desire
*
* @return the Local EJB Home corresponding to the homeName
*/
public EJBLocalHome getLocalHome(String jndiHomeName) throws ServiceLocatorException {
EJBLocalHome home = null;
try {
home = (EJBLocalHome) ic.lookup(jndiHomeName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
}
/**
* will get the ejb Remote home factory. clients need to cast to the type of
* EJBHome they desire
*
* @return the EJB Home corresponding to the homeName
*/
public EJBHome getRemoteHome(String jndiHomeName, Class className) throws ServiceLocatorException {
EJBHome home = null;
try {
Object objref = ic.lookup(jndiHomeName);
Object obj = PortableRemoteObject.narrow(objref, className);
home = (EJBHome) obj;
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return home;
}
/**
* @return the factory for the factory to get queue connections from
*/
public QueueConnectionFactory getQueueConnectionFactory(String qConnFactoryName) throws ServiceLocatorException {
QueueConnectionFactory factory = null;
try {
factory = (QueueConnectionFactory) ic.lookup(qConnFactoryName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return factory;
}
/**
* @return the Queue Destination to send messages to
*/
public Queue getQueue(String queueName) throws ServiceLocatorException {
Queue queue = null;
try {
queue = (Queue) ic.lookup(queueName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return queue;
}
/**
* This method helps in obtaining the topic factory
*
* @return the factory for the factory to get topic connections from
*/
public TopicConnectionFactory getTopicConnectionFactory(String topicConnFactoryName) throws ServiceLocatorException {
TopicConnectionFactory factory = null;
try {
factory = (TopicConnectionFactory) ic.lookup(topicConnFactoryName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return factory;
}
/**
* This method obtains the topc itself for event caller
*
* @return the Topic Destination to send messages to
*/
public Topic getTopic(String topicName) throws ServiceLocatorException {
Topic topic = null;
try {
topic = (Topic) ic.lookup(topicName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return topic;
}
/**
* This method obtains the datasource itself for event caller
*
* @return the DataSource corresponding to the name parameter
*/
public DataSource getDataSource(String dataSourceName) throws ServiceLocatorException {
DataSource dataSource = null;
try {
dataSource = (DataSource) ic.lookup(dataSourceName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return dataSource;
}
/**
* @return the URL value corresponding to the env entry name.
*/
public URL getUrl(String envName) throws ServiceLocatorException {
URL url = null;
try {
url = (URL) ic.lookup(envName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return url;
}
/**
* @return the boolean value corresponding to the env entry such as
* SEND_CONFIRMATION_MAIL property.
*/
public boolean getBoolean(String envName) throws ServiceLocatorException {
Boolean bool = null;
try {
bool = (Boolean) ic.lookup(envName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return bool.booleanValue();
}
/**
* @return the String value corresponding to the env entry name.
*/
public String getString(String envName) throws ServiceLocatorException {
String envEntry = null;
try {
envEntry = (String) ic.lookup(envName);
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception e) {
throw new ServiceLocatorException(e);
}
return envEntry;
}
public Object getDAO(String jndiDAOName) throws ServiceLocatorException {
Object object = null;
try {
String className = (String) ic.lookup(jndiDAOName);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
object = classLoader.loadClass(className).newInstance();
} catch (NamingException ne) {
throw new ServiceLocatorException(ne);
} catch (Exception se) {
throw new ServiceLocatorException(se);
}
return object;
}
} |
Java | public class ProcurementAwardBidderController implements Initializable {
@FXML
private TextField fname_txt;
@FXML
private TextField lname_txt;
@FXML
private TextField dateToday_txt;
@FXML
private DatePicker contractEnd_dp;
@FXML
private TextArea remarks_txt;
@FXML
private Label bidderName_txt;
@FXML
private Label bidderRepresentative_txt;
@FXML
private Label bidderContact_txt;
@FXML
private Label bidderEmail_txt;
@FXML
private Label bidderLocation_txt;
@FXML
private Label supplierCount_txt;
@FXML
private Label itemID_txt;
@FXML
private TextField bidderPrice_txt;
@FXML
private Label bidderID_txt;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
displayCurrentDate();
baseSupplierCount();
}
public void displayCurrentDate(){
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
// get current date time with Date()
Date date = new Date();
dateToday_txt.setText(dateFormat.format(date));
}
@FXML
public void award(ActionEvent event) {
String fname = fname_txt.getText();
String lname = lname_txt.getText();
String cEnd = contractEnd_dp.getEditor().getText();
String remarks = remarks_txt.getText();
Boolean flag = fname.isEmpty() || lname.isEmpty() || cEnd.isEmpty() || remarks.isEmpty();
int x = Integer.parseInt(supplierCount_txt.getText());
String suppID = String.valueOf(x+1);
Log1_ProcurementSupplierModel suppDB = new Log1_ProcurementSupplierModel();
Log1_ProcurementPurchaseListModel purchListDB = new Log1_ProcurementPurchaseListModel();
Log1_ProcurementPostedItemStatusModel purchItemStatsDB = new Log1_ProcurementPostedItemStatusModel();
Log1_ProcurementBiddersModel bidderDB = new Log1_ProcurementBiddersModel();
Log1_ProcurementSupplierCountModel supplierCount = new Log1_ProcurementSupplierCountModel();
if(flag){
AlertMaker.showErrorMessage("","Please fill up all the details");
return;
}else{
String[][] supplierData ={
{"SupplierName", bidderName_txt.getText()},
{"SupplierRepresentative", bidderRepresentative_txt.getText()},
{"SupplierContact", bidderContact_txt.getText()},
{"SupplierEmail", bidderEmail_txt.getText()},
{"SupplierLocation", bidderLocation_txt.getText()},
{"ContractStarted", dateToday_txt.getText()},
{"ContractEnd", contractEnd_dp.getEditor().getText()},
{"AwardedBy",fname_txt.getText()+", "+lname_txt.getText()},
{"Remarks",remarks_txt.getText()},
{"SupplierStatus","Active"}
};
String[][] purchItemData ={
{"ItemID", itemID_txt.getText()},
{"SupplierID",suppID},
{"Price", bidderPrice_txt.getText()},
{"Status", "readyForBudgetRequest"}
};
if(suppDB.insert(supplierData) && purchListDB.insert(purchItemData)){
AlertMaker.showSimpleAlert("", "Bidder Awarded!");
purchItemStatsDB.update(new Object[][]{
{"Status", "Supplier Selected"}
}).where(new Object[][]{
{"ItemID", "=", itemID_txt.getText()}
}).executeUpdate();
bidderDB.update(new Object[][]{
{"BidderStatus","Bidder Selected"}
}).where(new Object[][]{
{"BidderID","=",bidderID_txt.getText()}
}).executeUpdate();
supplierCount.update(new Object[][]{
{"SupplierCount", suppID}
}).where(new Object[][]{
{"id", "=", "1"}
}).executeUpdate();
close();
}
}
}
@FXML
private void cancel(ActionEvent event) {
Stage stage = (Stage) dateToday_txt.getScene().getWindow();
stage.close();
}
public void close(){
Stage stage = (Stage) dateToday_txt.getScene().getWindow();
stage.close();
}
public void getBidderName(Log1_ProcurementBiddersClassfiles a) {
bidderName_txt.setText(a.getBidderName());
bidderRepresentative_txt.setText(a.getBidderRepresentative());
bidderContact_txt.setText(a.getBidderContact());
bidderEmail_txt.setText(a.getBidderEmail());
bidderLocation_txt.setText(a.getBidderLocation());
itemID_txt.setText(a.getItemID());
bidderID_txt.setText(a.getBidderID());
bidderPrice_txt.setText(a.getBidderPrice());
if (bidderPrice_txt.getText().isEmpty()) {
bidderPrice_txt.setText("0");
}else{
bidderPrice_txt.setText(NumberFormat.getInstance().format(Long.parseLong(bidderPrice_txt.getText().substring(4).replace(",", ""))));
bidderPrice_txt.end();
}
}
public void baseSupplierCount(){
Log1_ProcurementSupplierCountModel supplierCount = new Log1_ProcurementSupplierCountModel();
List count = supplierCount.get();
count.stream().forEach(row -> {
HashMap hash = (HashMap) row;
supplierCount_txt.setText((String.valueOf(hash.get("SupplierCount"))));
});
}
} |
Java | public class DeployDatabaseCommand extends AbstractCommand implements UndoableCommand {
/**
* Optional XML/JSON file for the database. If set, databaseFilename is ignored.
*/
private File databaseFile;
/**
* Optional XML/JSON filename for the database
*/
private String databaseFilename;
/**
* Provide an easy way of creating a database based on a name without a file being provided. If this is false and
* databaseFilename is null, then no database will be deployed.
*/
private boolean createDatabaseWithoutFile = false;
/**
* The name of the database to be deployed; only needs to be set if the database payload is automatically generated
* instead of being loaded from a file.
*/
private String databaseName;
/**
* If true, this will look for a ./forests/(name of database) directory that defines custom forests for this
* database. If such a directory exists, this command will not create any forests for the database. If the
* directory does not exist, then this command will create forests for the database as defined by forestsPerHost.
*/
private boolean checkForCustomForests = true;
/**
* Optional name of the file in the forests directory that will be used to create each forest. If not provided, a
* "vanilla" forest is created on each host with a name based on the databaseName attribute. This is ignored if
* custom forests are found in ./forests/(name of forest).
*/
private String forestFilename;
/**
* Number of forests to create per host for this database. This is ignored if custom forests are found in
* ./forests/(name of forest).
*/
private int forestsPerHost = 1;
/**
* Passed on to DeployForestsCommand. If forests are to be created, controls whether forests on created on every
* host or only one one host.
*/
@Deprecated
private boolean createForestsOnEachHost = true;
private int undoSortOrder;
private boolean subDatabase = false;
private String superDatabaseName;
/**
* To optimize the creation of forests for many databases, this command can have its forest creation postponed. The
* command will still construct a DeployForestsCommand, which a client is then expected to retrieve later, as that
* command defines all of the forests to be created.
*/
private boolean postponeForestCreation = false;
private DeployForestsCommand deployForestsCommand;
// This is expected to be set via DeployOtherDatabasesCommand
private String payload;
/**
* Expected to be set by DeployOtherDatabasesCommand; a list of database names (should default to the ones MarkLogic
* provides out-of-the-box) that won't be undeployed during an "undo" operation.
*/
private Set<String> databasesToNotUndeploy;
private DeployDatabaseCommandFactory deployDatabaseCommandFactory = new DefaultDeployDatabaseCommandFactory();
public DeployDatabaseCommand() {
setExecuteSortOrder(SortOrderConstants.DEPLOY_OTHER_DATABASES);
setUndoSortOrder(SortOrderConstants.DELETE_OTHER_DATABASES);
setResourceClassType(Database.class);
}
public DeployDatabaseCommand(File databaseFile) {
this();
this.databaseFile = databaseFile;
}
public DeployDatabaseCommand(String databaseFilename) {
this();
this.databaseFilename = databaseFilename;
}
@Override
public String toString() {
if (databaseFile != null) {
return databaseFile.getAbsolutePath();
}
return databaseFilename;
}
@Override
public Integer getUndoSortOrder() {
return undoSortOrder;
}
@Override
public void execute(CommandContext context) {
String payload = buildPayloadForSaving(context);
if (payload != null) {
DatabaseManager dbMgr = new DatabaseManager(context.getManageClient());
databaseName = dbMgr.getResourceId(payload);
dbMgr.save(payload);
DeployForestsCommand tempCommand = buildDeployForestsCommand(databaseName, context);
if (tempCommand != null) {
this.deployForestsCommand = tempCommand;
if (postponeForestCreation) {
logger.info("Postponing creation of forests for database: " + databaseName);
} else {
deployForestsCommand.execute(context);
}
}
deploySubDatabases(this.databaseName, context);
}
}
/**
* If this is not a sub-database, then deploy sub-databases if any have been configured for this database.
*
* @param context
*/
public void deploySubDatabases(String dbName, CommandContext context) {
if (!isSubDatabase()) {
new DeploySubDatabasesCommand(dbName, deployDatabaseCommandFactory).execute(context);
}
}
/**
* Performs all work necessary to construct a payload that can either be saved immediately or included in a CMA
* configuration.
*
* @param context
* @return
*/
public String buildPayloadForSaving(CommandContext context) {
String payload = buildPayload(context);
if (payload != null) {
payload = adjustPayloadBeforeSavingResource(context, null, payload);
}
return payload;
}
/**
* When deleting databases, resource files are not yet merged together first. This should only mean that some
* unnecessary delete calls are made.
*
* @param context
*/
@Override
public void undo(CommandContext context) {
String payload = buildPayload(context);
if (databasesToNotUndeploy != null) {
final String dbName = new PayloadParser().getPayloadFieldValue(payload, "database-name", false);
if (dbName != null && databasesToNotUndeploy.contains(dbName)) {
logger.info(format("Not undeploying database %s because it is in the list of database names to not undeploy.", dbName));
return;
}
}
if (payload != null) {
DatabaseManager dbMgr = newDatabaseManageForDeleting(context);
// if this has sub-databases, detach/delete them first
if (!isSubDatabase()) {
final String dbName = dbMgr.getResourceId(payload);
new DeploySubDatabasesCommand(dbName, deployDatabaseCommandFactory).undo(context);
}
dbMgr.delete(payload);
}
}
/**
* Configures the DatabaseManager in terms of how it deletes forests based on properties in the AppConfig instance
* in the CommandContext.
*
* @param context
* @return
*/
protected DatabaseManager newDatabaseManageForDeleting(CommandContext context) {
DatabaseManager dbMgr = new DatabaseManager(context.getManageClient());
dbMgr.setForestDelete(getForestDeleteLevel(context.getAppConfig()));
dbMgr.setDeleteReplicas(context.getAppConfig().isDeleteReplicas());
return dbMgr;
}
protected String getForestDeleteLevel(AppConfig appConfig) {
return appConfig.isDeleteForests() ? DatabaseManager.DELETE_FOREST_DATA : DatabaseManager.DELETE_FOREST_CONFIGURATION;
}
/**
* Builds the XML or JSON payload for this command, based on the given CommandContext.
*
* @param context
* @return
*/
public String buildPayload(CommandContext context) {
String payload = getPayload(context);
return payload != null ? payloadTokenReplacer.replaceTokens(payload, context.getAppConfig(), false) : null;
}
/**
* Get the payload based on the given CommandContext. Only loads the payload, does not replace any tokens in it.
* Call buildPayload to construct a payload with all tokens replaced.
*
* @param context
* @return
*/
protected String getPayload(CommandContext context) {
if (this.payload != null) {
return payload;
}
File f = null;
if (this.databaseFile != null) {
f = this.databaseFile;
}
else if (databaseFilename != null) {
/**
* This is a little trickier in 3.3.0 - we only have a filename, so need to check every ConfigDir for the
* file. Last one wins.
*/
if (isSubDatabase()) {
for (ConfigDir configDir : context.getAppConfig().getConfigDirs()) {
String subDbFileName = configDir.getDatabasesDir() + File.separator + "subdatabases" + File.separator + this.getSuperDatabaseName() + File.separator + databaseFilename;
File tmpFile = new File(subDbFileName);
if (tmpFile != null && tmpFile.exists()) {
f = tmpFile;
}
}
} else {
for (ConfigDir configDir : context.getAppConfig().getConfigDirs()) {
File dbDir = configDir.getDatabasesDir();
if (dbDir != null && dbDir.exists()) {
File tmpFile = new File(dbDir, databaseFilename);
if (tmpFile != null && tmpFile.exists()) {
f = tmpFile;
}
}
}
}
}
if (f != null && f.exists()) {
return copyFileToString(f);
} else if (createDatabaseWithoutFile) {
return buildDefaultDatabasePayload(context);
} else {
if (logger.isInfoEnabled()) {
logger.info(format("Database file '%s' does not exist, so not executing", databaseFilename));
}
return null;
}
}
/**
* Determines if forests should be created after a database is deployed.
*
* This includes checking to see if a custom forests directory exists at ./forests/(database name). The database
* name is extracted from the payload via a PayloadParser. This check can be disabled by setting
* checkForCustomForests to false.
*
* @param databaseName
* @param context
* @return
*/
protected boolean shouldCreateForests(String databaseName, CommandContext context) {
if (!context.getAppConfig().isCreateForests()) {
if (logger.isInfoEnabled()) {
logger.info("Forest creation is disabled, so not creating any forests");
}
return false;
}
if (isCheckForCustomForests()) {
boolean customForestsDontExist = !customForestsExist(context, databaseName);
if (!customForestsDontExist && logger.isInfoEnabled()) {
logger.info("Found custom forests for database " + databaseName + ", so not creating default forests");
}
return customForestsDontExist;
}
return true;
}
/**
* @param context
* @param dbName
* @return true if any file exists in ./forests/(name of database)
*/
protected boolean customForestsExist(CommandContext context, String dbName) {
for (ConfigDir configDir : context.getAppConfig().getConfigDirs()) {
File dir = configDir.getForestsDir();
if (dir.exists()) {
File dbDir = new File(dir, dbName);
if (dbDir.exists()) {
return dbDir.listFiles().length > 0;
}
}
}
return false;
}
/**
* Initializes an instance of DeployForestsCommand. Public so that it can be accessed by a client that wishes to call
* buildForests on the command.
*
* @param databaseName
* @param context
* @return will return null if it's determined that no forests should be created for the database
*/
public DeployForestsCommand buildDeployForestsCommand(String databaseName, CommandContext context) {
if (shouldCreateForests(databaseName, context)) {
DeployForestsCommand c = new DeployForestsCommand(databaseName);
c.setForestsPerHost(getForestsPerHost());
c.setCreateForestsOnEachHost(createForestsOnEachHost);
c.setForestFilename(forestFilename);
return c;
}
return null;
}
protected String buildDefaultDatabasePayload(CommandContext context) {
return format("{\"database-name\": \"%s\"}", databaseName);
}
public int getForestsPerHost() {
return forestsPerHost;
}
public void setForestsPerHost(int forestsPerHost) {
this.forestsPerHost = forestsPerHost;
}
public String getForestFilename() {
return forestFilename;
}
public void setForestFilename(String forestFilename) {
this.forestFilename = forestFilename;
}
public void setUndoSortOrder(int undoSortOrder) {
this.undoSortOrder = undoSortOrder;
}
public String getDatabaseFilename() {
return databaseFilename;
}
public void setDatabaseFilename(String databaseFilename) {
this.databaseFilename = databaseFilename;
}
public boolean isCreateDatabaseWithoutFile() {
return createDatabaseWithoutFile;
}
public void setCreateDatabaseWithoutFile(boolean createDatabaseWithoutFile) {
this.createDatabaseWithoutFile = createDatabaseWithoutFile;
}
public String getDatabaseName() {
return databaseName;
}
public void setDatabaseName(String databaseName) {
this.databaseName = databaseName;
}
@Deprecated
public boolean isCreateForestsOnEachHost() {
return createForestsOnEachHost;
}
/**
* Use appConfig.setDatabasesWithForestsOnOneHost
* @param createForestsOnEachHost
*/
@Deprecated
public void setCreateForestsOnEachHost(boolean createForestsOnEachHost) {
this.createForestsOnEachHost = createForestsOnEachHost;
}
public boolean isCheckForCustomForests() {
return checkForCustomForests;
}
public void setCheckForCustomForests(boolean checkForCustomForests) {
this.checkForCustomForests = checkForCustomForests;
}
public void setSubDatabase(boolean isSubDatabase){
this.subDatabase = isSubDatabase;
}
public boolean isSubDatabase() {
return this.subDatabase;
}
public void setSuperDatabaseName(String name){
this.superDatabaseName = name;
}
public String getSuperDatabaseName() {
return this.superDatabaseName;
}
public void setDatabaseFile(File databaseFile) {
this.databaseFile = databaseFile;
}
public Set<String> getDatabasesToNotUndeploy() {
return databasesToNotUndeploy;
}
public void setDatabasesToNotUndeploy(Set<String> databasesToNotUndeploy) {
this.databasesToNotUndeploy = databasesToNotUndeploy;
}
public void setDeployDatabaseCommandFactory(DeployDatabaseCommandFactory deployDatabaseCommandFactory) {
this.deployDatabaseCommandFactory = deployDatabaseCommandFactory;
}
public void setPostponeForestCreation(boolean postponeForestCreation) {
this.postponeForestCreation = postponeForestCreation;
}
public boolean isPostponeForestCreation() {
return postponeForestCreation;
}
public DeployForestsCommand getDeployForestsCommand() {
return deployForestsCommand;
}
public void setPayload(String payload) {
this.payload = payload;
}
} |
Java | public class XmlReaderTest {
@Test
public void testReader() {
assumeFalse(GraphicsEnvironment.isHeadless());
final SortableDefaultMutableTreeNode rootNode = new SortableDefaultMutableTreeNode();
URL image = XmlReaderTest.class.getClassLoader().getResource( "exif-test-canon-eos-350d.jpg" );
File imageFile = null;
try {
imageFile = new File( Objects.requireNonNull(image).toURI() );
} catch ( URISyntaxException | NullPointerException ex ) {
Logger.getLogger( XmlReaderTest.class.getName() ).log( Level.SEVERE, null, ex );
fail( "Could not create imageFile" );
}
final PictureInfo pi = new PictureInfo( imageFile, "First Picture" );
final SortableDefaultMutableTreeNode picture1 = new SortableDefaultMutableTreeNode( pi );
rootNode.add( picture1 );
assertEquals( ( (PictureInfo) picture1.getUserObject() ).getImageFile().getName(), pi.getImageFile().getName() );
}
} |
Java | public class OneTimePasswordService {
private int otpDigits;
private String otpAlgorithm;
private int preStepsWindow;
private int postStepsWindow;
private Base32 base32 = new Base32();
protected final Logger logger = LoggerFactory.getLogger(getClass());
public boolean isPasswordValid(String presentedPassword, String secretKey) {
byte[] decodedSecretKey = base32.decode(secretKey);
String hexDecodedSecretKey = EncodingGroovyMethods.encodeHex(decodedSecretKey).toString();
int currentTimeSteps = stepsForUnixTime(System.currentTimeMillis());
int validWindowStart = currentTimeSteps - preStepsWindow;
int validWindowEnd = currentTimeSteps + postStepsWindow;
logger.debug("validating OTP in the window: {}..{}", new Object[] { validWindowStart, validWindowEnd });
for (int steps = validWindowStart; steps <= validWindowEnd; steps++) {
if (TOTP.generateTOTP(
hexDecodedSecretKey,
toStepsTimeHex(steps),
String.valueOf(otpDigits),
otpAlgorithm).equals(presentedPassword)) {
return true;
}
}
return false;
}
public void setOtpDigits(int otpDigits) {
this.otpDigits = otpDigits;
}
public void setOtpAlgorithm(String otpAlgorithm) {
this.otpAlgorithm = otpAlgorithm;
}
public void setPreStepsWindow(int preStepsWindow) {
this.preStepsWindow = preStepsWindow;
}
public void setPostStepsWindow(int postStepsWindow) {
this.postStepsWindow = postStepsWindow;
}
private int stepsForUnixTime(long unixTimeInMillis) {
return (int)(unixTimeInMillis / 1000 / 30);
}
private String toStepsTimeHex(int stepTime) {
String steps = Long.toHexString(stepTime).toUpperCase();
while (steps.length() < 16) {
steps = "0" + steps;
}
return steps;
}
} |
Java | public class GT
extends BinaryExp {
public GT(final Expression e1, final Expression e2) {
super(e1, e2);
returnType = Boolean.class;
}
public String toString() {
return "(> " + e1 + " " + e2 + ")";
}
public void compile(final MethodVisitor mv) {
writeLineInfo(mv);
// compiles e1, e2, and adds the instructions to compare the two values
e1.compile(mv);
if (useBigIntArithmetics()) {
mv.visitTypeInsn(CHECKCAST, "java/math/BigInteger");
}
else {
mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
}
e2.compile(mv);
if (useBigIntArithmetics()) {
mv.visitTypeInsn(CHECKCAST, "java/math/BigInteger");
}
else {
mv.visitTypeInsn(CHECKCAST, "java/lang/Integer");
mv.visitMethodInsn(INVOKEVIRTUAL, "java/lang/Integer", "intValue", "()I");
}
Label iftrue = new Label();
Label end = new Label();
if (useBigIntArithmetics()) {
mv.visitMethodInsn(INVOKEVIRTUAL, "java/math/BigInteger", "compareTo", "(Ljava/math/BigInteger;)I");
mv.visitJumpInsn(IFGT, iftrue);
}
else {
mv.visitJumpInsn(IF_ICMPGT, iftrue);
}
// case where !(e1 >= e2) : pushes false and jump to "end"
mv.visitTypeInsn(NEW, "java/lang/Boolean");
mv.visitInsn(DUP);
mv.visitInsn(ICONST_0);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Boolean", "<init>", "(Z)V");
mv.visitJumpInsn(GOTO, end);
// case where e1 >= e2 : pushes true
mv.visitLabel(iftrue);
mv.visitTypeInsn(NEW, "java/lang/Boolean");
mv.visitInsn(DUP);
mv.visitInsn(ICONST_1);
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Boolean", "<init>", "(Z)V");
mv.visitLabel(end);
}
} |
Java | public class HypoMagFreqDistAtLoc extends MagFreqDistsForFocalMechs implements java.io.Serializable{
private Location location;
/**
* Class Constructor.
* In this case the no focalMechanisms are specified.
* @param magDist IncrementalMagFreqDist[] list of MagFreqDist for the given location.
* @param loc Location
*/
public HypoMagFreqDistAtLoc(IncrementalMagFreqDist[] magDist, Location loc) {
super(magDist);
location = loc;
}
/**
* Class Constructor.
* This is for passing in a single magFreqDist (don't have to create an array) and no focal mechanism.
* @param magDist IncrementalMagFreqDist MagFreqDist for the given location.
* @param loc Location
*/
public HypoMagFreqDistAtLoc(IncrementalMagFreqDist magDist, Location loc) {
super(magDist);
location = loc;
}
/**
* Class constructor.
* This constructor allows user to give a list of focalMechanisms for a given location.
* @param magDist IncrementalMagFreqDist[] list of magFreqDist, same as number of focal mechanisms.
* @param loc Location Location
* @param focalMechanism FocalMechanism[] list of focal mechanism for a given location.
*
*/
public HypoMagFreqDistAtLoc(IncrementalMagFreqDist[] magDist, Location loc,
FocalMechanism[] focalMechanism) {
super(magDist, focalMechanism);
location = loc;
}
/**
* Class constructor.
* This constructor allows user to give a single magDist and focalMechanism for a given location.
* @param magDist IncrementalMagFreqDist
* @param loc Location Location
* @param focalMechanism FocalMechanism
*
*/
public HypoMagFreqDistAtLoc(IncrementalMagFreqDist magDist, Location loc, FocalMechanism focalMech) {
super(magDist,focalMech);
location = loc;
}
/**
* Returns the Location at which MagFreqDist(s) is calculated.
* @return Location
*/
public Location getLocation() {
return location;
}
} |
Java | public class OnBoardNotification {
private float x;
private float y;
private int speed;
private int textSize;
private int color;
private Context context;
private FrameLayout layout;
private TextView notificationHolder;
public OnBoardNotification(Context context){
this.context = context;
this.setHolder();
this.setLayout();
}
public OnBoardNotification(Context context,float x, float y){
this(context);
this.x = x;
this.y = y;
this.color = R.color.white;
}
public void setX(float x){this.x = x;}
public void setY(float y){this.y = y;}
public void setColor(int color){this.color = color;}
public void setSpeed(int speed){this.speed = speed;}
public void notify(String message, int color){
this.color = color;
this.execute(message, false);
}
public void notify(String message, int speed, int textSize, boolean center){
this.speed = speed;
this.textSize = textSize;
this.execute(message, center);
}
private void setLayout(){
this.layout = (FrameLayout)((Activity)this.context).findViewById(R.id.gameBoardLayout);
}
private void setHolder(){
this.notificationHolder = new TextView(this.context);
}
private void execute(String message, boolean center){
this.removeHolder();
this.layout.addView(notificationHolder);
this.setHolderProperties();
this.notificationHolder.setText(message);
this.setHolderCoordinates(center);
this.animateHolder();
}
private void setHolderCoordinates(boolean center){
if(center){
this.notificationHolder.measure(0, 0);
int width = this.notificationHolder.getMeasuredWidth();
this.notificationHolder.setX(this.x - (width/2));
}else{
this.notificationHolder.setX(this.x);
}
this.notificationHolder.setY(this.y);
}
private void setHolderProperties(){
this.notificationHolder.setTextSize(this.textSize);
this.notificationHolder.setShadowLayer(1.5f, 0, 0, Color.parseColor("#2F2F2F"));
this.notificationHolder.setTextColor(this.context.getResources().getColor(this.color));
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void animateHolder(){
this.notificationHolder.animate()
.alpha(0.f)
.scaleX(1.f).scaleY(1.2f)
.setDuration(this.speed)
.withEndAction(new Runnable() {
@Override
public void run() {
notificationHolder.setAlpha(1.f);
notificationHolder.setScaleX(1.f);
notificationHolder.setScaleY(1.f);
removeHolder();
}
})
.start();
}
private void removeHolder(){
if(this.layout.indexOfChild(notificationHolder) > -1){
this.layout.removeView(notificationHolder);
}
}
} |
Java | public final class ConnectionMap {
// https://www.cisco.com/c/en/us/td/docs/security/asa/syslog/b_syslog/syslogs3.html
// %ASA-6-302013: Built {inbound|outbound} TCP connection
// %ASA-6-302014: Teardown TCP connection
// %ASA-6-302015: Built {inbound|outbound} UDP connection
// %ASA-6-302016: Teardown UDP connection
private static final String OPEN = ".*30201[35].+outside:(.+?)/.*";
private static final String CLOSE = ".*30201[46].+outside:(.+?)/.*";
private static final Pattern OPEN_PATTERN = Pattern.compile(OPEN);
private static final Pattern CLOSE_PATTERN = Pattern.compile(CLOSE);
protected static final int WIDTH = 360 * 2;
protected static final int HEIGHT = 180 * 2;
private static int GREEN = 0xff006000;
private final Object lock = new Object();
private final Queue<String> queue = new LinkedList<>();
private final DatabaseReader reader;
private final Thread syslogMulticastThread, syslogUnicastThread;
private final Thread parseThread;
private final Map<Map.Entry<Integer,Integer>, Integer> map;
/**
* See https://twitter.com/wjholdentech/status/1169124304501563394.
*
* You can find the original "bw.jpeg" file that I started with in the project
* resources. Here are the Julia commands I used to generate these files:
*
* <pre>
* {@code
* using FileIO,Images,StatsBase
*
* # Start with a 720x360 grayscale equirectangular world map (white = water)
* bw = load("bw.jpeg")
*
* # Verify that it fits in 720x360
* size(bw)
*
* # Observe that we do not have the true black/white pixels we expected
* countmap(bw)
*
* # The pixels are grayscale, with values between 0 and 1. Round them off.
* bw_rounded = round.(bw)
* countmap(bw_rounded)
*
* # Get the indices of the non-white pixels, subtract one, and store as "x y" strings.
* land = map(p -> string((p[2]-1)," ",(p[1]-1)), findall(x -> x != Gray{N0f8}(1.0), bw_rounded))
*
* # Output the CSV as text
* out = open("earth.txt","w")
* foreach(line -> println(out, line), land)
* close(out)
* }
* </pre>
*/
private final List<List<Integer>> earth = new ArrayList<>();
/**
* This is a useless "feature" that I wanted to leave in for fun.
* To add a map of the earth I scraped an "equirectangular" map from
* Wikipedia. I knew the map wasn't grayscale, so I used a quick Julia
* program to coerce grayscale. To my disappointment, either Julia or
* Gimp interpolated gray colors anyways, so I ended up with a map of the
* earth with either too much land or too much water. You can press the
* numbers 1, 2, and 3 on the keyboard to select which map you want.
* 1 has too much land, 2 has too much water, and 3 is "just right" where
* I rounded the grayscale pixels back to what they were supposed to be.
*/
protected static int EARTH = 2;
int xoffset = 0;
int yoffset = 0;
// The magic numbers +20 and +1 are to correct a data problem. The
// pixels of the map are not correctly aligned with true lines of
// latitude and longitude. Change these constants if using a different map.
static int mapxoffset = 20;
static int mapyoffset = 1;
public void start() {
syslogMulticastThread.start();
//syslogUnicastThread.start();
parseThread.start();
}
private void increment(Map.Entry<Integer,Integer> location) {
int value = 1;
if (map.containsKey(location)) {
value += map.get(location);
}
map.put(location, value);
}
private void decrement(Map.Entry<Integer,Integer> location) {
if (map.containsKey(location)) {
int value = map.get(location);
if (value == 1) {
map.remove(location);
} else {
map.put(location, value - 1);
}
}
}
public ConnectionMap() throws URISyntaxException, IOException {
//URL url = getClass().getResource("/resources/GeoLite2-City.mmdb");
//File database = new File(url.toURI());
//reader = new DatabaseReader.Builder(database).build();
reader = new DatabaseReader.Builder(getClass().getResourceAsStream("/resources/GeoLite2-City.mmdb")).build();
map = new ConcurrentHashMap<>();
syslogMulticastThread = new Thread(new MulticastSyslogListener("239.5.1.4", 514, queue, lock));
syslogMulticastThread.setDaemon(false);
syslogUnicastThread = new Thread(new UnicastSyslogListener(514, queue, lock));
syslogUnicastThread.setDaemon(true);
parseThread = new Thread(() -> {
while (true) {
synchronized(lock) {
try {
lock.wait();
while (!queue.isEmpty()) {
String line = queue.remove();
Matcher openMatcher = OPEN_PATTERN.matcher(line);
if (openMatcher.matches()) {
Map.Entry<Integer,Integer> location = classify(getLocation(openMatcher.group(1)));
if (location != null) {
increment(location);
}
} else {
Matcher closeMatcher = CLOSE_PATTERN.matcher(line);
if (closeMatcher.matches()) {
Map.Entry<Integer,Integer> location = classify(getLocation(closeMatcher.group(1)));
decrement(location);
}
}
}
} catch (InterruptedException ex) {
System.err.println(ex);
return;
} catch (GeoIp2Exception ex) {
System.err.println(ex);
}
}
}
});
parseThread.setDaemon(true);
earth.add(readMap("/resources/earth1.txt"));
earth.add(readMap("/resources/earth2.txt"));
earth.add(readMap("/resources/earth3.txt"));
}
/**
* Read a list of space-separated (x,y) coordinates from the earth.txt file
* included as a project resource. Each (x,y) coordinate pair is composed into
* a single integer. The 16 most significant bits represent x and the 16
* least significant bits represent y. Thus, a different input file can be
* used for resolutions up to 65536x65536 (!!!) without any code changes.
*
* It is expected that the (x,y) coordinates are presented in the same domain
* that this program renders output. Each pixel is considered "land", and each
* pixel not presented is not considered land. Thus, the GUI needs only iterate
* over all coordinates presented and color the corresponding pixel green.
*
* @return an immutable set of integers that are the composition of (x,y)
* coordinates in the GUI's pixel space representing land.
*/
private List<Integer> readMap(String resource) {
final List<Integer> e = new ArrayList<>();
Scanner sc = new Scanner(getClass().getResourceAsStream(resource));
while (sc.hasNextInt()) {
final int x = sc.nextInt();
final int y = sc.nextInt();
e.add((x << 16) | y);
}
return Collections.unmodifiableList(e);
}
private double[] getLocation(String address) throws GeoIp2Exception {
try {
InetAddress ipAddress = InetAddress.getByName(address);
CityResponse response = reader.city(ipAddress);
Location location = response.getLocation();
return new double[] { location.getLatitude(), location.getLongitude() };
} catch (IOException ex) {
return null;
}
}
private Map.Entry<Integer,Integer> classify(double[] location) {
Integer latitude = (int)Math.round(location[0] + 90) * HEIGHT / 180;
Integer longitude = (int)Math.round(location[1] + 180) * WIDTH / 360;
return new AbstractMap.SimpleImmutableEntry<>(longitude, latitude);
}
public static void main(String[] args) throws UnknownHostException, URISyntaxException, IOException {
ConnectionMap fireGuard = new ConnectionMap();
fireGuard.start();
}
public BufferedImage renderImage() {
final BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB);
earth.get(EARTH).forEach(pixel -> {
final int x = pixel >> 16;
final int y = pixel & 0x0000ffff;
// I was surprised to learn that the alpha channel actually comes first.
// The bytes of the integer are AA|RR|GG|BB.
image.setRGB((x + xoffset + mapxoffset) % WIDTH, (y + yoffset - mapyoffset) % HEIGHT, ConnectionMap.GREEN);
});
if (!map.isEmpty()) {
// yeah I hate it too, but we need to normalize values relative to each other.
// int max = Collections.max(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue)).getValue();
map.forEach((location, intensity) -> {
// The heat map idea didn't work as well as I had hoped. For now,
// this is just a simple white/black map of pixels.
final int x = location.getKey();
final int y = ConnectionMap.HEIGHT - location.getValue();
image.setRGB((x + xoffset) % WIDTH, (y + yoffset) % HEIGHT, 0xffffffff);
});
}
return image;
}
protected static void moreGreen() {
int g = (GREEN & 0x0000ff00) >>> 8;
if (g < 0xff) {
GREEN = 0xff000000 | ((g + 1) << 8);
}
}
protected static void lessGreen() {
int g = (GREEN & 0x0000ff00) >>> 8;
if (g > 0) {
GREEN = 0xff000000 | ((g - 1) << 8);
}
}
protected static void mapOffsetX(int dx) {
mapxoffset += dx;
}
protected static void mapOffsetY(int dy) {
mapyoffset += dy;
}
} |
Java | public class SleepingJobletHandler extends BaseHandler{
private static final String TITLE = "Create Sleeping Joblets";
private static final String P_numJoblets = "numJoblets";
private static final String P_sleepMs = "sleepMs";
private static final String P_executionOrder = "executionOrder";
private static final String P_includeFailures = "includeFailures";
private static final String P_failEveryN = "failEveryN";
private static final String P_submitAction = "submitAction";
@Inject
private JobletService jobletService;
@Inject
private JobletPageFactory pageFactory;
@Handler(defaultHandler = true)
private Mav createSleepingJoblets(
@Param(P_numJoblets) OptionalInteger numJoblets,
@Param(P_sleepMs) OptionalLong sleepMs,
@Param(P_executionOrder) OptionalInteger executionOrder,
@Param(P_includeFailures) OptionalBoolean includeFailures,
@Param(P_failEveryN) OptionalInteger failEveryN,
@Param(P_submitAction) OptionalString submitAction){
var form = new HtmlForm()
.withMethod("post");
form.addTextField()
.withDisplay("Number of Joblets")
.withName(P_numJoblets)
.withPlaceholder("1000")
.withValue(numJoblets.map(Object::toString).orElse(1000 + ""));
form.addTextField()
.withDisplay("Sleep Millis")
.withName(P_sleepMs)
.withPlaceholder("1000")
.withValue(sleepMs.map(Object::toString).orElse(1000 + ""));
form.addTextField()
.withDisplay("Execution Order")
.withName(P_executionOrder)
.withPlaceholder(JobletPriority.DEFAULT.getExecutionOrder() + "")
.withValue(executionOrder
.map(Object::toString)
.orElse(JobletPriority.DEFAULT.getExecutionOrder() + ""));
form.addCheckboxField()
.withDisplay("Include Failures")
.withName(P_includeFailures)
.withChecked(includeFailures.orElse(true));
form.addTextField()
.withDisplay("Fail Every N")
.withName(P_failEveryN)
.withPlaceholder(100 + "")
.withValue(failEveryN.map(Object::toString).orElse(100 + ""));
form.addButton()
.withDisplay("Create Joblets")
.withValue("anything");
if(submitAction.isEmpty() || form.hasErrors()){
return pageFactory.startBuilder(request)
.withTitle(TITLE)
.withContent(makeContent(form))
.buildMav();
}
JobletPriority priority = JobletPriority.fromExecutionOrder(executionOrder.get());
List<JobletPackage> jobletPackages = new ArrayList<>();
for(int i = 0; i < numJoblets.get(); ++i){
int numFailuresForThisJoblet = 0;
if(includeFailures.orElse(false)){
boolean failThisJoblet = i % failEveryN.orElse(10) == 0;
if(failThisJoblet){
numFailuresForThisJoblet = JobletRequest.MAX_FAILURES + 3;//+3 to see if it causes a problem
}
}
SleepingJobletParams params = new SleepingJobletParams(String.valueOf(i), sleepMs.get(),
numFailuresForThisJoblet);
int batchSequence = i;//specify this so joblets execute in precise order
JobletPackage jobletPackage = JobletPackage.createDetailed(SleepingJoblet.JOBLET_TYPE, priority, Instant
.now(), batchSequence, true, null, null, params);
jobletPackages.add(jobletPackage);
}
jobletService.submitJobletPackages(jobletPackages);
return pageFactory.message(request, String.format("created %s @%s ms each", numJoblets.get(), sleepMs.get()));
}
public ContainerTag<?> makeContent(HtmlForm htmlForm){
var form = Bootstrap4FormHtml.render(htmlForm)
.withClass("card card-body bg-light");
return div(TagCreator.h4(TITLE), form)
.withClass("container my-3");
}
} |
Java | public class FreshnessApf implements AnnotationProcessorFactory {
// Process any set of annotations
private static final Collection<String> supportedAnnotations
= unmodifiableCollection(Arrays.asList("*"));
// No supported options
private static final Collection<String> supportedOptions = emptySet();
public Collection<String> supportedAnnotationTypes() {
return supportedAnnotations;
}
public Collection<String> supportedOptions() {
return supportedOptions;
}
public AnnotationProcessor getProcessorFor(
Set<AnnotationTypeDeclaration> atds,
AnnotationProcessorEnvironment env) {
return new FreshnessAp(env);
}
private static class FreshnessAp implements AnnotationProcessor {
private final AnnotationProcessorEnvironment env;
FreshnessAp(AnnotationProcessorEnvironment env) {
this.env = env;
}
public void process() {
System.out.println("Testing for freshness.");
boolean empty = true;
for (TypeDeclaration typeDecl : env.getSpecifiedTypeDeclarations()) {
for (FieldDeclaration fieldDecl: typeDecl.getFields() ) {
empty = false;
System.out.println(typeDecl.getQualifiedName() +
"." + fieldDecl.getSimpleName());
// Verify the declaration for the type of the
// field is a class with an annotation.
System.out.println(((DeclaredType) fieldDecl.getType()).getDeclaration().getAnnotationMirrors());
if (((DeclaredType) fieldDecl.getType()).getDeclaration().getAnnotationMirrors().size() == 0)
env.getMessager().printError("Expected an annotation.");
}
}
if (empty)
env.getMessager().printError("No fields encountered.");
}
}
} |
Java | public abstract class ConfigModelRegistry {
private final ConfigModelRegistry chained;
public ConfigModelRegistry() {
this(new EmptyTerminalRegistry());
}
/** Creates a config model class registry which forwards unresolved requests to the argument instance */
public ConfigModelRegistry(ConfigModelRegistry chained) {
this.chained=chained;
}
/**
* Returns the builders this id resolves to both in this and any chained registry.
*
* @return the resolved config model builders, or an empty list (never null) if none
*/
public abstract Collection<ConfigModelBuilder> resolve(ConfigModelId id);
public ConfigModelRegistry chained() { return chained; }
/** An empty registry which does not support chaining */
private static class EmptyTerminalRegistry extends ConfigModelRegistry {
public EmptyTerminalRegistry() {
super(null);
}
@Override
public Collection<ConfigModelBuilder> resolve(ConfigModelId id) {
return Collections.emptyList();
}
}
} |
Java | private static class EmptyTerminalRegistry extends ConfigModelRegistry {
public EmptyTerminalRegistry() {
super(null);
}
@Override
public Collection<ConfigModelBuilder> resolve(ConfigModelId id) {
return Collections.emptyList();
}
} |
Java | public class PlayModeCommandHandler implements CommandHandler {
private HistoryChannelController history;
public PlayModeCommandHandler(HistoryChannelController history){
this.history = history;
}
public void handleCommand(GameplayActionCommand gac) {
gac.execute();
history.addCommand(gac);
}
} |
Java | public class TravelAdviceDetail {
public String Id;
public String Type;
public String Canonical;
public String DataURL;
public String Title;
public String Introduction;
public String Location;
public String Modifications;
public ContentParagraph[] Content;
public String[] Authorities;
public String[] Creators;
public Date LastModified;
public Date Available;
public String License;
public String[] RightsHolders;
public String Language;
public String Subject;
public String[] Themes;
public TravelAdviceDetail(JSONObject obj) throws JSONException, ParseException {
this.Id = obj.getString("id");
this.Type = obj.getString("type");
this.Canonical = obj.getString("canonical");
this.DataURL = obj.getString("dataurl");
this.Title = obj.getString("title");
this.Introduction = obj.getString("introduction");
this.Location = obj.getString("location");
this.Modifications = obj.getString("modifications");
this.LastModified = Helper.parseISO8601(obj.getString("lastmodified"));
this.Available = Helper.parseISO8601(obj.getString("available"));
this.License = obj.getString("license");
this.Language = obj.getString("language");
this.Subject = obj.getString("subject");
JSONArray content, authorities, creators, rightsholders, themes;
content = obj.getJSONArray("content");
authorities = obj.getJSONArray("authorities");
creators = obj.getJSONArray("creators");
rightsholders = obj.getJSONArray("rightsholders");
themes = obj.getJSONArray("themes");
this.Content = new ContentParagraph[content.length()];
for (int i = 0; i < content.length(); i++) {
this.Content[i] = new ContentParagraph(content.getJSONObject(i));
}
this.Authorities = new String[authorities.length()];
for (int i = 0; i < authorities.length(); i++) {
this.Authorities[i] = authorities.getString(i);
}
this.Creators = new String[creators.length()];
for (int i = 0; i < creators.length(); i++) {
this.Creators[i] = creators.getString(i);
}
this.RightsHolders = new String[rightsholders.length()];
for (int i = 0; i < rightsholders.length(); i++) {
this.RightsHolders[i] = rightsholders.getString(i);
}
this.Themes = new String[themes.length()];
for (int i = 0; i < themes.length(); i++) {
this.Themes[i] = themes.getString(i);
}
}
public class ContentParagraph {
public String ParagraphTitle = null;
public String Summary = null;
public String Paragraph = null;
public ContentParagraph(JSONObject obj) throws JSONException {
if (obj.has("paragraphtitle")) {
this.ParagraphTitle = obj.getString("paragraphtitle");
}
if (obj.has("summary")) {
this.ParagraphTitle = obj.getString("summary");
}
if (obj.has("paragraph")) {
this.ParagraphTitle = obj.getString("paragraph");
}
}
}
} |
Java | public class SensorLatitude extends UasDatalinkLatitude {
/**
* Create from value.
*
* @param degrees Latitude, in degrees [-90,90], or {@code Double.POSITIVE_INFINITY} to
* represent an error condition
*/
public SensorLatitude(double degrees) {
super(degrees);
}
/**
* Create from encoded bytes.
*
* @param bytes Latitude, encoded as a 4-byte int
*/
public SensorLatitude(byte[] bytes) {
super(bytes);
}
@Override
public String getDisplayName() {
return "Sensor Latitude";
}
} |
Java | @SuppressWarnings({"serial", "unchecked"})
public abstract class BaseReportTigerMappingInfo<M extends BaseReportTigerMappingInfo<M>> extends ModelExt<M> implements IBean {
public M setId(java.math.BigInteger id) {
set("id", id);
return (M)this;
}
public java.math.BigInteger getId() {
return get("id");
}
public M setAppid(java.math.BigInteger appid) {
set("appid", appid);
return (M)this;
}
public java.math.BigInteger getAppid() {
return get("appid");
}
public M setCode(java.lang.String code) {
set("code", code);
return (M)this;
}
public java.lang.String getCode() {
return getStr("code");
}
public M setIntro(java.lang.String intro) {
set("intro", intro);
return (M)this;
}
public java.lang.String getIntro() {
return getStr("intro");
}
public M setCdate(java.math.BigInteger cdate) {
set("cdate", cdate);
return (M)this;
}
public java.math.BigInteger getCdate() {
return get("cdate");
}
} |
Java | public class MultipleComponentParameter implements IMultipleComponentParameter {
String sourceComponent;
String targetComponent;
String sourceValue;
String targetValue;
public MultipleComponentParameter(String source, String target) {
this(source, target, ".");
}
public MultipleComponentParameter(String source, String target, String seperator) {
StringTokenizer token = new StringTokenizer(source, seperator);
sourceComponent = token.nextToken();
sourceValue = token.nextToken();
token = new StringTokenizer(target, seperator);
targetComponent = token.nextToken();
targetValue = token.nextToken();
}
/*
* (non-Javadoc)
*
* @see org.talend.designer.core.model.components.IMultipleComponentParameter#getSourceComponent()
*/
public String getSourceComponent() {
return this.sourceComponent;
}
/*
* (non-Javadoc)
*
* @see org.talend.designer.core.model.components.IMultipleComponentParameter#getSourceValue()
*/
public String getSourceValue() {
return this.sourceValue;
}
/*
* (non-Javadoc)
*
* @see org.talend.designer.core.model.components.IMultipleComponentParameter#getTargetComponent()
*/
public String getTargetComponent() {
return this.targetComponent;
}
/*
* (non-Javadoc)
*
* @see org.talend.designer.core.model.components.IMultipleComponentParameter#getTargetValue()
*/
public String getTargetValue() {
return this.targetValue;
}
} |
Subsets and Splits