code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.email.provider;
import com.android.emailcommon.Logging;
import com.android.emailcommon.internet.MimeUtility;
import com.android.emailcommon.provider.EmailContent;
import com.android.emailcommon.provider.EmailContent.Attachment;
import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
import com.android.emailcommon.utility.AttachmentUtilities;
import com.android.emailcommon.utility.AttachmentUtilities.Columns;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/*
* A simple ContentProvider that allows file access to Email's attachments.
*
* The URI scheme is as follows. For raw file access:
* content://com.android.email.attachmentprovider/acct#/attach#/RAW
*
* And for access to thumbnails:
* content://com.android.email.attachmentprovider/acct#/attach#/THUMBNAIL/width#/height#
*
* The on-disk (storage) schema is as follows.
*
* Attachments are stored at: <database-path>/account#.db_att/item#
* Thumbnails are stored at: <cache-path>/thmb_account#_item#
*
* Using the standard application context, account #10 and attachment # 20, this would be:
* /data/data/com.android.email/databases/10.db_att/20
* /data/data/com.android.email/cache/thmb_10_20
*/
public class AttachmentProvider extends ContentProvider {
private static final String[] MIME_TYPE_PROJECTION = new String[] {
AttachmentColumns.MIME_TYPE, AttachmentColumns.FILENAME };
private static final int MIME_TYPE_COLUMN_MIME_TYPE = 0;
private static final int MIME_TYPE_COLUMN_FILENAME = 1;
private static final String[] PROJECTION_QUERY = new String[] { AttachmentColumns.FILENAME,
AttachmentColumns.SIZE, AttachmentColumns.CONTENT_URI };
@Override
public boolean onCreate() {
/*
* We use the cache dir as a temporary directory (since Android doesn't give us one) so
* on startup we'll clean up any .tmp files from the last run.
*/
File[] files = getContext().getCacheDir().listFiles();
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".tmp") || filename.startsWith("thmb_")) {
file.delete();
}
}
return true;
}
/**
* Returns the mime type for a given attachment. There are three possible results:
* - If thumbnail Uri, always returns "image/png" (even if there's no attachment)
* - If the attachment does not exist, returns null
* - Returns the mime type of the attachment
*/
@Override
public String getType(Uri uri) {
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
return "image/png";
} else {
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, MIME_TYPE_PROJECTION, null,
null, null);
try {
if (c.moveToFirst()) {
String mimeType = c.getString(MIME_TYPE_COLUMN_MIME_TYPE);
String fileName = c.getString(MIME_TYPE_COLUMN_FILENAME);
mimeType = AttachmentUtilities.inferMimeType(fileName, mimeType);
return mimeType;
}
} finally {
c.close();
}
return null;
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
/**
* Open an attachment file. There are two "formats" - "raw", which returns an actual file,
* and "thumbnail", which attempts to generate a thumbnail image.
*
* Thumbnails are cached for easy space recovery and cleanup.
*
* TODO: The thumbnail format returns null for its failure cases, instead of throwing
* FileNotFoundException, and should be fixed for consistency.
*
* @throws FileNotFoundException
*/
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
// If this is a write, the caller must have the EmailProvider permission, which is
// based on signature only
if (mode.equals("w")) {
Context context = getContext();
if (context.checkCallingPermission(EmailContent.PROVIDER_PERMISSION)
!= PackageManager.PERMISSION_GRANTED) {
throw new FileNotFoundException();
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
File saveIn =
AttachmentUtilities.getAttachmentDirectory(context, Long.parseLong(accountId));
if (!saveIn.exists()) {
saveIn.mkdirs();
}
File newFile = new File(saveIn, id);
return ParcelFileDescriptor.open(
newFile, ParcelFileDescriptor.MODE_READ_WRITE |
ParcelFileDescriptor.MODE_CREATE | ParcelFileDescriptor.MODE_TRUNCATE);
}
long callingId = Binder.clearCallingIdentity();
try {
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
if (AttachmentUtilities.FORMAT_THUMBNAIL.equals(format)) {
int width = Integer.parseInt(segments.get(3));
int height = Integer.parseInt(segments.get(4));
String filename = "thmb_" + accountId + "_" + id;
File dir = getContext().getCacheDir();
File file = new File(dir, filename);
if (!file.exists()) {
Uri attachmentUri = AttachmentUtilities.
getAttachmentUri(Long.parseLong(accountId), Long.parseLong(id));
Cursor c = query(attachmentUri,
new String[] { Columns.DATA }, null, null, null);
if (c != null) {
try {
if (c.moveToFirst()) {
attachmentUri = Uri.parse(c.getString(0));
} else {
return null;
}
} finally {
c.close();
}
}
String type = getContext().getContentResolver().getType(attachmentUri);
try {
InputStream in =
getContext().getContentResolver().openInputStream(attachmentUri);
Bitmap thumbnail = createThumbnail(type, in);
if (thumbnail == null) {
return null;
}
thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height, true);
FileOutputStream out = new FileOutputStream(file);
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
in.close();
} catch (IOException ioe) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
ioe.getMessage());
return null;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "openFile/thumbnail failed with " +
oome.getMessage());
return null;
}
}
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
else {
return ParcelFileDescriptor.open(
new File(getContext().getDatabasePath(accountId + ".db_att"), id),
ParcelFileDescriptor.MODE_READ_ONLY);
}
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int delete(Uri uri, String arg1, String[] arg2) {
return 0;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
return null;
}
/**
* Returns a cursor based on the data in the attachments table, or null if the attachment
* is not recorded in the table.
*
* Supports REST Uri only, for a single row - selection, selection args, and sortOrder are
* ignored (non-null values should probably throw an exception....)
*/
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
long callingId = Binder.clearCallingIdentity();
try {
if (projection == null) {
projection =
new String[] {
Columns._ID,
Columns.DATA,
Columns.DISPLAY_NAME, // matched the DISPLAY_NAME of {@link OpenableColumns}
Columns.SIZE, // matched the SIZE of {@link OpenableColumns}
};
}
List<String> segments = uri.getPathSegments();
String accountId = segments.get(0);
String id = segments.get(1);
String format = segments.get(2);
String name = null;
int size = -1;
String contentUri = null;
uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, Long.parseLong(id));
Cursor c = getContext().getContentResolver().query(uri, PROJECTION_QUERY,
null, null, null);
try {
if (c.moveToFirst()) {
name = c.getString(0);
size = c.getInt(1);
contentUri = c.getString(2);
} else {
return null;
}
} finally {
c.close();
}
MatrixCursor ret = new MatrixCursor(projection);
Object[] values = new Object[projection.length];
for (int i = 0, count = projection.length; i < count; i++) {
String column = projection[i];
if (Columns._ID.equals(column)) {
values[i] = id;
}
else if (Columns.DATA.equals(column)) {
values[i] = contentUri;
}
else if (Columns.DISPLAY_NAME.equals(column)) {
values[i] = name;
}
else if (Columns.SIZE.equals(column)) {
values[i] = size;
}
}
ret.addRow(values);
return ret;
} finally {
Binder.restoreCallingIdentity(callingId);
}
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
return 0;
}
private Bitmap createThumbnail(String type, InputStream data) {
if(MimeUtility.mimeTypeMatches(type, "image/*")) {
return createImageThumbnail(data);
}
return null;
}
private Bitmap createImageThumbnail(InputStream data) {
try {
Bitmap bitmap = BitmapFactory.decodeStream(data);
return bitmap;
} catch (OutOfMemoryError oome) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + oome.getMessage());
return null;
} catch (Exception e) {
Log.d(Logging.LOG_TAG, "createImageThumbnail failed with " + e.getMessage());
return null;
}
}
/**
* Need this to suppress warning in unit tests.
*/
@Override
public void shutdown() {
// Don't call super.shutdown(), which emits a warning...
}
}
|
craigacgomez/flaming_monkey_packages_apps_Email
|
src/com/android/email/provider/AttachmentProvider.java
|
Java
|
apache-2.0
| 13,480 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.08.31 at 10:43:34 AM EDT
//
package org.slc.sli.test.edfi.entitiesR1;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* This entity represents any program designed to work
* in conjunction with or to supplement the main
* academic program.
* Programs may provide instruction, training, services or benefits
* through federal,
* state, or local agencies. Programs may also include
* organized extracurricular activities for students.
*
*
* <p>Java class for program complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="program">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="programId" type="{http://slc-sli/ed-org/0.1}programId" minOccurs="0"/>
* <element name="programType" type="{http://slc-sli/ed-org/0.1}programType"/>
* <element name="programSponsor" type="{http://slc-sli/ed-org/0.1}programSponsorType" minOccurs="0"/>
* <element name="services" type="{http://slc-sli/ed-org/0.1}serviceDescriptorReferenceType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="staffAssociations" type="{http://slc-sli/ed-org/0.1}staffProgramAssociation" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "program", propOrder = {
"programId",
"programType",
"programSponsor",
"services",
"staffAssociations"
})
public class Program {
protected String programId;
@XmlElement(required = true)
protected ProgramType programType;
protected ProgramSponsorType programSponsor;
protected List<ServiceDescriptorReferenceType> services;
protected List<StaffProgramAssociation> staffAssociations;
/**
* Gets the value of the programId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProgramId() {
return programId;
}
/**
* Sets the value of the programId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProgramId(String value) {
this.programId = value;
}
/**
* Gets the value of the programType property.
*
* @return
* possible object is
* {@link ProgramType }
*
*/
public ProgramType getProgramType() {
return programType;
}
/**
* Sets the value of the programType property.
*
* @param value
* allowed object is
* {@link ProgramType }
*
*/
public void setProgramType(ProgramType value) {
this.programType = value;
}
/**
* Gets the value of the programSponsor property.
*
* @return
* possible object is
* {@link ProgramSponsorType }
*
*/
public ProgramSponsorType getProgramSponsor() {
return programSponsor;
}
/**
* Sets the value of the programSponsor property.
*
* @param value
* allowed object is
* {@link ProgramSponsorType }
*
*/
public void setProgramSponsor(ProgramSponsorType value) {
this.programSponsor = value;
}
/**
* Gets the value of the services property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the services property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServices().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ServiceDescriptorReferenceType }
*
*
*/
public List<ServiceDescriptorReferenceType> getServices() {
if (services == null) {
services = new ArrayList<ServiceDescriptorReferenceType>();
}
return this.services;
}
/**
* Gets the value of the staffAssociations property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the staffAssociations property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStaffAssociations().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link StaffProgramAssociation }
*
*
*/
public List<StaffProgramAssociation> getStaffAssociations() {
if (staffAssociations == null) {
staffAssociations = new ArrayList<StaffProgramAssociation>();
}
return this.staffAssociations;
}
}
|
inbloom/secure-data-service
|
tools/data-tools/src/org/slc/sli/test/edfi/entitiesR1/Program.java
|
Java
|
apache-2.0
| 6,094 |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/awt/geom/Path2D_Float_CopyIterator.hpp>
extern void unimplemented_(const char16_t* name);
java::awt::geom::Path2D_Float_CopyIterator::Path2D_Float_CopyIterator(const ::default_init_tag&)
: super(*static_cast< ::default_init_tag* >(0))
{
clinit();
}
java::awt::geom::Path2D_Float_CopyIterator::Path2D_Float_CopyIterator(Path2D_Float* p2df)
: Path2D_Float_CopyIterator(*static_cast< ::default_init_tag* >(0))
{
ctor(p2df);
}
void ::java::awt::geom::Path2D_Float_CopyIterator::ctor(Path2D_Float* p2df)
{ /* stub */
/* super::ctor(); */
unimplemented_(u"void ::java::awt::geom::Path2D_Float_CopyIterator::ctor(Path2D_Float* p2df)");
}
int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::floatArray* coords)
{ /* stub */
unimplemented_(u"int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::floatArray* coords)");
return 0;
}
int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::doubleArray* coords)
{ /* stub */
unimplemented_(u"int32_t java::awt::geom::Path2D_Float_CopyIterator::currentSegment(::doubleArray* coords)");
return 0;
}
extern java::lang::Class *class_(const char16_t *c, int n);
java::lang::Class* java::awt::geom::Path2D_Float_CopyIterator::class_()
{
static ::java::lang::Class* c = ::class_(u"java.awt.geom.Path2D.Float.CopyIterator", 39);
return c;
}
java::lang::Class* java::awt::geom::Path2D_Float_CopyIterator::getClass0()
{
return class_();
}
|
pebble2015/cpoi
|
ext/stub/java/awt/geom/Path2D_Float_CopyIterator-stub.cpp
|
C++
|
apache-2.0
| 1,586 |
/*
* Copyright 2017 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.index.es;
import java.util.List;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.service.PendingClusterTask;
import org.slf4j.Logger;
/**
* @since 5.10
*/
public final class AwaitPendingTasks {
private static final int PENDING_CLUSTER_TASKS_RETRY_INTERVAL = 50;
private AwaitPendingTasks() {}
public static final void await(Client client, Logger log) {
int pendingTaskCount = 0;
do {
List<PendingClusterTask> pendingTasks = client.admin()
.cluster()
.preparePendingClusterTasks()
.get()
.getPendingTasks();
pendingTaskCount = pendingTasks.size();
if (pendingTaskCount > 0) {
log.info("Waiting for pending cluster tasks to finish.");
try {
Thread.sleep(PENDING_CLUSTER_TASKS_RETRY_INTERVAL);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} while (pendingTaskCount > 0);
}
}
|
IHTSDO/snow-owl
|
commons/com.b2international.index/src/com/b2international/index/es/AwaitPendingTasks.java
|
Java
|
apache-2.0
| 1,558 |
package jwt4j.checkers;
import com.google.gson.JsonObject;
import jwt4j.TokenChecker;
import jwt4j.exceptions.InvalidIssuerException;
import static jwt4j.JWTConstants.ISSUER;
public class IssuerChecker implements TokenChecker
{
private final String issuer;
public IssuerChecker(final String issuer)
{
this.issuer = issuer;
}
@Override
public void check(JsonObject payloadJson)
{
if (!payloadJson.has(ISSUER) || !payloadJson.get(ISSUER).getAsString().equals(issuer)) {
throw new InvalidIssuerException("Expected " + issuer + " issuer");
}
}
}
|
milpol/jwt4j
|
src/main/java/jwt4j/checkers/IssuerChecker.java
|
Java
|
apache-2.0
| 614 |
/**
* A TabPanel osztály egységbe foglal több Panel-t, és segíti azok kezelését.
*
*
* @author Gabor Kokeny
*/
class TabPanel extends Container {
/**
* Ez a változó tárolja az aktív index értékét, amely egy pozitív egész szám.
*
* @property {number} activeTabIndex
*/
private activeIndex: number = null;
private activePanel: Panel;
private menu: TabPanelMenu;
/**
*
* @param {Container} parent
* @constructor
*/
constructor(parent: Container) {
super(parent, true);
this.setClass("ui-tabpanel");
this.getContainer().setClass("ui-tabpanel-wrapper");
this.menu = new TabPanelMenu(this.getContainer());
}
add(panel: Panel) {
if (!(panel instanceof Panel)) {
Log.error("Item couldn't add to tabpanel, because it is not a Panel", panel);
}
super.add(panel);
var me = this;
var listener = function(e:Event) {
var menuItem = new MenuItem(me.menu);
menuItem.setText(panel.getTitle());
menuItem.setIconClass(panel.getIconClass());
menuItem.addClickListener(function(e:MouseEvent){
me.setActivePanel(panel);
});
panel.removeListener(TabPanel.EVENT_BEFORE_RENDER, listener);
}
panel.addListener(TabPanel.EVENT_BEFORE_RENDER, listener);
//Log.debug("TabPanel children :", this.getChildren());
this.setActiveTabIndex(0);
}
/**
* Ezzel a metódussal lehet beállítani, hogy melyik legyen az aktív panel.
* Paraméterként egy számot kell megadnunk, ami nem lehet null, undifined, vagy negatív érték.
* A TabPanel 0 bázisindexű, így ha azt szeretnénk, hogy az első Panel legyen aktív akkor 0-t kell
* paraméterként megadni.
*
* Ha a paraméterként megadott index megegyezik az aktuális aktív index értékével, akkor a metódus kilép.
*
* @param {number} activeIndex
*/
setActiveTabIndex(index: number) {
this.checkTabIndex(index);
if (this.activeIndex == index) {
return;
}
var panel = this.getPanel(index);
this.setActivePanel(panel);
this.activeIndex = index;
}
/**
*
* @param {Panel} panel
* @private
*/
private setActivePanel(panel: Panel) {
Assert.notNull(panel, "panel");
if (this.activePanel) {
this.activePanel.removeClass("active");
}
this.activePanel = panel;
this.activePanel.addClass("active");
}
/**
* Ez a metódus vissza adja az aktív panel indexét.
* @return {number} Vissza adja a jelenleg aktív panel indexet. Ha nincs még panel hozzáadva a TabPanel-hez,
* akkor a -1 értékkel tér vissza.
*/
getActiveTabIndex(): number {
return this.activeIndex ? this.activeIndex : -1;
}
/**
* Ez a helper metódus eldönti, hogy a paraméterként kapott egész szám az megfelel-e
* a TabPanel által megkövetelt elvárásoknak.
*
* - Nem lehet null vagy undifined
* - Nem lehet negatív érték
* - Kisebb kell, hogy legyen mint a panelek száma.
*
* @param {number} tabIndex Az ellenőrizni kívánt index.
* @private
*/
private checkTabIndex(tabIndex: number) {
if (tabIndex === null || tabIndex === undefined) {
Log.error("The active tab index cannot be null or undifined");
}
if (tabIndex < 0) {
Log.error("The active tab index cannot be negative, it is should be a positve number!");
}
if (tabIndex >= this.getChildren().size()) {
Log.error("The active tab index should be less then " + this.getChildren().size());
}
}
/**
* Vissza adja a jelenleg aktív panelt. Az aktív panel módosítása
* a setActiveTabIndex metódus meghívásával lehetséges.
*
* @return {Panel} Az aktív panel vagy null érték, ha a TapPanel még üres.
*/
getActivePanel(): Panel {
return this.activePanel;
}
/**
*
* @param {number} index
* @return {Panel}
*/
getPanel(index: number): Panel {
//TODO check it
return <Panel>super.getComponent(index);
}
}
/**
*
* @author Gabor Kokeny
*/
class TabPanelMenu extends Menu {
constructor(parent: Container) {
super(parent);
}
}
|
Gubancs/TypeUI
|
typeui-framework/src/main/resources/typescript/ui/TabPanel.ts
|
TypeScript
|
apache-2.0
| 4,557 |
package com.bnsantos.movies.model;
import com.j256.ormlite.field.DatabaseField;
/**
* Created by bruno on 14/11/14.
*/
public class Links {
@DatabaseField(generatedId = true, columnName = "id")
private Integer id;
@DatabaseField()
private String self;
@DatabaseField()
private String alternate;
@DatabaseField()
private String cast;
@DatabaseField()
private String reviews;
@DatabaseField()
private String similar;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSelf() {
return self;
}
public void setSelf(String self) {
this.self = self;
}
public String getAlternate() {
return alternate;
}
public void setAlternate(String alternate) {
this.alternate = alternate;
}
public String getCast() {
return cast;
}
public void setCast(String cast) {
this.cast = cast;
}
public String getReviews() {
return reviews;
}
public void setReviews(String reviews) {
this.reviews = reviews;
}
public String getSimilar() {
return similar;
}
public void setSimilar(String similar) {
this.similar = similar;
}
}
|
bnsantos/android-javarx-example
|
app/src/main/java/com/bnsantos/movies/model/Links.java
|
Java
|
apache-2.0
| 1,305 |
package com.mytian.lb.bean.push;
import com.core.openapi.OpenApiBaseRequestAdapter;
import com.core.util.StringUtil;
import java.util.HashMap;
import java.util.Map;
public class UpdateChannelidParam extends OpenApiBaseRequestAdapter {
private String uid;
private String token;
private String channelId;
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
@Override
public boolean validate() {
if (StringUtil.isBlank(this.uid)) return false;
if (StringUtil.isBlank(this.token)) return false;
if (StringUtil.isBlank(this.channelId)) return false;
return true;
}
@Override
public void fill2Map(Map<String, Object> param, boolean includeEmptyAttr) {
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(uid)))
param.put("uid", uid);
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(token)))
param.put("token", token);
if (includeEmptyAttr || (!includeEmptyAttr && StringUtil.isNotBlank(channelId)))
param.put("parent.channelId", channelId);
}
@Override
public String toString() {
return "UpdateChannelidParam{" +
"uid='" + uid + '\'' +
", token='" + token + '\'' +
", channelId='" + channelId + '\'' +
'}';
}
}
|
tengbinlive/aibao_demo
|
app/src/main/java/com/mytian/lb/bean/push/UpdateChannelidParam.java
|
Java
|
apache-2.0
| 1,799 |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.flowable.rest.form;
import java.text.MessageFormat;
import org.apache.commons.lang3.StringUtils;
/**
* @author Yvo Swillens
*/
public final class FormRestUrls {
public static final String SEGMENT_FORM_RESOURCES = "form";
public static final String SEGMENT_REPOSITORY_RESOURCES = "form-repository";
public static final String SEGMENT_RUNTIME_FORM_DEFINITION = "runtime-form-definition";
public static final String SEGMENT_COMPLETED_FORM_DEFINITION = "completed-form-definition";
public static final String SEGMENT_DEPLOYMENT_RESOURCES = "deployments";
public static final String SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT = "resourcedata";
public static final String SEGMENT_FORMS_RESOURCES = "forms";
public static final String SEGMENT_FORM_MODEL = "model";
public static final String SEGMENT_FORM_INSTANCES_RESOURCES = "form-instances";
public static final String SEGMENT_QUERY_RESOURCES = "query";
/**
* URL template for a form collection: <i>/form/runtime-form-definition</i>
*/
public static final String[] URL_RUNTIME_TASK_FORM = { SEGMENT_FORM_RESOURCES, SEGMENT_RUNTIME_FORM_DEFINITION };
/**
* URL template for a form collection: <i>/form/completed-form-definition</i>
*/
public static final String[] URL_COMPLETED_TASK_FORM = { SEGMENT_FORM_RESOURCES, SEGMENT_COMPLETED_FORM_DEFINITION };
/**
* URL template for a form collection: <i>/form-repository/forms/{0:formId}</i>
*/
public static final String[] URL_FORM_COLLECTION = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORMS_RESOURCES };
/**
* URL template for a single form: <i>/form-repository/forms/{0:formId}</i>
*/
public static final String[] URL_FORM = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORMS_RESOURCES, "{0}" };
/**
* URL template for a single form model: <i>/form-repository/forms/{0:formId}/model</i>
*/
public static final String[] URL_FORM_MODEL = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORM_RESOURCES, "{0}", SEGMENT_FORM_MODEL };
/**
* URL template for the resource of a single form: <i>/form-repository/forms/{0:formId}/resourcedata</i>
*/
public static final String[] URL_FORM_RESOURCE_CONTENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_FORM_RESOURCES, "{0}", SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT };
/**
* URL template for a deployment collection: <i>/form-repository/deployments</i>
*/
public static final String[] URL_DEPLOYMENT_COLLECTION = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES };
/**
* URL template for a single deployment: <i>/form-repository/deployments/{0:deploymentId}</i>
*/
public static final String[] URL_DEPLOYMENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES, "{0}" };
/**
* URL template for the resource of a single deployment: <i>/form-repository/deployments/{0:deploymentId}/resourcedata/{1:resourceId}</i>
*/
public static final String[] URL_DEPLOYMENT_RESOURCE_CONTENT = { SEGMENT_REPOSITORY_RESOURCES, SEGMENT_DEPLOYMENT_RESOURCES, "{0}", SEGMENT_DEPLOYMENT_ARTIFACT_RESOURCE_CONTENT, "{1}" };
/**
* URL template for the resource of a form instance query: <i>/query/form-instances</i>
*/
public static final String[] URL_FORM_INSTANCE_QUERY = { SEGMENT_QUERY_RESOURCES, SEGMENT_FORM_INSTANCES_RESOURCES };
/**
* Creates an url based on the passed fragments and replaces any placeholders with the given arguments. The placeholders are following the {@link MessageFormat} convention (eg. {0} is replaced by
* first argument value).
*/
public static final String createRelativeResourceUrl(String[] segments, Object... arguments) {
return MessageFormat.format(StringUtils.join(segments, '/'), arguments);
}
}
|
robsoncardosoti/flowable-engine
|
modules/flowable-form-rest/src/main/java/org/flowable/rest/form/FormRestUrls.java
|
Java
|
apache-2.0
| 4,399 |
package weka.classifiers.lazy.AM.label;
import org.hamcrest.core.StringContains;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import weka.classifiers.lazy.AM.TestUtils;
import weka.core.Instances;
/**
* Test aspects of {@link IntLabeler} that are not applicable to other
* {@link Labeler} implementations.
*
* @author Nathan Glenn
*/
public class IntLabelerTest {
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void testConstructorCardinalityTooHigh() throws Exception {
exception.expect(IllegalArgumentException.class);
exception.expectMessage(new StringContains("Cardinality of instance too high (35)"));
Instances data = TestUtils.getDataSet(TestUtils.SOYBEAN);
new IntLabeler(data.get(0), false, MissingDataCompare.MATCH);
}
}
|
garfieldnate/Weka_AnalogicalModeling
|
src/test/java/weka/classifiers/lazy/AM/label/IntLabelerTest.java
|
Java
|
apache-2.0
| 877 |
/*
* Copyright 2015 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.javascript.jscomp.Es6ToEs3Util.makeIterator;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import com.google.javascript.rhino.TokenStream;
/**
* Rewrites ES6 destructuring patterns and default parameters to valid ES3 code.
*/
public final class Es6RewriteDestructuring implements NodeTraversal.Callback, HotSwapCompilerPass {
private final AbstractCompiler compiler;
static final String DESTRUCTURING_TEMP_VAR = "$jscomp$destructuring$var";
private int destructuringVarCounter = 0;
public Es6RewriteDestructuring(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
TranspilationPasses.processTranspile(compiler, externs, this);
TranspilationPasses.processTranspile(compiler, root, this);
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
TranspilationPasses.hotSwapTranspile(compiler, scriptRoot, this);
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
switch (n.getToken()) {
case FUNCTION:
visitFunction(t, n);
break;
case PARAM_LIST:
visitParamList(t, n, parent);
break;
case FOR_OF:
visitForOf(n);
break;
default:
break;
}
return true;
}
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (parent != null && parent.isDestructuringLhs()) {
parent = parent.getParent();
}
switch (n.getToken()) {
case ARRAY_PATTERN:
case OBJECT_PATTERN:
visitPattern(t, n, parent);
break;
default:
break;
}
}
/**
* If the function is an arrow function, wrap the body in a block if it is not already a block.
*/
private void visitFunction(NodeTraversal t, Node function) {
Node body = function.getLastChild();
if (!body.isNormalBlock()) {
body.detach();
Node replacement = IR.block(IR.returnNode(body)).useSourceInfoIfMissingFromForTree(body);
function.addChildToBack(replacement);
t.reportCodeChange();
}
}
/**
* Processes trailing default and rest parameters.
*/
private void visitParamList(NodeTraversal t, Node paramList, Node function) {
Node insertSpot = null;
Node body = function.getLastChild();
int i = 0;
Node next = null;
for (Node param = paramList.getFirstChild(); param != null; param = next, i++) {
next = param.getNext();
if (param.isDefaultValue()) {
JSDocInfo jsDoc = param.getJSDocInfo();
Node nameOrPattern = param.removeFirstChild();
Node defaultValue = param.removeFirstChild();
Node newParam;
// Treat name=undefined (and equivalent) as if it was just name. There
// is no need to generate a (name===void 0?void 0:name) statement for
// such arguments.
boolean isNoop = false;
if (!nameOrPattern.isName()) {
// Do not try to optimize unless nameOrPattern is a simple name.
} else if (defaultValue.isName()) {
isNoop = "undefined".equals(defaultValue.getString());
} else if (defaultValue.isVoid()) {
// Any kind of 'void literal' is fine, but 'void fun()' or anything
// else with side effects isn't. We're not trying to be particularly
// smart here and treat 'void {}' for example as if it could cause
// side effects. Any sane person will type 'name=undefined' or
// 'name=void 0' so this should not be an issue.
isNoop = NodeUtil.isImmutableValue(defaultValue.getFirstChild());
}
if (isNoop) {
newParam = nameOrPattern.cloneTree();
} else {
newParam =
nameOrPattern.isName()
? nameOrPattern
: IR.name(getTempParameterName(function, i));
Node lhs = nameOrPattern.cloneTree();
Node rhs = defaultValueHook(newParam.cloneTree(), defaultValue);
Node newStatement =
nameOrPattern.isName() ? IR.exprResult(IR.assign(lhs, rhs)) : IR.var(lhs, rhs);
newStatement.useSourceInfoIfMissingFromForTree(param);
body.addChildAfter(newStatement, insertSpot);
insertSpot = newStatement;
}
paramList.replaceChild(param, newParam);
newParam.setOptionalArg(true);
newParam.setJSDocInfo(jsDoc);
t.reportCodeChange();
} else if (param.isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param, getTempParameterName(function, i));
t.reportCodeChange();
} else if (param.isRest() && param.getFirstChild().isDestructuringPattern()) {
insertSpot =
replacePatternParamWithTempVar(
function, insertSpot, param.getFirstChild(), getTempParameterName(function, i));
t.reportCodeChange();
}
}
}
/**
* Replace a destructuring pattern parameter with a a temporary parameter name and add a new
* local variable declaration to the function assigning the temporary parameter to the pattern.
*
* <p> Note: Rewrites of variable declaration destructuring will happen later to rewrite
* this declaration as non-destructured code.
* @param function
* @param insertSpot The local variable declaration will be inserted after this statement.
* @param patternParam
* @param tempVarName the name to use for the temporary variable
* @return the declaration statement that was generated for the local variable
*/
private Node replacePatternParamWithTempVar(
Node function, Node insertSpot, Node patternParam, String tempVarName) {
Node newParam = IR.name(tempVarName);
newParam.setJSDocInfo(patternParam.getJSDocInfo());
patternParam.replaceWith(newParam);
Node newDecl = IR.var(patternParam, IR.name(tempVarName));
function.getLastChild().addChildAfter(newDecl, insertSpot);
return newDecl;
}
/**
* Find or create the best name to use for a parameter we need to rewrite.
*
* <ol>
* <li> Use the JS Doc function parameter name at the given index, if possible.
* <li> Otherwise, build one of our own.
* </ol>
* @param function
* @param parameterIndex
* @return name to use for the given parameter
*/
private String getTempParameterName(Node function, int parameterIndex) {
String tempVarName;
JSDocInfo fnJSDoc = NodeUtil.getBestJSDocInfo(function);
if (fnJSDoc != null && fnJSDoc.getParameterNameAt(parameterIndex) != null) {
tempVarName = fnJSDoc.getParameterNameAt(parameterIndex);
} else {
tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
}
checkState(TokenStream.isJSIdentifier(tempVarName));
return tempVarName;
}
private void visitForOf(Node node) {
Node lhs = node.getFirstChild();
if (lhs.isDestructuringLhs()) {
visitDestructuringPatternInEnhancedFor(lhs.getFirstChild());
}
}
private void visitPattern(NodeTraversal t, Node pattern, Node parent) {
if (NodeUtil.isNameDeclaration(parent) && !NodeUtil.isEnhancedFor(parent.getParent())) {
replacePattern(t, pattern, pattern.getNext(), parent, parent);
} else if (parent.isAssign()) {
if (parent.getParent().isExprResult()) {
replacePattern(t, pattern, pattern.getNext(), parent, parent.getParent());
} else {
wrapAssignmentInCallToArrow(t, parent);
}
} else if (parent.isRest()
|| parent.isStringKey()
|| parent.isArrayPattern()
|| parent.isDefaultValue()) {
// Nested pattern; do nothing. We will visit it after rewriting the parent.
} else if (NodeUtil.isEnhancedFor(parent) || NodeUtil.isEnhancedFor(parent.getParent())) {
visitDestructuringPatternInEnhancedFor(pattern);
} else if (parent.isCatch()) {
visitDestructuringPatternInCatch(pattern);
} else {
throw new IllegalStateException("unexpected parent");
}
}
private void replacePattern(
NodeTraversal t, Node pattern, Node rhs, Node parent, Node nodeToDetach) {
switch (pattern.getToken()) {
case ARRAY_PATTERN:
replaceArrayPattern(t, pattern, rhs, parent, nodeToDetach);
break;
case OBJECT_PATTERN:
replaceObjectPattern(t, pattern, rhs, parent, nodeToDetach);
break;
default:
throw new IllegalStateException("unexpected");
}
}
/**
* Convert 'var {a: b, c: d} = rhs' to:
*
* @const var temp = rhs; var b = temp.a; var d = temp.c;
*/
private void replaceObjectPattern(
NodeTraversal t, Node objectPattern, Node rhs, Node parent, Node nodeToDetach) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node tempDecl = IR.var(IR.name(tempVarName), rhs.detach())
.useSourceInfoIfMissingFromForTree(objectPattern);
// TODO(tbreisacher): Remove the "if" and add this JSDoc unconditionally.
if (parent.isConst()) {
JSDocInfoBuilder jsDoc = new JSDocInfoBuilder(false);
jsDoc.recordConstancy();
tempDecl.setJSDocInfo(jsDoc.build());
}
nodeToDetach.getParent().addChildBefore(tempDecl, nodeToDetach);
for (Node child = objectPattern.getFirstChild(), next; child != null; child = next) {
next = child.getNext();
Node newLHS;
Node newRHS;
if (child.isStringKey()) {
if (!child.hasChildren()) { // converting shorthand
Node name = IR.name(child.getString());
name.useSourceInfoIfMissingFrom(child);
child.addChildToBack(name);
}
Node getprop =
new Node(
child.isQuotedString() ? Token.GETELEM : Token.GETPROP,
IR.name(tempVarName),
IR.string(child.getString()));
Node value = child.removeFirstChild();
if (!value.isDefaultValue()) {
newLHS = value;
newRHS = getprop;
} else {
newLHS = value.removeFirstChild();
Node defaultValue = value.removeFirstChild();
newRHS = defaultValueHook(getprop, defaultValue);
}
} else if (child.isComputedProp()) {
if (child.getLastChild().isDefaultValue()) {
newLHS = child.getLastChild().removeFirstChild();
Node getelem = IR.getelem(IR.name(tempVarName), child.removeFirstChild());
String intermediateTempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node intermediateDecl = IR.var(IR.name(intermediateTempVarName), getelem);
intermediateDecl.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(intermediateDecl, nodeToDetach);
newRHS =
defaultValueHook(
IR.name(intermediateTempVarName), child.getLastChild().removeFirstChild());
} else {
newRHS = IR.getelem(IR.name(tempVarName), child.removeFirstChild());
newLHS = child.removeFirstChild();
}
} else if (child.isDefaultValue()) {
newLHS = child.removeFirstChild();
Node defaultValue = child.removeFirstChild();
Node getprop = IR.getprop(IR.name(tempVarName), IR.string(newLHS.getString()));
newRHS = defaultValueHook(getprop, defaultValue);
} else {
throw new IllegalStateException("unexpected child");
}
Node newNode;
if (NodeUtil.isNameDeclaration(parent)) {
newNode = IR.declaration(newLHS, newRHS, parent.getToken());
} else if (parent.isAssign()) {
newNode = IR.exprResult(IR.assign(newLHS, newRHS));
} else {
throw new IllegalStateException("not reached");
}
newNode.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(newNode, nodeToDetach);
// Explicitly visit the LHS of the new node since it may be a nested
// destructuring pattern.
visit(t, newLHS, newLHS.getParent());
}
nodeToDetach.detach();
t.reportCodeChange();
}
/**
* Convert 'var [x, y] = rhs' to: var temp = $jscomp.makeIterator(rhs); var x = temp.next().value;
* var y = temp.next().value;
*/
private void replaceArrayPattern(
NodeTraversal t, Node arrayPattern, Node rhs, Node parent, Node nodeToDetach) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node tempDecl = IR.var(
IR.name(tempVarName),
makeIterator(compiler, rhs.detach()));
tempDecl.useSourceInfoIfMissingFromForTree(arrayPattern);
nodeToDetach.getParent().addChildBefore(tempDecl, nodeToDetach);
boolean needsRuntime = false;
for (Node child = arrayPattern.getFirstChild(), next; child != null; child = next) {
next = child.getNext();
if (child.isEmpty()) {
// Just call the next() method to advance the iterator, but throw away the value.
Node nextCall = IR.exprResult(IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))));
nextCall.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(nextCall, nodeToDetach);
continue;
}
Node newLHS;
Node newRHS;
if (child.isDefaultValue()) {
// [x = defaultValue] = rhs;
// becomes
// var temp0 = $jscomp.makeIterator(rhs);
// var temp1 = temp.next().value
// x = (temp1 === undefined) ? defaultValue : temp1;
String nextVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node var = IR.var(
IR.name(nextVarName),
IR.getprop(
IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))),
IR.string("value")));
var.useSourceInfoIfMissingFromForTree(child);
nodeToDetach.getParent().addChildBefore(var, nodeToDetach);
newLHS = child.getFirstChild().detach();
newRHS = defaultValueHook(IR.name(nextVarName), child.getLastChild().detach());
} else if (child.isRest()) {
// [...x] = rhs;
// becomes
// var temp = $jscomp.makeIterator(rhs);
// x = $jscomp.arrayFromIterator(temp);
newLHS = child.getFirstChild().detach();
newRHS =
IR.call(
NodeUtil.newQName(compiler, "$jscomp.arrayFromIterator"),
IR.name(tempVarName));
needsRuntime = true;
} else {
// LHS is just a name (or a nested pattern).
// var [x] = rhs;
// becomes
// var temp = $jscomp.makeIterator(rhs);
// var x = temp.next().value;
newLHS = child.detach();
newRHS = IR.getprop(
IR.call(IR.getprop(IR.name(tempVarName), IR.string("next"))),
IR.string("value"));
}
Node newNode;
if (parent.isAssign()) {
Node assignment = IR.assign(newLHS, newRHS);
newNode = IR.exprResult(assignment);
} else {
newNode = IR.declaration(newLHS, newRHS, parent.getToken());
}
newNode.useSourceInfoIfMissingFromForTree(arrayPattern);
nodeToDetach.getParent().addChildBefore(newNode, nodeToDetach);
// Explicitly visit the LHS of the new node since it may be a nested
// destructuring pattern.
visit(t, newLHS, newLHS.getParent());
}
nodeToDetach.detach();
if (needsRuntime) {
compiler.ensureLibraryInjected("es6/util/arrayfromiterator", false);
}
t.reportCodeChange();
}
/**
* Convert the assignment '[x, y] = rhs' that is used as an expression and not an expr result to:
* (() => let temp0 = rhs; var temp1 = $jscomp.makeIterator(temp0); var x = temp0.next().value;
* var y = temp0.next().value; return temp0; }) And the assignment '{x: a, y: b} = rhs' used as an
* expression and not an expr result to: (() => let temp0 = rhs; var temp1 = temp0; var a =
* temp0.x; var b = temp0.y; return temp0; })
*/
private void wrapAssignmentInCallToArrow(NodeTraversal t, Node assignment) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node rhs = assignment.getLastChild().detach();
Node newAssignment = IR.let(IR.name(tempVarName), rhs);
Node replacementExpr = IR.assign(assignment.getFirstChild().detach(), IR.name(tempVarName));
Node exprResult = IR.exprResult(replacementExpr);
Node returnNode = IR.returnNode(IR.name(tempVarName));
Node block = IR.block(newAssignment, exprResult, returnNode);
Node call = IR.call(IR.arrowFunction(IR.name(""), IR.paramList(), block));
call.useSourceInfoIfMissingFromForTree(assignment);
call.putBooleanProp(Node.FREE_CALL, true);
assignment.getParent().replaceChild(assignment, call);
NodeUtil.markNewScopesChanged(call, compiler);
replacePattern(
t,
replacementExpr.getFirstChild(),
replacementExpr.getLastChild(),
replacementExpr,
exprResult);
}
private void visitDestructuringPatternInEnhancedFor(Node pattern) {
checkArgument(pattern.isDestructuringPattern());
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
if (NodeUtil.isEnhancedFor(pattern.getParent())) {
Node forNode = pattern.getParent();
Node block = forNode.getLastChild();
Node decl = IR.var(IR.name(tempVarName));
decl.useSourceInfoIfMissingFromForTree(pattern);
forNode.replaceChild(pattern, decl);
Node exprResult = IR.exprResult(IR.assign(pattern, IR.name(tempVarName)));
exprResult.useSourceInfoIfMissingFromForTree(pattern);
block.addChildToFront(exprResult);
} else {
Node destructuringLhs = pattern.getParent();
checkState(destructuringLhs.isDestructuringLhs());
Node declarationNode = destructuringLhs.getParent();
Node forNode = declarationNode.getParent();
checkState(NodeUtil.isEnhancedFor(forNode));
Node block = forNode.getLastChild();
declarationNode.replaceChild(
destructuringLhs, IR.name(tempVarName).useSourceInfoFrom(pattern));
Token declarationType = declarationNode.getToken();
Node decl = IR.declaration(pattern.detach(), IR.name(tempVarName), declarationType);
decl.useSourceInfoIfMissingFromForTree(pattern);
block.addChildToFront(decl);
}
}
private void visitDestructuringPatternInCatch(Node pattern) {
String tempVarName = DESTRUCTURING_TEMP_VAR + (destructuringVarCounter++);
Node catchBlock = pattern.getNext();
pattern.replaceWith(IR.name(tempVarName));
catchBlock.addChildToFront(IR.declaration(pattern, IR.name(tempVarName), Token.LET));
}
/**
* Helper for transpiling DEFAULT_VALUE trees.
*/
private static Node defaultValueHook(Node getprop, Node defaultValue) {
return IR.hook(IR.sheq(getprop, IR.name("undefined")), defaultValue, getprop.cloneTree());
}
}
|
MatrixFrog/closure-compiler
|
src/com/google/javascript/jscomp/Es6RewriteDestructuring.java
|
Java
|
apache-2.0
| 19,873 |
<?php
/**
* ZonecityController
* @var $this ZonecityController
* @var $model OmmuZoneCity
* @var $form CActiveForm
* version: 1.1.0
* Reference start
*
* TOC :
* Index
* Suggest
* Manage
* Add
* Edit
* RunAction
* Delete
* Publish
*
* LoadModel
* performAjaxValidation
*
* @author Putra Sudaryanto <putra@sudaryanto.id>
* @copyright Copyright (c) 2015 Ommu Platform (ommu.co)
* @link https://github.com/oMMu/Ommu-Core
* @contect (+62)856-299-4114
*
*----------------------------------------------------------------------------------------------------------
*/
class ZonecityController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/column2', meaning
* using two-column layout. See 'protected/views/layouts/column2.php'.
*/
//public $layout='//layouts/column2';
public $defaultAction = 'index';
/**
* Initialize admin page theme
*/
public function init()
{
if(!Yii::app()->user->isGuest) {
if(Yii::app()->user->level == 1) {
$arrThemes = Utility::getCurrentTemplate('admin');
Yii::app()->theme = $arrThemes['folder'];
$this->layout = $arrThemes['layout'];
} else {
$this->redirect(Yii::app()->createUrl('site/login'));
}
} else {
$this->redirect(Yii::app()->createUrl('site/login'));
}
}
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
//'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','suggest'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array(),
'users'=>array('@'),
'expression'=>'isset(Yii::app()->user->level)',
//'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level != 1)',
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('manage','add','edit','runaction','delete','publish'),
'users'=>array('@'),
'expression'=>'isset(Yii::app()->user->level) && (Yii::app()->user->level == 1)',
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array(),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
/**
* Lists all models.
*/
public function actionIndex()
{
$this->redirect(array('manage'));
}
/**
* Lists all models.
*/
public function actionSuggest($id=null)
{
if($id == null) {
if(isset($_GET['term'])) {
$criteria = new CDbCriteria;
$criteria->condition = 'city LIKE :city';
$criteria->select = "city_id, city";
$criteria->order = "city_id ASC";
$criteria->params = array(':city' => '%' . strtolower($_GET['term']) . '%');
$model = OmmuZoneCity::model()->findAll($criteria);
if($model) {
foreach($model as $items) {
$result[] = array('id' => $items->city_id, 'value' => $items->city);
}
}
}
echo CJSON::encode($result);
Yii::app()->end();
} else {
$model = OmmuZoneCity::getCity($id);
$message['data'] = '<option value="">'.Yii::t('phrase', 'Select one').'</option>';
foreach($model as $key => $val) {
$message['data'] .= '<option value="'.$key.'">'.$val.'</option>';
}
echo CJSON::encode($message);
}
}
/**
* Manages all models.
*/
public function actionManage()
{
$model=new OmmuZoneCity('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['OmmuZoneCity'])) {
$model->attributes=$_GET['OmmuZoneCity'];
}
$columnTemp = array();
if(isset($_GET['GridColumn'])) {
foreach($_GET['GridColumn'] as $key => $val) {
if($_GET['GridColumn'][$key] == 1) {
$columnTemp[] = $key;
}
}
}
$columns = $model->getGridColumn($columnTemp);
$this->pageTitle = 'Ommu Zone Cities Manage';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_manage',array(
'model'=>$model,
'columns' => $columns,
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionAdd()
{
$model=new OmmuZoneCity;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['OmmuZoneCity'])) {
$model->attributes=$_POST['OmmuZoneCity'];
$jsonError = CActiveForm::validate($model);
if(strlen($jsonError) > 2) {
echo $jsonError;
} else {
if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
if($model->save()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success created.</strong></div>',
));
} else {
print_r($model->getErrors());
}
}
}
Yii::app()->end();
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 600;
$this->pageTitle = 'Create Ommu Zone Cities';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_add',array(
'model'=>$model,
));
}
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionEdit($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if(isset($_POST['OmmuZoneCity'])) {
$model->attributes=$_POST['OmmuZoneCity'];
$jsonError = CActiveForm::validate($model);
if(strlen($jsonError) > 2) {
echo $jsonError;
} else {
if(isset($_GET['enablesave']) && $_GET['enablesave'] == 1) {
if($model->save()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success updated.</strong></div>',
));
} else {
print_r($model->getErrors());
}
}
}
Yii::app()->end();
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 600;
$this->pageTitle = 'Update Ommu Zone Cities';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_edit',array(
'model'=>$model,
));
}
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionRunAction() {
$id = $_POST['trash_id'];
$criteria = null;
$actions = $_GET['action'];
if(count($id) > 0) {
$criteria = new CDbCriteria;
$criteria->addInCondition('id', $id);
if($actions == 'publish') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 1,
),$criteria);
} elseif($actions == 'unpublish') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 0,
),$criteria);
} elseif($actions == 'trash') {
OmmuZoneCity::model()->updateAll(array(
'publish' => 2,
),$criteria);
} elseif($actions == 'delete') {
OmmuZoneCity::model()->deleteAll($criteria);
}
}
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax'])) {
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('manage'));
}
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$model=$this->loadModel($id);
if(Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
if(isset($id)) {
if($model->delete()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success deleted.</strong></div>',
));
}
}
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 350;
$this->pageTitle = 'OmmuZoneCity Delete.';
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_delete');
}
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionPublish($id)
{
$model=$this->loadModel($id);
if($model->publish == 1) {
$title = Yii::t('phrase', 'Unpublish');
$replace = 0;
} else {
$title = Yii::t('phrase', 'Publish');
$replace = 1;
}
if(Yii::app()->request->isPostRequest) {
// we only allow deletion via POST request
if(isset($id)) {
//change value active or publish
$model->publish = $replace;
if($model->update()) {
echo CJSON::encode(array(
'type' => 5,
'get' => Yii::app()->controller->createUrl('manage'),
'id' => 'partial-ommu-zone-city',
'msg' => '<div class="errorSummary success"><strong>OmmuZoneCity success published.</strong></div>',
));
}
}
} else {
$this->dialogDetail = true;
$this->dialogGroundUrl = Yii::app()->controller->createUrl('manage');
$this->dialogWidth = 350;
$this->pageTitle = $title;
$this->pageDescription = '';
$this->pageMeta = '';
$this->render('/zone_city/admin_publish',array(
'title'=>$title,
'model'=>$model,
));
}
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model = OmmuZoneCity::model()->findByPk($id);
if($model===null)
throw new CHttpException(404, Yii::t('phrase', 'The requested page does not exist.'));
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='ommu-zone-city-form') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
|
oMMuCo/HPTT-FT-UGM-Official-Website
|
protected/controllers/ZonecityController.php
|
PHP
|
apache-2.0
| 10,950 |
/*
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.kinesisvideo;
import com.amazonaws.services.kinesisvideo.model.ClientLimitExceededException;
import com.amazonaws.services.kinesisvideo.model.ConnectionLimitExceededException;
import com.amazonaws.services.kinesisvideo.model.InvalidArgumentException;
import com.amazonaws.services.kinesisvideo.model.InvalidEndpointException;
import com.amazonaws.services.kinesisvideo.model.NotAuthorizedException;
import com.amazonaws.services.kinesisvideo.model.PutMediaRequest;
import com.amazonaws.services.kinesisvideo.model.ResourceNotFoundException;
import java.io.Closeable;
/**
* Interface for accessing Amazon Kinesis Video's PutMedia operation. This is a special, asynchronous operation that is not supported
* in the normal client ({@link AWSKinesisVideoMediaClient}.
* <p>
* <b>Note:</b> Do not directly implement this interface, new methods are added to it regularly. Extend from
* {@link AbstractAmazonKinesisVideoPutMedia} instead.
* </p>
*/
// TODO service docs when available.
public interface AmazonKinesisVideoPutMedia extends Closeable {
/**
* <p>
* Use this API to send media data to a Kinesis video stream.
* </p>
* <note>
* <p>
* Before using this API, you must call the <code>GetDataEndpoint</code> API to get an endpoint. You then specify
* the endpoint in your <code>PutMedia</code> request.
* </p>
* </note>
* <p>
* In the request, you use the HTTP headers to provide parameter information, for example, stream name, time stamp,
* and whether the time stamp value is absolute or relative to when the producer started recording. You use the
* request body to send the media data. Kinesis Video Streams supports only the Matroska (MKV) container format for
* sending media data using this API.
* </p>
* <p>
* You have the following options for sending data using this API:
* </p>
* <ul>
* <li>
* <p>
* Send media data in real time: For example, a security camera can send frames in real time as it generates them.
* This approach minimizes the latency between the video recording and data sent on the wire. This is referred to as
* a continuous producer. In this case, a consumer application can read the stream in real time or when needed.
* </p>
* </li>
* <li>
* <p>
* Send media data offline (in batches): For example, a body camera might record video for hours and store it on the
* device. Later, when you connect the camera to the docking port, the camera can start a <code>PutMedia</code>
* session to send data to a Kinesis video stream. In this scenario, latency is not an issue.
* </p>
* </li>
* </ul>
* <p>
* When using this API, note the following considerations:
* </p>
* <ul>
* <li>
* <p>
* You must specify either <code>streamName</code> or <code>streamARN</code>, but not both.
* </p>
* </li>
* <li>
* <p>
* You might find it easier to use a single long-running <code>PutMedia</code> session and send a large number of
* media data fragments in the payload. Note that for each fragment received, Kinesis Video Streams sends one or
* more acknowledgements. Potential network considerations might cause you to not get all these acknowledgements as
* they are generated.
* </p>
* </li>
* <li>
* <p>
* You might choose multiple consecutive <code>PutMedia</code> sessions, each with fewer fragments to ensure that
* you get all acknowledgements from the service in real time.
* </p>
* </li>
* </ul>
* <note>
* <p>
* If you send data to the same stream on multiple simultaneous <code>PutMedia</code> sessions, the media fragments
* get interleaved on the stream. You should make sure that this is OK in your application scenario.
* </p>
* </note>
* <p>
* The following limits apply when using the <code>PutMedia</code> API:
* </p>
* <ul>
* <li>
* <p>
* A client can call <code>PutMedia</code> up to five times per second per stream.
* </p>
* </li>
* <li>
* <p>
* A client can send up to five fragments per second per stream.
* </p>
* </li>
* <li>
* <p>
* Kinesis Video Streams reads media data at a rate of up to 12.5 MB/second, or 100 Mbps during a
* <code>PutMedia</code> session.
* </p>
* </li>
* </ul>
* <p>
* Note the following constraints. In these cases, Kinesis Video Streams sends the Error acknowledgement in the
* response.
* </p>
* <ul>
* <li>
* <p>
* Fragments that have time codes spanning longer than 10 seconds and that contain more than 50 megabytes of data
* are not allowed.
* </p>
* </li>
* <li>
* <p>
* An MKV stream containing more than one MKV segment or containing disallowed MKV elements (like
* <code>track*</code>) also results in the Error acknowledgement.
* </p>
* </li>
* </ul>
* <p>
* Kinesis Video Streams stores each incoming fragment and related metadata in what is called a "chunk." The
* fragment metadata includes the following:
* </p>
* <ul>
* <li>
* <p>
* The MKV headers provided at the start of the <code>PutMedia</code> request
* </p>
* </li>
* <li>
* <p>
* The following Kinesis Video Streams-specific metadata for the fragment:
* </p>
* <ul>
* <li>
* <p>
* <code>server_timestamp</code> - Time stamp when Kinesis Video Streams started receiving the fragment.
* </p>
* </li>
* <li>
* <p>
* <code>producer_timestamp</code> - Time stamp, when the producer started recording the fragment. Kinesis Video
* Streams uses three pieces of information received in the request to calculate this value.
* </p>
* <ul>
* <li>
* <p>
* The fragment timecode value received in the request body along with the fragment.
* </p>
* </li>
* <li>
* <p>
* Two request headers: <code>producerStartTimestamp</code> (when the producer started recording) and
* <code>fragmentTimeCodeType</code> (whether the fragment timecode in the payload is absolute or relative).
* </p>
* </li>
* </ul>
* <p>
* Kinesis Video Streams then computes the <code>producer_timestamp</code> for the fragment as follows:
* </p>
* <p>
* If <code>fragmentTimeCodeType</code> is relative, then
* </p>
* <p>
* <code>producer_timestamp</code> = <code>producerStartTimeSamp</code> + fragment timecode
* </p>
* <p>
* If <code>fragmentTimeCodeType</code> is absolute, then
* </p>
* <p>
* <code>producer_timestamp</code> = fragment timecode (converted to milliseconds)
* </p>
* </li>
* <li>
* <p>
* Unique fragment number assigned by Kinesis Video Streams.
* </p>
* </li>
* </ul>
* <p/></li>
* </ul>
* <note>
* <p>
* When you make the <code>GetMedia</code> request, Kinesis Video Streams returns a stream of these chunks. The
* client can process the metadata as needed.
* </p>
* </note> <note>
* <p>
* This operation is only available for the AWS SDK for Java. It is not supported in AWS SDKs for other languages.
* </p>
* </note>
*
* @param request Represents the input of a <code>PutMedia</code> operation
* @param responseHandler Handler to asynchronously process the {@link com.amazonaws.services.kinesisvideo.model.AckEvent} that
* are received by the service.
* @return Result of the PutMedia operation returned by the service.
* @throws ResourceNotFoundException
* Status Code: 404, The stream with the given name does not exist.
* @throws NotAuthorizedException
* Status Code: 403, The caller is not authorized to perform an operation on the given stream, or the token
* has expired.
* @throws InvalidEndpointException
* Status Code: 400, Caller used wrong endpoint to write data to a stream. On receiving such an exception,
* the user must call <code>GetDataEndpoint</code> with <code>AccessMode</code> set to "READ" and use the
* endpoint Kinesis Video returns in the next <code>GetMedia</code> call.
* @throws InvalidArgumentException
* The value for this input parameter is invalid.
* @throws ClientLimitExceededException
* Kinesis Video Streams has throttled the request because you have exceeded the limit of allowed client
* calls. Try making the call later.
* @throws ConnectionLimitExceededException
* Kinesis Video Streams has throttled the request because you have exceeded the limit of allowed client
* connections.
* @sample AmazonKinesisVideoMedia.PutMedia
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/kinesis-video-media-2017-09-30/PutMedia" target="_top">AWS
* API Documentation</a>
*/
void putMedia(PutMediaRequest request, PutMediaAckResponseHandler responseHandler);
/**
* Closes the client and releases all resources like connection pools and threads.
*/
@Override
void close();
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-kinesisvideo/src/main/java/com/amazonaws/services/kinesisvideo/AmazonKinesisVideoPutMedia.java
|
Java
|
apache-2.0
| 10,008 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.sejda.sambox.pdmodel.graphics.optionalcontent;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import javax.imageio.ImageIO;
import org.junit.Assert;
import org.sejda.io.SeekableSources;
import org.sejda.sambox.cos.COSName;
import org.sejda.sambox.input.PDFParser;
import org.sejda.sambox.pdmodel.PDDocument;
import org.sejda.sambox.pdmodel.PDDocumentCatalog;
import org.sejda.sambox.pdmodel.PDPage;
import org.sejda.sambox.pdmodel.PDPageContentStream;
import org.sejda.sambox.pdmodel.PDPageContentStream.AppendMode;
import org.sejda.sambox.pdmodel.PDResources;
import org.sejda.sambox.pdmodel.PageMode;
import org.sejda.sambox.pdmodel.font.PDFont;
import org.sejda.sambox.pdmodel.font.PDType1Font;
import org.sejda.sambox.pdmodel.graphics.optionalcontent.PDOptionalContentProperties.BaseState;
import org.sejda.sambox.rendering.PDFRenderer;
import org.sejda.sambox.util.SpecVersionUtils;
import junit.framework.TestCase;
/**
* Tests optional content group functionality (also called layers).
*/
public class TestOptionalContentGroups extends TestCase
{
private final File testResultsDir = new File("target/test-output");
@Override
protected void setUp() throws Exception
{
super.setUp();
testResultsDir.mkdirs();
}
/**
* Tests OCG generation.
*
* @throws Exception if an error occurs
*/
public void testOCGGeneration() throws Exception
{
PDDocument doc = new PDDocument();
try
{
// Create new page
PDPage page = new PDPage();
doc.addPage(page);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
// Prepare OCG functionality
PDOptionalContentProperties ocprops = new PDOptionalContentProperties();
doc.getDocumentCatalog().setOCProperties(ocprops);
// ocprops.setBaseState(BaseState.ON); //ON=default
// Create OCG for background
PDOptionalContentGroup background = new PDOptionalContentGroup("background");
ocprops.addGroup(background);
assertTrue(ocprops.isGroupEnabled("background"));
// Create OCG for enabled
PDOptionalContentGroup enabled = new PDOptionalContentGroup("enabled");
ocprops.addGroup(enabled);
assertFalse(ocprops.setGroupEnabled("enabled", true));
assertTrue(ocprops.isGroupEnabled("enabled"));
// Create OCG for disabled
PDOptionalContentGroup disabled = new PDOptionalContentGroup("disabled");
ocprops.addGroup(disabled);
assertFalse(ocprops.setGroupEnabled("disabled", true));
assertTrue(ocprops.isGroupEnabled("disabled"));
assertTrue(ocprops.setGroupEnabled("disabled", false));
assertFalse(ocprops.isGroupEnabled("disabled"));
// Setup page content stream and paint background/title
PDPageContentStream contentStream = new PDPageContentStream(doc, page,
AppendMode.OVERWRITE, false);
PDFont font = PDType1Font.HELVETICA_BOLD;
contentStream.beginMarkedContent(COSName.OC, background);
contentStream.beginText();
contentStream.setFont(font, 14);
contentStream.newLineAtOffset(80, 700);
contentStream.showText("PDF 1.5: Optional Content Groups");
contentStream.endText();
font = PDType1Font.HELVETICA;
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 680);
contentStream.showText("You should see a green textline, but no red text line.");
contentStream.endText();
contentStream.endMarkedContent();
// Paint enabled layer
contentStream.beginMarkedContent(COSName.OC, enabled);
contentStream.setNonStrokingColor(Color.GREEN);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 600);
contentStream.showText("This is from an enabled layer. If you see this, that's good.");
contentStream.endText();
contentStream.endMarkedContent();
// Paint disabled layer
contentStream.beginMarkedContent(COSName.OC, disabled);
contentStream.setNonStrokingColor(Color.RED);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 500);
contentStream
.showText("This is from a disabled layer. If you see this, that's NOT good!");
contentStream.endText();
contentStream.endMarkedContent();
contentStream.close();
File targetFile = new File(testResultsDir, "ocg-generation.pdf");
doc.writeTo(targetFile);
}
finally
{
doc.close();
}
}
/**
* Tests OCG functions on a loaded PDF.
*
* @throws Exception if an error occurs
*/
public void testOCGConsumption() throws Exception
{
File pdfFile = new File(testResultsDir, "ocg-generation.pdf");
if (!pdfFile.exists())
{
testOCGGeneration();
}
try (PDDocument doc = PDFParser.parse(SeekableSources.seekableSourceFrom(pdfFile)))
{
assertEquals(SpecVersionUtils.V1_5, doc.getVersion());
PDDocumentCatalog catalog = doc.getDocumentCatalog();
PDPage page = doc.getPage(0);
PDResources resources = page.getResources();
COSName mc0 = COSName.getPDFName("oc1");
PDOptionalContentGroup ocg = (PDOptionalContentGroup) resources.getProperties(mc0);
assertNotNull(ocg);
assertEquals("background", ocg.getName());
assertNull(resources.getProperties(COSName.getPDFName("inexistent")));
PDOptionalContentProperties ocgs = catalog.getOCProperties();
assertEquals(BaseState.ON, ocgs.getBaseState());
Set<String> names = new java.util.HashSet<String>(Arrays.asList(ocgs.getGroupNames()));
assertEquals(3, names.size());
assertTrue(names.contains("background"));
assertTrue(ocgs.isGroupEnabled("background"));
assertTrue(ocgs.isGroupEnabled("enabled"));
assertFalse(ocgs.isGroupEnabled("disabled"));
ocgs.setGroupEnabled("background", false);
assertFalse(ocgs.isGroupEnabled("background"));
PDOptionalContentGroup background = ocgs.getGroup("background");
assertEquals(ocg.getName(), background.getName());
assertNull(ocgs.getGroup("inexistent"));
Collection<PDOptionalContentGroup> coll = ocgs.getOptionalContentGroups();
assertEquals(3, coll.size());
Set<String> nameSet = new HashSet<>();
for (PDOptionalContentGroup ocg2 : coll)
{
nameSet.add(ocg2.getName());
}
assertTrue(nameSet.contains("background"));
assertTrue(nameSet.contains("enabled"));
assertTrue(nameSet.contains("disabled"));
}
}
public void testOCGsWithSameNameCanHaveDifferentVisibility() throws Exception
{
PDDocument doc = new PDDocument();
try
{
// Create new page
PDPage page = new PDPage();
doc.addPage(page);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
// Prepare OCG functionality
PDOptionalContentProperties ocprops = new PDOptionalContentProperties();
doc.getDocumentCatalog().setOCProperties(ocprops);
// ocprops.setBaseState(BaseState.ON); //ON=default
// Create visible OCG
PDOptionalContentGroup visible = new PDOptionalContentGroup("layer");
ocprops.addGroup(visible);
assertTrue(ocprops.isGroupEnabled(visible));
// Create invisible OCG
PDOptionalContentGroup invisible = new PDOptionalContentGroup("layer");
ocprops.addGroup(invisible);
assertFalse(ocprops.setGroupEnabled(invisible, false));
assertFalse(ocprops.isGroupEnabled(invisible));
// Check that visible layer is still visible
assertTrue(ocprops.isGroupEnabled(visible));
// Setup page content stream and paint background/title
PDPageContentStream contentStream = new PDPageContentStream(doc, page,
AppendMode.OVERWRITE, false);
PDFont font = PDType1Font.HELVETICA_BOLD;
contentStream.beginMarkedContent(COSName.OC, visible);
contentStream.beginText();
contentStream.setFont(font, 14);
contentStream.newLineAtOffset(80, 700);
contentStream.showText("PDF 1.5: Optional Content Groups");
contentStream.endText();
font = PDType1Font.HELVETICA;
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 680);
contentStream.showText("You should see this text, but no red text line.");
contentStream.endText();
contentStream.endMarkedContent();
// Paint disabled layer
contentStream.beginMarkedContent(COSName.OC, invisible);
contentStream.setNonStrokingColor(Color.RED);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 500);
contentStream
.showText("This is from a disabled layer. If you see this, that's NOT good!");
contentStream.endText();
contentStream.endMarkedContent();
contentStream.close();
File targetFile = new File(testResultsDir, "ocg-generation-same-name.pdf");
doc.writeTo(targetFile);
}
finally
{
doc.close();
}
}
/**
* PDFBOX-4496: setGroupEnabled(String, boolean) must catch all OCGs of a name even when several names are
* identical.
*
* @throws IOException
*/
public void testOCGGenerationSameNameCanHaveSameVisibilityOff() throws IOException
{
BufferedImage expectedImage;
BufferedImage actualImage;
try (PDDocument doc = new PDDocument())
{
// Create new page
PDPage page = new PDPage();
doc.addPage(page);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
// Prepare OCG functionality
PDOptionalContentProperties ocprops = new PDOptionalContentProperties();
doc.getDocumentCatalog().setOCProperties(ocprops);
// ocprops.setBaseState(BaseState.ON); //ON=default
// Create OCG for background
PDOptionalContentGroup background = new PDOptionalContentGroup("background");
ocprops.addGroup(background);
assertTrue(ocprops.isGroupEnabled("background"));
// Create OCG for enabled
PDOptionalContentGroup enabled = new PDOptionalContentGroup("science");
ocprops.addGroup(enabled);
assertFalse(ocprops.setGroupEnabled("science", true));
assertTrue(ocprops.isGroupEnabled("science"));
// Create OCG for disabled1
PDOptionalContentGroup disabled1 = new PDOptionalContentGroup("alternative");
ocprops.addGroup(disabled1);
// Create OCG for disabled2 with same name as disabled1
PDOptionalContentGroup disabled2 = new PDOptionalContentGroup("alternative");
ocprops.addGroup(disabled2);
assertFalse(ocprops.setGroupEnabled("alternative", false));
assertFalse(ocprops.isGroupEnabled("alternative"));
// Setup page content stream and paint background/title
PDPageContentStream contentStream = new PDPageContentStream(doc, page,
AppendMode.OVERWRITE, false);
PDFont font = PDType1Font.HELVETICA_BOLD;
contentStream.beginMarkedContent(COSName.OC, background);
contentStream.beginText();
contentStream.setFont(font, 14);
contentStream.newLineAtOffset(80, 700);
contentStream.showText("PDF 1.5: Optional Content Groups");
contentStream.endText();
contentStream.endMarkedContent();
font = PDType1Font.HELVETICA;
// Paint enabled layer
contentStream.beginMarkedContent(COSName.OC, enabled);
contentStream.setNonStrokingColor(Color.GREEN);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 600);
contentStream.showText("The earth is a sphere");
contentStream.endText();
contentStream.endMarkedContent();
// Paint disabled layer1
contentStream.beginMarkedContent(COSName.OC, disabled1);
contentStream.setNonStrokingColor(Color.RED);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 500);
contentStream.showText("Alternative 1: The earth is a flat circle");
contentStream.endText();
contentStream.endMarkedContent();
// Paint disabled layer2
contentStream.beginMarkedContent(COSName.OC, disabled2);
contentStream.setNonStrokingColor(Color.BLUE);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 450);
contentStream.showText("Alternative 2: The earth is a flat parallelogram");
contentStream.endText();
contentStream.endMarkedContent();
contentStream.close();
doc.getDocumentCatalog().setPageMode(PageMode.USE_OPTIONAL_CONTENT);
File targetFile = new File(testResultsDir, "ocg-generation-same-name-off.pdf");
doc.writeTo(targetFile.getAbsolutePath());
}
// render PDF with science disabled and alternatives with same name enabled
try (PDDocument doc = PDDocument
.load(new File(testResultsDir, "ocg-generation-same-name-off.pdf")))
{
doc.getDocumentCatalog().getOCProperties().setGroupEnabled("background", false);
doc.getDocumentCatalog().getOCProperties().setGroupEnabled("science", false);
doc.getDocumentCatalog().getOCProperties().setGroupEnabled("alternative", true);
actualImage = new PDFRenderer(doc).renderImage(0, 2);
ImageIO.write(actualImage, "png",
new File(testResultsDir, "ocg-generation-same-name-off-actual.png"));
}
// create PDF without OCGs to created expected rendering
try (PDDocument doc2 = new PDDocument())
{
// Create new page
PDPage page = new PDPage();
doc2.addPage(page);
PDResources resources = page.getResources();
if (resources == null)
{
resources = new PDResources();
page.setResources(resources);
}
try (PDPageContentStream contentStream = new PDPageContentStream(doc2, page,
AppendMode.OVERWRITE, false))
{
PDFont font = PDType1Font.HELVETICA;
contentStream.setNonStrokingColor(Color.RED);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 500);
contentStream.showText("Alternative 1: The earth is a flat circle");
contentStream.endText();
contentStream.setNonStrokingColor(Color.BLUE);
contentStream.beginText();
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(80, 450);
contentStream.showText("Alternative 2: The earth is a flat parallelogram");
contentStream.endText();
}
File targetFile = new File(testResultsDir, "ocg-generation-same-name-off-expected.pdf");
doc2.writeTo(targetFile.getAbsolutePath());
}
try (PDDocument doc = PDDocument
.load(new File(testResultsDir, "ocg-generation-same-name-off-expected.pdf")))
{
expectedImage = new PDFRenderer(doc).renderImage(0, 2);
ImageIO.write(expectedImage, "png",
new File(testResultsDir, "ocg-generation-same-name-off-expected.png"));
}
// compare images
DataBufferInt expectedData = (DataBufferInt) expectedImage.getRaster().getDataBuffer();
DataBufferInt actualData = (DataBufferInt) actualImage.getRaster().getDataBuffer();
Assert.assertArrayEquals(expectedData.getData(), actualData.getData());
}
}
|
torakiki/sambox
|
src/test/java/org/sejda/sambox/pdmodel/graphics/optionalcontent/TestOptionalContentGroups.java
|
Java
|
apache-2.0
| 18,662 |
require_relative '../../../../test_helper'
require_relative '../endpoint_test_helper'
class CommentsTest < Minitest::Test
extend Smartsheet::Test::EndpointHelper
attr_accessor :mock_client
attr_accessor :smartsheet_client
def category
smartsheet_client.sheets.comments
end
def self.endpoints
[
{
symbol: :add,
method: :post,
url: ['sheets', :sheet_id, 'discussions', :discussion_id, 'comments'],
args: {sheet_id: 123, discussion_id: 234, body: {}},
has_params: false,
headers: nil
},
# TODO: Add this!
# {
# symbol: :add_with_file,
# method: :post,
# url: ['sheets', :sheet_id, 'rows', :row_id, 'discussions'],
# args: {sheet_id: 123, row_id: 234, body: {}},
# has_params: false,
# headers: nil
# },
{
symbol: :update,
method: :put,
url: ['sheets', :sheet_id, 'comments', :comment_id],
args: {sheet_id: 123, comment_id: 234, body: {}},
has_params: false,
headers: nil
},
{
symbol: :delete,
method: :delete,
url: ['sheets', :sheet_id, 'comments', :comment_id],
args: {sheet_id: 123, comment_id: 234},
has_params: false,
headers: nil
},
{
symbol: :get,
method: :get,
url: ['sheets', :sheet_id, 'comments', :comment_id],
args: {sheet_id: 123, comment_id: 234},
has_params: false,
headers: nil
},
]
end
define_setup
define_endpoints_tests
end
|
smartsheet-platform/smartsheet-ruby-sdk
|
test/unit/smartsheet/endpoints/sheets/comments_test.rb
|
Ruby
|
apache-2.0
| 1,724 |
/*
* Copyright 2002-2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.FlashMap;
import org.springframework.web.servlet.FlashMapManager;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.SmartView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;
/**
* View that redirects to an absolute, context relative, or current request
* relative URL. The URL may be a URI template in which case the URI template
* variables will be replaced with values available in the model. By default
* all primitive model attributes (or collections thereof) are exposed as HTTP
* query parameters (assuming they've not been used as URI template variables),
* but this behavior can be changed by overriding the
* {@link #isEligibleProperty(String, Object)} method.
*
* <p>A URL for this view is supposed to be a HTTP redirect URL, i.e.
* suitable for HttpServletResponse's {@code sendRedirect} method, which
* is what actually does the redirect if the HTTP 1.0 flag is on, or via sending
* back an HTTP 303 code - if the HTTP 1.0 compatibility flag is off.
*
* <p>Note that while the default value for the "contextRelative" flag is off,
* you will probably want to almost always set it to true. With the flag off,
* URLs starting with "/" are considered relative to the web server root, while
* with the flag on, they are considered relative to the web application root.
* Since most web applications will never know or care what their context path
* actually is, they are much better off setting this flag to true, and submitting
* paths which are to be considered relative to the web application root.
*
* <p><b>NOTE when using this redirect view in a Portlet environment:</b> Make sure
* that your controller respects the Portlet {@code sendRedirect} constraints.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Colin Sampaleanu
* @author Sam Brannen
* @author Arjen Poutsma
* @author Rossen Stoyanchev
* @see #setContextRelative
* @see #setHttp10Compatible
* @see #setExposeModelAttributes
* @see javax.servlet.http.HttpServletResponse#sendRedirect
*/
public class RedirectView extends AbstractUrlBasedView implements SmartView {
private static final Pattern URI_TEMPLATE_VARIABLE_PATTERN = Pattern.compile("\\{([^/]+?)\\}");
private boolean contextRelative = false;
private boolean http10Compatible = true;
private boolean exposeModelAttributes = true;
private String encodingScheme;
private HttpStatus statusCode;
private boolean expandUriTemplateVariables = true;
private boolean propagateQueryParams = false;
/**
* Constructor for use as a bean.
*/
public RedirectView() {
setExposePathVariables(false);
}
/**
* Create a new RedirectView with the given URL.
* <p>The given URL will be considered as relative to the web server,
* not as relative to the current ServletContext.
* @param url the URL to redirect to
* @see #RedirectView(String, boolean)
*/
public RedirectView(String url) {
super(url);
setExposePathVariables(false);
}
/**
* Create a new RedirectView with the given URL.
* @param url the URL to redirect to
* @param contextRelative whether to interpret the given URL as
* relative to the current ServletContext
*/
public RedirectView(String url, boolean contextRelative) {
super(url);
this.contextRelative = contextRelative;
setExposePathVariables(false);
}
/**
* Create a new RedirectView with the given URL.
* @param url the URL to redirect to
* @param contextRelative whether to interpret the given URL as
* relative to the current ServletContext
* @param http10Compatible whether to stay compatible with HTTP 1.0 clients
*/
public RedirectView(String url, boolean contextRelative, boolean http10Compatible) {
super(url);
this.contextRelative = contextRelative;
this.http10Compatible = http10Compatible;
setExposePathVariables(false);
}
/**
* Create a new RedirectView with the given URL.
* @param url the URL to redirect to
* @param contextRelative whether to interpret the given URL as
* relative to the current ServletContext
* @param http10Compatible whether to stay compatible with HTTP 1.0 clients
* @param exposeModelAttributes whether or not model attributes should be
* exposed as query parameters
*/
public RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes) {
super(url);
this.contextRelative = contextRelative;
this.http10Compatible = http10Compatible;
this.exposeModelAttributes = exposeModelAttributes;
setExposePathVariables(false);
}
/**
* Set whether to interpret a given URL that starts with a slash ("/")
* as relative to the current ServletContext, i.e. as relative to the
* web application root.
* <p>Default is "false": A URL that starts with a slash will be interpreted
* as absolute, i.e. taken as-is. If "true", the context path will be
* prepended to the URL in such a case.
* @see javax.servlet.http.HttpServletRequest#getContextPath
*/
public void setContextRelative(boolean contextRelative) {
this.contextRelative = contextRelative;
}
/**
* Set whether to stay compatible with HTTP 1.0 clients.
* <p>In the default implementation, this will enforce HTTP status code 302
* in any case, i.e. delegate to {@code HttpServletResponse.sendRedirect}.
* Turning this off will send HTTP status code 303, which is the correct
* code for HTTP 1.1 clients, but not understood by HTTP 1.0 clients.
* <p>Many HTTP 1.1 clients treat 302 just like 303, not making any
* difference. However, some clients depend on 303 when redirecting
* after a POST request; turn this flag off in such a scenario.
* @see javax.servlet.http.HttpServletResponse#sendRedirect
*/
public void setHttp10Compatible(boolean http10Compatible) {
this.http10Compatible = http10Compatible;
}
/**
* Set the {@code exposeModelAttributes} flag which denotes whether
* or not model attributes should be exposed as HTTP query parameters.
* <p>Defaults to {@code true}.
*/
public void setExposeModelAttributes(final boolean exposeModelAttributes) {
this.exposeModelAttributes = exposeModelAttributes;
}
/**
* Set the encoding scheme for this view.
* <p>Default is the request's encoding scheme
* (which is ISO-8859-1 if not specified otherwise).
*/
public void setEncodingScheme(String encodingScheme) {
this.encodingScheme = encodingScheme;
}
/**
* Set the status code for this view.
* <p>Default is to send 302/303, depending on the value of the
* {@link #setHttp10Compatible(boolean) http10Compatible} flag.
*/
public void setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
}
/**
* Whether to treat the redirect URL as a URI template.
* Set this flag to {@code false} if the redirect URL contains open
* and close curly braces "{", "}" and you don't want them interpreted
* as URI variables.
* <p>Defaults to {@code true}.
*/
public void setExpandUriTemplateVariables(boolean expandUriTemplateVariables) {
this.expandUriTemplateVariables = expandUriTemplateVariables;
}
/**
* When set to {@code true} the query string of the current URL is appended
* and thus propagated through to the redirected URL.
* <p>Defaults to {@code false}.
* @since 4.1
*/
public void setPropagateQueryParams(boolean propagateQueryParams) {
this.propagateQueryParams = propagateQueryParams;
}
/**
* Whether to propagate the query params of the current URL.
* @since 4.1
*/
public boolean isPropagateQueryProperties() {
return this.propagateQueryParams;
}
/**
* Returns "true" indicating this view performs a redirect.
*/
@Override
public boolean isRedirectView() {
return true;
}
/**
* An ApplicationContext is not strictly required for RedirectView.
*/
@Override
protected boolean isContextRequired() {
return false;
}
/**
* Convert model to request parameters and redirect to the given URL.
* @see #appendQueryProperties
* @see #sendRedirect
*/
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
HttpServletResponse response) throws IOException {
String targetUrl = createTargetUrl(model, request);
targetUrl = updateTargetUrl(targetUrl, model, request, response);
FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
if (!CollectionUtils.isEmpty(flashMap)) {
UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build();
flashMap.setTargetRequestPath(uriComponents.getPath());
flashMap.addTargetRequestParams(uriComponents.getQueryParams());
FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
if (flashMapManager == null) {
throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set");
}
flashMapManager.saveOutputFlashMap(flashMap, request, response);
}
sendRedirect(request, response, targetUrl, this.http10Compatible);
}
/**
* Create the target URL by checking if the redirect string is a URI template first,
* expanding it with the given model, and then optionally appending simple type model
* attributes as query String parameters.
*/
protected final String createTargetUrl(Map<String, Object> model, HttpServletRequest request)
throws UnsupportedEncodingException {
// Prepare target URL.
StringBuilder targetUrl = new StringBuilder();
if (this.contextRelative && getUrl().startsWith("/")) {
// Do not apply context path to relative URLs.
targetUrl.append(request.getContextPath());
}
targetUrl.append(getUrl());
String enc = this.encodingScheme;
if (enc == null) {
enc = request.getCharacterEncoding();
}
if (enc == null) {
enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
}
if (this.expandUriTemplateVariables && StringUtils.hasText(targetUrl)) {
Map<String, String> variables = getCurrentRequestUriVariables(request);
targetUrl = replaceUriTemplateVariables(targetUrl.toString(), model, variables, enc);
}
if (isPropagateQueryProperties()) {
appendCurrentQueryParams(targetUrl, request);
}
if (this.exposeModelAttributes) {
appendQueryProperties(targetUrl, model, enc);
}
return targetUrl.toString();
}
/**
* Replace URI template variables in the target URL with encoded model
* attributes or URI variables from the current request. Model attributes
* referenced in the URL are removed from the model.
* @param targetUrl the redirect URL
* @param model Map that contains model attributes
* @param currentUriVariables current request URI variables to use
* @param encodingScheme the encoding scheme to use
* @throws UnsupportedEncodingException if string encoding failed
*/
protected StringBuilder replaceUriTemplateVariables(
String targetUrl, Map<String, Object> model, Map<String, String> currentUriVariables, String encodingScheme)
throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
Matcher matcher = URI_TEMPLATE_VARIABLE_PATTERN.matcher(targetUrl);
int endLastMatch = 0;
while (matcher.find()) {
String name = matcher.group(1);
Object value = (model.containsKey(name) ? model.remove(name) : currentUriVariables.get(name));
if (value == null) {
throw new IllegalArgumentException("Model has no value for key '" + name + "'");
}
result.append(targetUrl.substring(endLastMatch, matcher.start()));
result.append(UriUtils.encodePathSegment(value.toString(), encodingScheme));
endLastMatch = matcher.end();
}
result.append(targetUrl.substring(endLastMatch, targetUrl.length()));
return result;
}
@SuppressWarnings("unchecked")
private Map<String, String> getCurrentRequestUriVariables(HttpServletRequest request) {
String name = HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE;
Map<String, String> uriVars = (Map<String, String>) request.getAttribute(name);
return (uriVars != null) ? uriVars : Collections.<String, String> emptyMap();
}
/**
* Append the query string of the current request to the target redirect URL.
* @param targetUrl the StringBuilder to append the properties to
* @param request the current request
* @since 4.1
*/
protected void appendCurrentQueryParams(StringBuilder targetUrl, HttpServletRequest request) {
String query = request.getQueryString();
if (StringUtils.hasText(query)) {
// Extract anchor fragment, if any.
String fragment = null;
int anchorIndex = targetUrl.indexOf("#");
if (anchorIndex > -1) {
fragment = targetUrl.substring(anchorIndex);
targetUrl.delete(anchorIndex, targetUrl.length());
}
if (targetUrl.toString().indexOf('?') < 0) {
targetUrl.append('?').append(query);
}
else {
targetUrl.append('&').append(query);
}
// Append anchor fragment, if any, to end of URL.
if (fragment != null) {
targetUrl.append(fragment);
}
}
}
/**
* Append query properties to the redirect URL.
* Stringifies, URL-encodes and formats model attributes as query properties.
* @param targetUrl the StringBuilder to append the properties to
* @param model Map that contains model attributes
* @param encodingScheme the encoding scheme to use
* @throws UnsupportedEncodingException if string encoding failed
* @see #queryProperties
*/
@SuppressWarnings("unchecked")
protected void appendQueryProperties(StringBuilder targetUrl, Map<String, Object> model, String encodingScheme)
throws UnsupportedEncodingException {
// Extract anchor fragment, if any.
String fragment = null;
int anchorIndex = targetUrl.indexOf("#");
if (anchorIndex > -1) {
fragment = targetUrl.substring(anchorIndex);
targetUrl.delete(anchorIndex, targetUrl.length());
}
// If there aren't already some parameters, we need a "?".
boolean first = (targetUrl.toString().indexOf('?') < 0);
for (Map.Entry<String, Object> entry : queryProperties(model).entrySet()) {
Object rawValue = entry.getValue();
Iterator<Object> valueIter;
if (rawValue != null && rawValue.getClass().isArray()) {
valueIter = Arrays.asList(ObjectUtils.toObjectArray(rawValue)).iterator();
}
else if (rawValue instanceof Collection) {
valueIter = ((Collection<Object>) rawValue).iterator();
}
else {
valueIter = Collections.singleton(rawValue).iterator();
}
while (valueIter.hasNext()) {
Object value = valueIter.next();
if (first) {
targetUrl.append('?');
first = false;
}
else {
targetUrl.append('&');
}
String encodedKey = urlEncode(entry.getKey(), encodingScheme);
String encodedValue = (value != null ? urlEncode(value.toString(), encodingScheme) : "");
targetUrl.append(encodedKey).append('=').append(encodedValue);
}
}
// Append anchor fragment, if any, to end of URL.
if (fragment != null) {
targetUrl.append(fragment);
}
}
/**
* Determine name-value pairs for query strings, which will be stringified,
* URL-encoded and formatted by {@link #appendQueryProperties}.
* <p>This implementation filters the model through checking
* {@link #isEligibleProperty(String, Object)} for each element,
* by default accepting Strings, primitives and primitive wrappers only.
* @param model the original model Map
* @return the filtered Map of eligible query properties
* @see #isEligibleProperty(String, Object)
*/
protected Map<String, Object> queryProperties(Map<String, Object> model) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> entry : model.entrySet()) {
if (isEligibleProperty(entry.getKey(), entry.getValue())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
}
/**
* Determine whether the given model element should be exposed
* as a query property.
* <p>The default implementation considers Strings and primitives
* as eligible, and also arrays and Collections/Iterables with
* corresponding elements. This can be overridden in subclasses.
* @param key the key of the model element
* @param value the value of the model element
* @return whether the element is eligible as query property
*/
protected boolean isEligibleProperty(String key, Object value) {
if (value == null) {
return false;
}
if (isEligibleValue(value)) {
return true;
}
if (value.getClass().isArray()) {
int length = Array.getLength(value);
if (length == 0) {
return false;
}
for (int i = 0; i < length; i++) {
Object element = Array.get(value, i);
if (!isEligibleValue(element)) {
return false;
}
}
return true;
}
if (value instanceof Collection) {
Collection<?> coll = (Collection<?>) value;
if (coll.isEmpty()) {
return false;
}
for (Object element : coll) {
if (!isEligibleValue(element)) {
return false;
}
}
return true;
}
return false;
}
/**
* Determine whether the given model element value is eligible for exposure.
* <p>The default implementation considers primitives, Strings, Numbers, Dates,
* URIs, URLs and Locale objects as eligible. This can be overridden in subclasses.
* @param value the model element value
* @return whether the element value is eligible
* @see BeanUtils#isSimpleValueType
*/
protected boolean isEligibleValue(Object value) {
return (value != null && BeanUtils.isSimpleValueType(value.getClass()));
}
/**
* URL-encode the given input String with the given encoding scheme.
* <p>The default implementation uses {@code URLEncoder.encode(input, enc)}.
* @param input the unencoded input String
* @param encodingScheme the encoding scheme
* @return the encoded output String
* @throws UnsupportedEncodingException if thrown by the JDK URLEncoder
* @see java.net.URLEncoder#encode(String, String)
* @see java.net.URLEncoder#encode(String)
*/
protected String urlEncode(String input, String encodingScheme) throws UnsupportedEncodingException {
return (input != null ? URLEncoder.encode(input, encodingScheme) : null);
}
/**
* Find the registered {@link RequestDataValueProcessor}, if any, and allow
* it to update the redirect target URL.
* @param targetUrl the given redirect URL
* @return the updated URL or the same as URL as the one passed in
*/
protected String updateTargetUrl(String targetUrl, Map<String, Object> model,
HttpServletRequest request, HttpServletResponse response) {
WebApplicationContext wac = getWebApplicationContext();
if (wac == null) {
wac = RequestContextUtils.findWebApplicationContext(request, getServletContext());
}
if (wac != null && wac.containsBean(RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME)) {
RequestDataValueProcessor processor = wac.getBean(
RequestContextUtils.REQUEST_DATA_VALUE_PROCESSOR_BEAN_NAME, RequestDataValueProcessor.class);
return processor.processUrl(request, targetUrl);
}
return targetUrl;
}
/**
* Send a redirect back to the HTTP client
* @param request current HTTP request (allows for reacting to request method)
* @param response current HTTP response (for sending response headers)
* @param targetUrl the target URL to redirect to
* @param http10Compatible whether to stay compatible with HTTP 1.0 clients
* @throws IOException if thrown by response methods
*/
protected void sendRedirect(HttpServletRequest request, HttpServletResponse response,
String targetUrl, boolean http10Compatible) throws IOException {
String encodedRedirectURL = response.encodeRedirectURL(targetUrl);
if (http10Compatible) {
HttpStatus attributeStatusCode = (HttpStatus) request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE);
if (this.statusCode != null) {
response.setStatus(this.statusCode.value());
response.setHeader("Location", encodedRedirectURL);
}
else if (attributeStatusCode != null) {
response.setStatus(attributeStatusCode.value());
response.setHeader("Location", encodedRedirectURL);
}
else {
// Send status code 302 by default.
response.sendRedirect(encodedRedirectURL);
}
}
else {
HttpStatus statusCode = getHttp11StatusCode(request, response, targetUrl);
response.setStatus(statusCode.value());
response.setHeader("Location", encodedRedirectURL);
}
}
/**
* Determines the status code to use for HTTP 1.1 compatible requests.
* <p>The default implementation returns the {@link #setStatusCode(HttpStatus) statusCode}
* property if set, or the value of the {@link #RESPONSE_STATUS_ATTRIBUTE} attribute.
* If neither are set, it defaults to {@link HttpStatus#SEE_OTHER} (303).
* @param request the request to inspect
* @param response the servlet response
* @param targetUrl the target URL
* @return the response status
*/
protected HttpStatus getHttp11StatusCode(
HttpServletRequest request, HttpServletResponse response, String targetUrl) {
if (this.statusCode != null) {
return this.statusCode;
}
HttpStatus attributeStatusCode = (HttpStatus) request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE);
if (attributeStatusCode != null) {
return attributeStatusCode;
}
return HttpStatus.SEE_OTHER;
}
}
|
QBNemo/spring-mvc-showcase
|
src/main/java/org/springframework/web/servlet/view/RedirectView.java
|
Java
|
apache-2.0
| 22,944 |
#include <sgx_fcntl_util.h>
#include <sgx_ocall_util.h>
#include <sgx_thread.h>
INIT_LOCK(ocall_open2);
INIT_LOCK(ocall_creat);
INIT_LOCK(ocall_openat2);
INIT_LOCK(ocall_fcntl1);
INIT_LOCK(ocall_fcntl2);
INIT_LOCK(ocall_fcntl3);
int sgx_wrapper_open(const char *pathname, int flags, ...)
{
va_list ap;
mode_t mode = 0;
va_start(ap, flags);
if (flags & O_CREAT)
mode = va_arg(ap, mode_t);
else
mode = 0777;
va_end(ap);
int retval;
sgx_status_t status = SAFE_INVOKE(ocall_open2, &retval, pathname, flags, mode);
CHECK_STATUS(status);
return retval;
}
int sgx_wrapper_creat(const char *pathname, unsigned int mode)
{
int retval;
sgx_status_t status = SAFE_INVOKE(ocall_creat, &retval, pathname, mode);
CHECK_STATUS(status);
return retval;
}
int sgx_wrapper_openat(int dirfd, const char *pathname, int flags, ...)
{
va_list ap;
mode_t mode = 0;
va_start(ap, flags);
if (flags & O_CREAT)
mode = va_arg(ap, mode_t);
else
mode = 0777;
va_end(ap);
int retval;
sgx_status_t status = SAFE_INVOKE(ocall_openat2, &retval, dirfd, pathname, flags, mode);
CHECK_STATUS(status);
return retval;
}
int sgx_wrapper_fcntl(int fd, int cmd, ...)
{
sgx_status_t status;
va_list ap;
int retval;
va_start(ap, cmd);
long larg = -1;
struct flock *flarg = NULL;
// Fix me: Should refer to the linux kernel in order to do it in the right way
switch(cmd) {
case F_GETFD:
case F_GETFL:
case F_GETOWN:
va_end(ap);
status = SAFE_INVOKE(ocall_fcntl1, &retval, fd, cmd);
CHECK_STATUS(status);
return retval;
case F_DUPFD:
case F_DUPFD_CLOEXEC:
case F_SETFD:
case F_SETFL:
case F_SETOWN:
larg = va_arg(ap, long);
// fprintf(stderr, "fcntl setfd or setfl with flag: %d \n", larg);
status = SAFE_INVOKE(ocall_fcntl2, &retval, fd, cmd, larg);
CHECK_STATUS(status);
return retval;
case F_SETLK:
case F_GETLK:
case F_SETLKW:
flarg = va_arg(ap, struct flock *);
status = SAFE_INVOKE(ocall_fcntl3, &retval, fd, cmd, flarg, sizeof(struct flock));
CHECK_STATUS(status);
return retval;
default:
va_end(ap);
return -1;
};
return -1;
}
|
shwetasshinde24/Panoply
|
case-studies/h2o/src/H2oEnclave/IO/sgx_fcntl.cpp
|
C++
|
apache-2.0
| 2,173 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ssmincidents.model;
import java.io.Serializable;
import javax.annotation.Generated;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/ssm-incidents-2018-05-10/ListTimelineEvents" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListTimelineEventsResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
/**
* <p>
* Details about each event that occurred during the incident.
* </p>
*/
private java.util.List<EventSummary> eventSummaries;
/**
* <p>
* The pagination token to continue to the next page of results.
* </p>
*/
private String nextToken;
/**
* <p>
* Details about each event that occurred during the incident.
* </p>
*
* @return Details about each event that occurred during the incident.
*/
public java.util.List<EventSummary> getEventSummaries() {
return eventSummaries;
}
/**
* <p>
* Details about each event that occurred during the incident.
* </p>
*
* @param eventSummaries
* Details about each event that occurred during the incident.
*/
public void setEventSummaries(java.util.Collection<EventSummary> eventSummaries) {
if (eventSummaries == null) {
this.eventSummaries = null;
return;
}
this.eventSummaries = new java.util.ArrayList<EventSummary>(eventSummaries);
}
/**
* <p>
* Details about each event that occurred during the incident.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setEventSummaries(java.util.Collection)} or {@link #withEventSummaries(java.util.Collection)} if you want
* to override the existing values.
* </p>
*
* @param eventSummaries
* Details about each event that occurred during the incident.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTimelineEventsResult withEventSummaries(EventSummary... eventSummaries) {
if (this.eventSummaries == null) {
setEventSummaries(new java.util.ArrayList<EventSummary>(eventSummaries.length));
}
for (EventSummary ele : eventSummaries) {
this.eventSummaries.add(ele);
}
return this;
}
/**
* <p>
* Details about each event that occurred during the incident.
* </p>
*
* @param eventSummaries
* Details about each event that occurred during the incident.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTimelineEventsResult withEventSummaries(java.util.Collection<EventSummary> eventSummaries) {
setEventSummaries(eventSummaries);
return this;
}
/**
* <p>
* The pagination token to continue to the next page of results.
* </p>
*
* @param nextToken
* The pagination token to continue to the next page of results.
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* <p>
* The pagination token to continue to the next page of results.
* </p>
*
* @return The pagination token to continue to the next page of results.
*/
public String getNextToken() {
return this.nextToken;
}
/**
* <p>
* The pagination token to continue to the next page of results.
* </p>
*
* @param nextToken
* The pagination token to continue to the next page of results.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListTimelineEventsResult withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEventSummaries() != null)
sb.append("EventSummaries: ").append(getEventSummaries()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListTimelineEventsResult == false)
return false;
ListTimelineEventsResult other = (ListTimelineEventsResult) obj;
if (other.getEventSummaries() == null ^ this.getEventSummaries() == null)
return false;
if (other.getEventSummaries() != null && other.getEventSummaries().equals(this.getEventSummaries()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEventSummaries() == null) ? 0 : getEventSummaries().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListTimelineEventsResult clone() {
try {
return (ListTimelineEventsResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
aws/aws-sdk-java
|
aws-java-sdk-ssmincidents/src/main/java/com/amazonaws/services/ssmincidents/model/ListTimelineEventsResult.java
|
Java
|
apache-2.0
| 6,834 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Contributions from 2013-2017 where performed either by US government
* employees, or under US Veterans Health Administration contracts.
*
* US Veterans Health Administration contributions by government employees
* are work of the U.S. Government and are not subject to copyright
* protection in the United States. Portions contributed by government
* employees are USGovWork (17USC §105). Not subject to copyright.
*
* Contribution by contractors to the US Veterans Health Administration
* during this period are contractually contributed under the
* Apache License, Version 2.0.
*
* See: https://www.usa.gov/government-works
*
* Contributions prior to 2013:
*
* Copyright (C) International Health Terminology Standards Development Organisation.
* Licensed under the Apache License, Version 2.0.
*
*/
package sh.isaac.api;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import javafx.concurrent.Task;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.component.concept.ConceptChronology;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.externalizable.IsaacObjectType;
/**
* The Class Util.
*
* @author kec
*/
public class Util {
private static final Logger LOG = LogManager.getLogger(Util.class);
/**
* Adds the to task set and wait till done.
*
* @param <T> the generic type
* @param task the task
* @return the t
* @throws InterruptedException the interrupted exception
* @throws ExecutionException the execution exception
*/
public static <T> T addToTaskSetAndWaitTillDone(Task<T> task)
throws InterruptedException, ExecutionException {
Get.activeTasks().add(task);
try {
final T returnValue = task.get();
return returnValue;
} finally {
Get.activeTasks().remove(task);
}
}
/**
* String array to path array.
*
* @param strings the strings
* @return the path[]
*/
public static Path[] stringArrayToPathArray(String... strings) {
final Path[] paths = new Path[strings.length];
for (int i = 0; i < paths.length; i++) {
paths[i] = Paths.get(strings[i]);
}
return paths;
}
/**
* Convenience method to find the nearest concept related to a semantic. Recursively walks referenced components until it finds a concept.
* @param nid
* @return the nearest concept nid, or empty, if no concept can be found.
*/
public static Optional<Integer> getNearestConcept(int nid) {
Optional<? extends Chronology> c = Get.identifiedObjectService().getChronology(nid);
if (c.isPresent()) {
if (c.get().getIsaacObjectType() == IsaacObjectType.SEMANTIC) {
return getNearestConcept(((SemanticChronology)c.get()).getReferencedComponentNid());
}
else if (c.get().getIsaacObjectType() == IsaacObjectType.CONCEPT) {
return Optional.of(((ConceptChronology)c.get()).getNid());
}
else {
LOG.warn("Unexpected object type: " + c.get().getIsaacObjectType());
}
}
return Optional.empty();
}
}
|
OSEHRA/ISAAC
|
core/api/src/main/java/sh/isaac/api/Util.java
|
Java
|
apache-2.0
| 3,905 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v10/resources/shared_criterion.proto
package com.google.ads.googleads.v10.resources;
public interface SharedCriterionOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.resources.SharedCriterion)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Immutable. The resource name of the shared criterion.
* Shared set resource names have the form:
* `customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The resourceName.
*/
java.lang.String getResourceName();
/**
* <pre>
* Immutable. The resource name of the shared criterion.
* Shared set resource names have the form:
* `customers/{customer_id}/sharedCriteria/{shared_set_id}~{criterion_id}`
* </pre>
*
* <code>string resource_name = 1 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for resourceName.
*/
com.google.protobuf.ByteString
getResourceNameBytes();
/**
* <pre>
* Immutable. The shared set to which the shared criterion belongs.
* </pre>
*
* <code>optional string shared_set = 10 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return Whether the sharedSet field is set.
*/
boolean hasSharedSet();
/**
* <pre>
* Immutable. The shared set to which the shared criterion belongs.
* </pre>
*
* <code>optional string shared_set = 10 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The sharedSet.
*/
java.lang.String getSharedSet();
/**
* <pre>
* Immutable. The shared set to which the shared criterion belongs.
* </pre>
*
* <code>optional string shared_set = 10 [(.google.api.field_behavior) = IMMUTABLE, (.google.api.resource_reference) = { ... }</code>
* @return The bytes for sharedSet.
*/
com.google.protobuf.ByteString
getSharedSetBytes();
/**
* <pre>
* Output only. The ID of the criterion.
* This field is ignored for mutates.
* </pre>
*
* <code>optional int64 criterion_id = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return Whether the criterionId field is set.
*/
boolean hasCriterionId();
/**
* <pre>
* Output only. The ID of the criterion.
* This field is ignored for mutates.
* </pre>
*
* <code>optional int64 criterion_id = 11 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The criterionId.
*/
long getCriterionId();
/**
* <pre>
* Output only. The type of the criterion.
* </pre>
*
* <code>.google.ads.googleads.v10.enums.CriterionTypeEnum.CriterionType type = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The enum numeric value on the wire for type.
*/
int getTypeValue();
/**
* <pre>
* Output only. The type of the criterion.
* </pre>
*
* <code>.google.ads.googleads.v10.enums.CriterionTypeEnum.CriterionType type = 4 [(.google.api.field_behavior) = OUTPUT_ONLY];</code>
* @return The type.
*/
com.google.ads.googleads.v10.enums.CriterionTypeEnum.CriterionType getType();
/**
* <pre>
* Immutable. Keyword.
* </pre>
*
* <code>.google.ads.googleads.v10.common.KeywordInfo keyword = 3 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the keyword field is set.
*/
boolean hasKeyword();
/**
* <pre>
* Immutable. Keyword.
* </pre>
*
* <code>.google.ads.googleads.v10.common.KeywordInfo keyword = 3 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The keyword.
*/
com.google.ads.googleads.v10.common.KeywordInfo getKeyword();
/**
* <pre>
* Immutable. Keyword.
* </pre>
*
* <code>.google.ads.googleads.v10.common.KeywordInfo keyword = 3 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.KeywordInfoOrBuilder getKeywordOrBuilder();
/**
* <pre>
* Immutable. YouTube Video.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeVideoInfo youtube_video = 5 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the youtubeVideo field is set.
*/
boolean hasYoutubeVideo();
/**
* <pre>
* Immutable. YouTube Video.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeVideoInfo youtube_video = 5 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The youtubeVideo.
*/
com.google.ads.googleads.v10.common.YouTubeVideoInfo getYoutubeVideo();
/**
* <pre>
* Immutable. YouTube Video.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeVideoInfo youtube_video = 5 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.YouTubeVideoInfoOrBuilder getYoutubeVideoOrBuilder();
/**
* <pre>
* Immutable. YouTube Channel.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeChannelInfo youtube_channel = 6 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the youtubeChannel field is set.
*/
boolean hasYoutubeChannel();
/**
* <pre>
* Immutable. YouTube Channel.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeChannelInfo youtube_channel = 6 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The youtubeChannel.
*/
com.google.ads.googleads.v10.common.YouTubeChannelInfo getYoutubeChannel();
/**
* <pre>
* Immutable. YouTube Channel.
* </pre>
*
* <code>.google.ads.googleads.v10.common.YouTubeChannelInfo youtube_channel = 6 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.YouTubeChannelInfoOrBuilder getYoutubeChannelOrBuilder();
/**
* <pre>
* Immutable. Placement.
* </pre>
*
* <code>.google.ads.googleads.v10.common.PlacementInfo placement = 7 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the placement field is set.
*/
boolean hasPlacement();
/**
* <pre>
* Immutable. Placement.
* </pre>
*
* <code>.google.ads.googleads.v10.common.PlacementInfo placement = 7 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The placement.
*/
com.google.ads.googleads.v10.common.PlacementInfo getPlacement();
/**
* <pre>
* Immutable. Placement.
* </pre>
*
* <code>.google.ads.googleads.v10.common.PlacementInfo placement = 7 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.PlacementInfoOrBuilder getPlacementOrBuilder();
/**
* <pre>
* Immutable. Mobile App Category.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileAppCategoryInfo mobile_app_category = 8 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the mobileAppCategory field is set.
*/
boolean hasMobileAppCategory();
/**
* <pre>
* Immutable. Mobile App Category.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileAppCategoryInfo mobile_app_category = 8 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The mobileAppCategory.
*/
com.google.ads.googleads.v10.common.MobileAppCategoryInfo getMobileAppCategory();
/**
* <pre>
* Immutable. Mobile App Category.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileAppCategoryInfo mobile_app_category = 8 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.MobileAppCategoryInfoOrBuilder getMobileAppCategoryOrBuilder();
/**
* <pre>
* Immutable. Mobile application.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileApplicationInfo mobile_application = 9 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return Whether the mobileApplication field is set.
*/
boolean hasMobileApplication();
/**
* <pre>
* Immutable. Mobile application.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileApplicationInfo mobile_application = 9 [(.google.api.field_behavior) = IMMUTABLE];</code>
* @return The mobileApplication.
*/
com.google.ads.googleads.v10.common.MobileApplicationInfo getMobileApplication();
/**
* <pre>
* Immutable. Mobile application.
* </pre>
*
* <code>.google.ads.googleads.v10.common.MobileApplicationInfo mobile_application = 9 [(.google.api.field_behavior) = IMMUTABLE];</code>
*/
com.google.ads.googleads.v10.common.MobileApplicationInfoOrBuilder getMobileApplicationOrBuilder();
public com.google.ads.googleads.v10.resources.SharedCriterion.CriterionCase getCriterionCase();
}
|
googleads/google-ads-java
|
google-ads-stubs-v10/src/main/java/com/google/ads/googleads/v10/resources/SharedCriterionOrBuilder.java
|
Java
|
apache-2.0
| 8,879 |
package com.example;
/**
* Created by hilmiat on 7/29/17.
*/
public class DemoConditional {
public static char getGrade(int nilai){
char grade = 'D';
if(nilai > 85){
grade = 'A';
}else if(nilai > 69){
grade = 'B';
}else if(nilai >= 60){
grade = 'C';
}
return grade;
}
public static void main(String[] args) {
int[] nilai_siswa = {78,90,89,68,77};
OperasiArray.cetakArray(nilai_siswa);
//100-86 A,70-85 B,60-69 C,0-59 D
//kalau D tidak lulus, A,B,C lulus
for(int n:nilai_siswa){
System.out.println("Nilai "+n+",garade-nya:"+getGrade(n));
}
}
}
|
hilmiat/NF_android_complete
|
Pertemuan2/pertemuan_dua/src/main/java/com/example/DemoConditional.java
|
Java
|
apache-2.0
| 707 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.bookkeeper.client;
import static org.apache.bookkeeper.client.BookKeeperClientStats.WRITE_DELAYED_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS;
import static org.apache.bookkeeper.client.BookKeeperClientStats.WRITE_TIMED_OUT_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS;
import static org.apache.bookkeeper.common.concurrent.FutureUtils.result;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import io.netty.util.IllegalReferenceCountException;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.bookkeeper.client.AsyncCallback.AddCallback;
import org.apache.bookkeeper.client.AsyncCallback.ReadCallback;
import org.apache.bookkeeper.client.BKException.BKBookieHandleNotAvailableException;
import org.apache.bookkeeper.client.BKException.BKIllegalOpException;
import org.apache.bookkeeper.client.BookKeeper.DigestType;
import org.apache.bookkeeper.client.api.WriteFlag;
import org.apache.bookkeeper.client.api.WriteHandle;
import org.apache.bookkeeper.conf.ClientConfiguration;
import org.apache.bookkeeper.net.BookieSocketAddress;
import org.apache.bookkeeper.proto.BookieServer;
import org.apache.bookkeeper.stats.NullStatsLogger;
import org.apache.bookkeeper.stats.StatsLogger;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.test.TestStatsProvider;
import org.apache.bookkeeper.zookeeper.BoundExponentialBackoffRetryPolicy;
import org.apache.bookkeeper.zookeeper.ZooKeeperClient;
import org.apache.bookkeeper.zookeeper.ZooKeeperWatcherBase;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.ConnectionLossException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.data.ACL;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Tests of the main BookKeeper client.
*/
public class BookKeeperTest extends BookKeeperClusterTestCase {
private static final Logger LOG = LoggerFactory.getLogger(BookKeeperTest.class);
private static final long INVALID_LEDGERID = -1L;
private final DigestType digestType;
public BookKeeperTest() {
super(4);
this.digestType = DigestType.CRC32;
}
@Test
public void testConstructionZkDelay() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri())
.setZkTimeout(20000);
CountDownLatch l = new CountDownLatch(1);
zkUtil.sleepCluster(200, TimeUnit.MILLISECONDS, l);
l.await();
BookKeeper bkc = new BookKeeper(conf);
bkc.createLedger(digestType, "testPasswd".getBytes()).close();
bkc.close();
}
@Test
public void testConstructionNotConnectedExplicitZk() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri())
.setZkTimeout(20000);
CountDownLatch l = new CountDownLatch(1);
zkUtil.sleepCluster(200, TimeUnit.MILLISECONDS, l);
l.await();
ZooKeeper zk = new ZooKeeper(
zkUtil.getZooKeeperConnectString(),
50,
event -> {});
assertFalse("ZK shouldn't have connected yet", zk.getState().isConnected());
try {
BookKeeper bkc = new BookKeeper(conf, zk);
fail("Shouldn't be able to construct with unconnected zk");
} catch (IOException cle) {
// correct behaviour
assertTrue(cle.getCause() instanceof ConnectionLossException);
}
}
/**
* Test that bookkeeper is not able to open ledgers if
* it provides the wrong password or wrong digest.
*/
@Test
public void testBookkeeperDigestPasswordWithAutoDetection() throws Exception {
testBookkeeperDigestPassword(true);
}
@Test
public void testBookkeeperDigestPasswordWithoutAutoDetection() throws Exception {
testBookkeeperDigestPassword(false);
}
void testBookkeeperDigestPassword(boolean autodetection) throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
conf.setEnableDigestTypeAutodetection(autodetection);
BookKeeper bkc = new BookKeeper(conf);
DigestType digestCorrect = digestType;
byte[] passwdCorrect = "AAAAAAA".getBytes();
DigestType digestBad = digestType == DigestType.MAC ? DigestType.CRC32 : DigestType.MAC;
byte[] passwdBad = "BBBBBBB".getBytes();
LedgerHandle lh = null;
try {
lh = bkc.createLedger(digestCorrect, passwdCorrect);
long id = lh.getId();
for (int i = 0; i < 100; i++) {
lh.addEntry("foobar".getBytes());
}
lh.close();
// try open with bad passwd
try {
bkc.openLedger(id, digestCorrect, passwdBad);
fail("Shouldn't be able to open with bad passwd");
} catch (BKException.BKUnauthorizedAccessException bke) {
// correct behaviour
}
// try open with bad digest
try {
bkc.openLedger(id, digestBad, passwdCorrect);
if (!autodetection) {
fail("Shouldn't be able to open with bad digest");
}
} catch (BKException.BKDigestMatchException bke) {
// correct behaviour
if (autodetection) {
fail("Should not throw digest match exception if `autodetection` is enabled");
}
}
// try open with both bad
try {
bkc.openLedger(id, digestBad, passwdBad);
fail("Shouldn't be able to open with bad passwd and digest");
} catch (BKException.BKUnauthorizedAccessException bke) {
// correct behaviour
}
// try open with both correct
bkc.openLedger(id, digestCorrect, passwdCorrect).close();
} finally {
if (lh != null) {
lh.close();
}
bkc.close();
}
}
/**
* Tests that when trying to use a closed BK client object we get
* a callback error and not an InterruptedException.
* @throws Exception
*/
@Test
public void testAsyncReadWithError() throws Exception {
LedgerHandle lh = bkc.createLedger(3, 3, DigestType.CRC32, "testPasswd".getBytes());
bkc.close();
final AtomicInteger result = new AtomicInteger(0);
final CountDownLatch counter = new CountDownLatch(1);
// Try to write, we shoud get and error callback but not an exception
lh.asyncAddEntry("test".getBytes(), new AddCallback() {
public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
result.set(rc);
counter.countDown();
}
}, null);
counter.await();
assertTrue(result.get() != 0);
}
/**
* Test that bookkeeper will close cleanly if close is issued
* while another operation is in progress.
*/
@Test
public void testCloseDuringOp() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
for (int i = 0; i < 10; i++) {
final BookKeeper client = new BookKeeper(conf);
final CountDownLatch l = new CountDownLatch(1);
final AtomicBoolean success = new AtomicBoolean(false);
Thread t = new Thread() {
public void run() {
try {
LedgerHandle lh = client.createLedger(3, 3, digestType, "testPasswd".getBytes());
startNewBookie();
killBookie(0);
lh.asyncAddEntry("test".getBytes(), new AddCallback() {
@Override
public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) {
// noop, we don't care if this completes
}
}, null);
client.close();
success.set(true);
l.countDown();
} catch (Exception e) {
LOG.error("Error running test", e);
success.set(false);
l.countDown();
}
}
};
t.start();
assertTrue("Close never completed", l.await(10, TimeUnit.SECONDS));
assertTrue("Close was not successful", success.get());
}
}
@Test
public void testIsClosed() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
BookKeeper bkc = new BookKeeper(conf);
LedgerHandle lh = bkc.createLedger(digestType, "testPasswd".getBytes());
Long lId = lh.getId();
lh.addEntry("000".getBytes());
boolean result = bkc.isClosed(lId);
assertTrue("Ledger shouldn't be flagged as closed!", !result);
lh.close();
result = bkc.isClosed(lId);
assertTrue("Ledger should be flagged as closed!", result);
bkc.close();
}
@Test
public void testReadFailureCallback() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
BookKeeper bkc = new BookKeeper(conf);
LedgerHandle lh = bkc.createLedger(digestType, "testPasswd".getBytes());
final int numEntries = 10;
for (int i = 0; i < numEntries; i++) {
lh.addEntry(("entry-" + i).getBytes());
}
stopBKCluster();
try {
lh.readEntries(0, numEntries - 1);
fail("Read operation should have failed");
} catch (BKBookieHandleNotAvailableException e) {
// expected
}
final CountDownLatch counter = new CountDownLatch(1);
final AtomicInteger receivedResponses = new AtomicInteger(0);
final AtomicInteger returnCode = new AtomicInteger();
lh.asyncReadEntries(0, numEntries - 1, new ReadCallback() {
@Override
public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> seq, Object ctx) {
returnCode.set(rc);
receivedResponses.incrementAndGet();
counter.countDown();
}
}, null);
counter.await();
// Wait extra time to ensure no extra responses received
Thread.sleep(1000);
assertEquals(1, receivedResponses.get());
assertEquals(BKException.Code.BookieHandleNotAvailableException, returnCode.get());
bkc.close();
}
@Test
public void testAutoCloseableBookKeeper() throws Exception {
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
BookKeeper bkc2;
try (BookKeeper bkc = new BookKeeper(conf)) {
bkc2 = bkc;
long ledgerId;
try (LedgerHandle lh = bkc.createLedger(digestType, "testPasswd".getBytes())) {
ledgerId = lh.getId();
for (int i = 0; i < 100; i++) {
lh.addEntry("foobar".getBytes());
}
}
assertTrue("Ledger should be closed!", bkc.isClosed(ledgerId));
}
assertTrue("BookKeeper should be closed!", bkc2.closed);
}
@Test
public void testReadAfterLastAddConfirmed() throws Exception {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkWriter = new BookKeeper(clientConfiguration)) {
LedgerHandle writeLh = bkWriter.createLedger(digestType, "testPasswd".getBytes());
long ledgerId = writeLh.getId();
int numOfEntries = 5;
for (int i = 0; i < numOfEntries; i++) {
writeLh.addEntry(("foobar" + i).getBytes());
}
try (BookKeeper bkReader = new BookKeeper(clientConfiguration);
LedgerHandle rlh = bkReader.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes())) {
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
assertFalse(writeLh.isClosed());
// with readUnconfirmedEntries we are able to read all of the entries
Enumeration<LedgerEntry> entries = rlh.readUnconfirmedEntries(0, numOfEntries - 1);
int entryId = 0;
while (entries.hasMoreElements()) {
LedgerEntry entry = entries.nextElement();
String entryString = new String(entry.getEntry());
assertTrue("Expected entry String: " + ("foobar" + entryId)
+ " actual entry String: " + entryString,
entryString.equals("foobar" + entryId));
entryId++;
}
}
try (BookKeeper bkReader = new BookKeeper(clientConfiguration);
LedgerHandle rlh = bkReader.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes())) {
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
assertFalse(writeLh.isClosed());
// without readUnconfirmedEntries we are not able to read all of the entries
try {
rlh.readEntries(0, numOfEntries - 1);
fail("shoud not be able to read up to " + (numOfEntries - 1) + " with readEntries");
} catch (BKException.BKReadException expected) {
}
// read all entries within the 0..LastAddConfirmed range with readEntries
assertEquals(rlh.getLastAddConfirmed() + 1,
Collections.list(rlh.readEntries(0, rlh.getLastAddConfirmed())).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
// read all entries within the 0..LastAddConfirmed range with readUnconfirmedEntries
assertEquals(rlh.getLastAddConfirmed() + 1,
Collections.list(rlh.readUnconfirmedEntries(0, rlh.getLastAddConfirmed())).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
// read all entries within the LastAddConfirmed..numOfEntries - 1 range with readUnconfirmedEntries
assertEquals(numOfEntries - rlh.getLastAddConfirmed(),
Collections.list(rlh.readUnconfirmedEntries(rlh.getLastAddConfirmed(), numOfEntries - 1)).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
try {
// read all entries within the LastAddConfirmed..numOfEntries range with readUnconfirmedEntries
// this is an error, we are going outside the range of existing entries
rlh.readUnconfirmedEntries(rlh.getLastAddConfirmed(), numOfEntries);
fail("the read tried to access data for unexisting entry id " + numOfEntries);
} catch (BKException.BKNoSuchEntryException expected) {
// expecting a BKNoSuchEntryException, as the entry does not exist on bookies
}
try {
// read all entries within the LastAddConfirmed..numOfEntries range with readEntries
// this is an error, we are going outside the range of existing entries
rlh.readEntries(rlh.getLastAddConfirmed(), numOfEntries);
fail("the read tries to access data for unexisting entry id " + numOfEntries);
} catch (BKException.BKReadException expected) {
// expecting a BKReadException, as the client rejected the request to access entries
// after local LastAddConfirmed
}
}
// ensure that after restarting every bookie entries are not lost
// even entries after the LastAddConfirmed
restartBookies();
try (BookKeeper bkReader = new BookKeeper(clientConfiguration);
LedgerHandle rlh = bkReader.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes())) {
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
assertFalse(writeLh.isClosed());
// with readUnconfirmedEntries we are able to read all of the entries
Enumeration<LedgerEntry> entries = rlh.readUnconfirmedEntries(0, numOfEntries - 1);
int entryId = 0;
while (entries.hasMoreElements()) {
LedgerEntry entry = entries.nextElement();
String entryString = new String(entry.getEntry());
assertTrue("Expected entry String: " + ("foobar" + entryId)
+ " actual entry String: " + entryString,
entryString.equals("foobar" + entryId));
entryId++;
}
}
try (BookKeeper bkReader = new BookKeeper(clientConfiguration);
LedgerHandle rlh = bkReader.openLedgerNoRecovery(ledgerId, digestType, "testPasswd".getBytes())) {
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
assertFalse(writeLh.isClosed());
// without readUnconfirmedEntries we are not able to read all of the entries
try {
rlh.readEntries(0, numOfEntries - 1);
fail("shoud not be able to read up to " + (numOfEntries - 1) + " with readEntries");
} catch (BKException.BKReadException expected) {
}
// read all entries within the 0..LastAddConfirmed range with readEntries
assertEquals(rlh.getLastAddConfirmed() + 1,
Collections.list(rlh.readEntries(0, rlh.getLastAddConfirmed())).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
// read all entries within the 0..LastAddConfirmed range with readUnconfirmedEntries
assertEquals(rlh.getLastAddConfirmed() + 1,
Collections.list(rlh.readUnconfirmedEntries(0, rlh.getLastAddConfirmed())).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
// read all entries within the LastAddConfirmed..numOfEntries - 1 range with readUnconfirmedEntries
assertEquals(numOfEntries - rlh.getLastAddConfirmed(),
Collections.list(rlh.readUnconfirmedEntries(rlh.getLastAddConfirmed(), numOfEntries - 1)).size());
// assert local LAC does not change after reads
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 2) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 2)));
try {
// read all entries within the LastAddConfirmed..numOfEntries range with readUnconfirmedEntries
// this is an error, we are going outside the range of existing entries
rlh.readUnconfirmedEntries(rlh.getLastAddConfirmed(), numOfEntries);
fail("the read tried to access data for unexisting entry id " + numOfEntries);
} catch (BKException.BKNoSuchEntryException expected) {
// expecting a BKNoSuchEntryException, as the entry does not exist on bookies
}
try {
// read all entries within the LastAddConfirmed..numOfEntries range with readEntries
// this is an error, we are going outside the range of existing entries
rlh.readEntries(rlh.getLastAddConfirmed(), numOfEntries);
fail("the read tries to access data for unexisting entry id " + numOfEntries);
} catch (BKException.BKReadException expected) {
// expecting a BKReadException, as the client rejected the request to access entries
// after local LastAddConfirmed
}
}
// open ledger with fencing, this will repair the ledger and make the last entry readable
try (BookKeeper bkReader = new BookKeeper(clientConfiguration);
LedgerHandle rlh = bkReader.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertTrue(
"Expected LAC of rlh: " + (numOfEntries - 1) + " actual LAC of rlh: " + rlh.getLastAddConfirmed(),
(rlh.getLastAddConfirmed() == (numOfEntries - 1)));
assertFalse(writeLh.isClosed());
// without readUnconfirmedEntries we are not able to read all of the entries
Enumeration<LedgerEntry> entries = rlh.readEntries(0, numOfEntries - 1);
int entryId = 0;
while (entries.hasMoreElements()) {
LedgerEntry entry = entries.nextElement();
String entryString = new String(entry.getEntry());
assertTrue("Expected entry String: " + ("foobar" + entryId)
+ " actual entry String: " + entryString,
entryString.equals("foobar" + entryId));
entryId++;
}
}
// should still be able to close as long as recovery closed the ledger
// with the same last entryId and length as in the write handle.
writeLh.close();
}
}
@Test
public void testReadWriteWithV2WireProtocol() throws Exception {
ClientConfiguration conf = new ClientConfiguration().setUseV2WireProtocol(true);
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
int numEntries = 100;
byte[] data = "foobar".getBytes();
try (BookKeeper bkc = new BookKeeper(conf)) {
// basic read/write
{
long ledgerId;
try (LedgerHandle lh = bkc.createLedger(digestType, "testPasswd".getBytes())) {
ledgerId = lh.getId();
for (int i = 0; i < numEntries; i++) {
lh.addEntry(data);
}
}
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
assertArrayEquals(data, entry.getEntry());
}
}
}
// basic fencing
{
long ledgerId;
try (LedgerHandle lh2 = bkc.createLedger(digestType, "testPasswd".getBytes())) {
ledgerId = lh2.getId();
lh2.addEntry(data);
try (LedgerHandle lh2Fence = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
}
try {
lh2.addEntry(data);
fail("ledger should be fenced");
} catch (BKException.BKLedgerFencedException ex){
}
}
}
}
}
@SuppressWarnings("deprecation")
@Test
public void testReadEntryReleaseByteBufs() throws Exception {
ClientConfiguration confWriter = new ClientConfiguration();
confWriter.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
int numEntries = 10;
byte[] data = "foobar".getBytes();
long ledgerId;
try (BookKeeper bkc = new BookKeeper(confWriter)) {
try (LedgerHandle lh = bkc.createLedger(digestType, "testPasswd".getBytes())) {
ledgerId = lh.getId();
for (int i = 0; i < numEntries; i++) {
lh.addEntry(data);
}
}
}
// v2 protocol, using pooled buffers
ClientConfiguration confReader1 = new ClientConfiguration()
.setUseV2WireProtocol(true)
.setNettyUsePooledBuffers(true)
.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkc = new BookKeeper(confReader1)) {
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
try {
entry.data.release();
} catch (IllegalReferenceCountException ok) {
fail("ByteBuf already released");
}
}
}
}
// v2 protocol, not using pooled buffers
ClientConfiguration confReader2 = new ClientConfiguration()
.setUseV2WireProtocol(true)
.setNettyUsePooledBuffers(false);
confReader2.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkc = new BookKeeper(confReader2)) {
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
try {
entry.data.release();
} catch (IllegalReferenceCountException e) {
fail("ByteBuf already released");
}
}
}
}
// v3 protocol, not using pooled buffers
ClientConfiguration confReader3 = new ClientConfiguration()
.setUseV2WireProtocol(false)
.setNettyUsePooledBuffers(false)
.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkc = new BookKeeper(confReader3)) {
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
assertTrue("Can't release entry " + entry.getEntryId() + ": ref = " + entry.data.refCnt(),
entry.data.release());
try {
assertFalse(entry.data.release());
fail("ByteBuf already released");
} catch (IllegalReferenceCountException ok) {
}
}
}
}
// v3 protocol, using pooled buffers
// v3 protocol from 4.5 always "wraps" buffers returned by protobuf
ClientConfiguration confReader4 = new ClientConfiguration()
.setUseV2WireProtocol(false)
.setNettyUsePooledBuffers(true)
.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkc = new BookKeeper(confReader4)) {
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
// ButeBufs not reference counter
assertTrue("Can't release entry " + entry.getEntryId() + ": ref = " + entry.data.refCnt(),
entry.data.release());
try {
assertFalse(entry.data.release());
fail("ByteBuf already released");
} catch (IllegalReferenceCountException ok) {
}
}
}
}
// cannot read twice an entry
ClientConfiguration confReader5 = new ClientConfiguration();
confReader5.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
try (BookKeeper bkc = new BookKeeper(confReader5)) {
try (LedgerHandle lh = bkc.openLedger(ledgerId, digestType, "testPasswd".getBytes())) {
assertEquals(numEntries - 1, lh.readLastConfirmed());
for (Enumeration<LedgerEntry> readEntries = lh.readEntries(0, numEntries - 1);
readEntries.hasMoreElements();) {
LedgerEntry entry = readEntries.nextElement();
entry.getEntry();
try {
entry.getEntry();
fail("entry data accessed twice");
} catch (IllegalStateException ok){
}
try {
entry.getEntryInputStream();
fail("entry data accessed twice");
} catch (IllegalStateException ok){
}
}
}
}
}
/**
* Tests that issuing multiple reads for the same entry at the same time works as expected.
*
* @throws Exception
*/
@Test
public void testDoubleRead() throws Exception {
LedgerHandle lh = bkc.createLedger(digestType, "".getBytes());
lh.addEntry("test".getBytes());
// Read the same entry more times asynchronously
final int n = 10;
final CountDownLatch latch = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
lh.asyncReadEntries(0, 0, new ReadCallback() {
public void readComplete(int rc, LedgerHandle lh,
Enumeration<LedgerEntry> seq, Object ctx) {
if (rc == BKException.Code.OK) {
latch.countDown();
} else {
fail("Read fail");
}
}
}, null);
}
latch.await();
}
/**
* Tests that issuing multiple reads for the same entry at the same time works as expected.
*
* @throws Exception
*/
@Test
public void testDoubleReadWithV2Protocol() throws Exception {
ClientConfiguration conf = new ClientConfiguration(baseClientConf);
conf.setUseV2WireProtocol(true);
BookKeeperTestClient bkc = new BookKeeperTestClient(conf);
LedgerHandle lh = bkc.createLedger(digestType, "".getBytes());
lh.addEntry("test".getBytes());
// Read the same entry more times asynchronously
final int n = 10;
final CountDownLatch latch = new CountDownLatch(n);
for (int i = 0; i < n; i++) {
lh.asyncReadEntries(0, 0, new ReadCallback() {
public void readComplete(int rc, LedgerHandle lh,
Enumeration<LedgerEntry> seq, Object ctx) {
if (rc == BKException.Code.OK) {
latch.countDown();
} else {
fail("Read fail");
}
}
}, null);
}
latch.await();
bkc.close();
}
@Test(expected = BKIllegalOpException.class)
public void testCannotUseWriteFlagsOnV2Protocol() throws Exception {
ClientConfiguration conf = new ClientConfiguration(baseClientConf);
conf.setUseV2WireProtocol(true);
try (BookKeeperTestClient bkc = new BookKeeperTestClient(conf)) {
try (WriteHandle wh = result(bkc.newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
.withAckQuorumSize(2)
.withPassword("".getBytes())
.withWriteFlags(WriteFlag.DEFERRED_SYNC)
.execute())) {
result(wh.appendAsync("test".getBytes()));
}
}
}
@Test(expected = BKIllegalOpException.class)
public void testCannotUseForceOnV2Protocol() throws Exception {
ClientConfiguration conf = new ClientConfiguration(baseClientConf);
conf.setUseV2WireProtocol(true);
try (BookKeeperTestClient bkc = new BookKeeperTestClient(conf)) {
try (WriteHandle wh = result(bkc.newCreateLedgerOp()
.withEnsembleSize(3)
.withWriteQuorumSize(3)
.withAckQuorumSize(2)
.withPassword("".getBytes())
.withWriteFlags(WriteFlag.NONE)
.execute())) {
result(wh.appendAsync("".getBytes()));
result(wh.force());
}
}
}
class MockZooKeeperClient extends ZooKeeperClient {
class MockZooKeeper extends ZooKeeper {
public MockZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly)
throws IOException {
super(connectString, sessionTimeout, watcher, canBeReadOnly);
}
@Override
public void create(final String path, byte[] data, List<ACL> acl, CreateMode createMode, StringCallback cb,
Object ctx) {
StringCallback injectedCallback = new StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
/**
* if ledgerIdToInjectFailure matches with the path of
* the node, then throw CONNECTIONLOSS error and then
* reset it to INVALID_LEDGERID.
*/
if (path.contains(ledgerIdToInjectFailure.toString())) {
ledgerIdToInjectFailure.set(INVALID_LEDGERID);
cb.processResult(KeeperException.Code.CONNECTIONLOSS.intValue(), path, ctx, name);
} else {
cb.processResult(rc, path, ctx, name);
}
}
};
super.create(path, data, acl, createMode, injectedCallback, ctx);
}
}
private final String connectString;
private final int sessionTimeoutMs;
private final ZooKeeperWatcherBase watcherManager;
private final AtomicLong ledgerIdToInjectFailure;
MockZooKeeperClient(String connectString, int sessionTimeoutMs, ZooKeeperWatcherBase watcher,
AtomicLong ledgerIdToInjectFailure) throws IOException {
/*
* in OperationalRetryPolicy maxRetries is > 0. So in case of any
* RecoverableException scenario, it will retry.
*/
super(connectString, sessionTimeoutMs, watcher,
new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, Integer.MAX_VALUE),
new BoundExponentialBackoffRetryPolicy(sessionTimeoutMs, sessionTimeoutMs, 3),
NullStatsLogger.INSTANCE, 1, 0, false);
this.connectString = connectString;
this.sessionTimeoutMs = sessionTimeoutMs;
this.watcherManager = watcher;
this.ledgerIdToInjectFailure = ledgerIdToInjectFailure;
}
@Override
protected ZooKeeper createZooKeeper() throws IOException {
return new MockZooKeeper(this.connectString, this.sessionTimeoutMs, this.watcherManager, false);
}
}
@Test
public void testZKConnectionLossForLedgerCreation() throws Exception {
int zkSessionTimeOut = 10000;
AtomicLong ledgerIdToInjectFailure = new AtomicLong(INVALID_LEDGERID);
ZooKeeperWatcherBase zooKeeperWatcherBase = new ZooKeeperWatcherBase(zkSessionTimeOut,
NullStatsLogger.INSTANCE);
MockZooKeeperClient zkFaultInjectionWrapper = new MockZooKeeperClient(zkUtil.getZooKeeperConnectString(),
zkSessionTimeOut, zooKeeperWatcherBase, ledgerIdToInjectFailure);
zkFaultInjectionWrapper.waitForConnection();
assertEquals("zkFaultInjectionWrapper should be in connected state", States.CONNECTED,
zkFaultInjectionWrapper.getState());
BookKeeper bk = new BookKeeper(baseClientConf, zkFaultInjectionWrapper);
long oldZkInstanceSessionId = zkFaultInjectionWrapper.getSessionId();
long ledgerId = 567L;
LedgerHandle lh = bk.createLedgerAdv(ledgerId, 1, 1, 1, DigestType.CRC32, "".getBytes(), null);
lh.close();
/*
* trigger Expired event so that MockZooKeeperClient would run
* 'clientCreator' and create new zk handle. In this case it would
* create MockZooKeeper.
*/
zooKeeperWatcherBase.process(new WatchedEvent(EventType.None, KeeperState.Expired, ""));
zkFaultInjectionWrapper.waitForConnection();
for (int i = 0; i < 10; i++) {
if (zkFaultInjectionWrapper.getState() == States.CONNECTED) {
break;
}
Thread.sleep(200);
}
assertEquals("zkFaultInjectionWrapper should be in connected state", States.CONNECTED,
zkFaultInjectionWrapper.getState());
assertNotEquals("Session Id of old and new ZK instance should be different", oldZkInstanceSessionId,
zkFaultInjectionWrapper.getSessionId());
ledgerId++;
ledgerIdToInjectFailure.set(ledgerId);
/**
* ledgerIdToInjectFailure is set to 'ledgerId', so zookeeper.create
* would return CONNECTIONLOSS error for the first time and when it is
* retried, as expected it would return NODEEXISTS error.
*
* AbstractZkLedgerManager.createLedgerMetadata should deal with this
* scenario appropriately.
*/
lh = bk.createLedgerAdv(ledgerId, 1, 1, 1, DigestType.CRC32, "".getBytes(), null);
lh.close();
assertEquals("injectZnodeCreationNoNodeFailure should have been reset it to INVALID_LEDGERID", INVALID_LEDGERID,
ledgerIdToInjectFailure.get());
lh = bk.openLedger(ledgerId, DigestType.CRC32, "".getBytes());
lh.close();
ledgerId++;
lh = bk.createLedgerAdv(ledgerId, 1, 1, 1, DigestType.CRC32, "".getBytes(), null);
lh.close();
bk.close();
}
@Test
public void testLedgerDeletionIdempotency() throws Exception {
BookKeeper bk = new BookKeeper(baseClientConf);
long ledgerId = 789L;
LedgerHandle lh = bk.createLedgerAdv(ledgerId, 1, 1, 1, DigestType.CRC32, "".getBytes(), null);
lh.close();
bk.deleteLedger(ledgerId);
bk.deleteLedger(ledgerId);
bk.close();
}
/**
* Mock of RackawareEnsemblePlacementPolicy. Overrides areAckedBookiesAdheringToPlacementPolicy to only return true
* when ackedBookies consists of writeQuorumSizeToUseForTesting bookies.
*/
public static class MockRackawareEnsemblePlacementPolicy extends RackawareEnsemblePlacementPolicy {
private int writeQuorumSizeToUseForTesting;
private CountDownLatch conditionFirstInvocationLatch;
void setWriteQuorumSizeToUseForTesting(int writeQuorumSizeToUseForTesting) {
this.writeQuorumSizeToUseForTesting = writeQuorumSizeToUseForTesting;
}
void setConditionFirstInvocationLatch(CountDownLatch conditionFirstInvocationLatch) {
this.conditionFirstInvocationLatch = conditionFirstInvocationLatch;
}
@Override
public boolean areAckedBookiesAdheringToPlacementPolicy(Set<BookieSocketAddress> ackedBookies,
int writeQuorumSize,
int ackQuorumSize) {
conditionFirstInvocationLatch.countDown();
return ackedBookies.size() == writeQuorumSizeToUseForTesting;
}
}
/**
* Test to verify that PendingAddOp waits for success condition from areAckedBookiesAdheringToPlacementPolicy
* before returning success to client. Also tests working of WRITE_DELAYED_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS and
* WRITE_TIMED_OUT_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS counters.
*/
@Test
public void testEnforceMinNumFaultDomainsForWrite() throws Exception {
byte[] data = "foobar".getBytes();
byte[] password = "testPasswd".getBytes();
startNewBookie();
startNewBookie();
ClientConfiguration conf = new ClientConfiguration();
conf.setMetadataServiceUri(zkUtil.getMetadataServiceUri());
conf.setEnsemblePlacementPolicy(MockRackawareEnsemblePlacementPolicy.class);
conf.setAddEntryTimeout(2);
conf.setAddEntryQuorumTimeout(4);
conf.setEnforceMinNumFaultDomainsForWrite(true);
TestStatsProvider statsProvider = new TestStatsProvider();
// Abnormal values for testing to prevent timeouts
BookKeeperTestClient bk = new BookKeeperTestClient(conf, statsProvider);
StatsLogger statsLogger = bk.getStatsLogger();
int ensembleSize = 3;
int writeQuorumSize = 3;
int ackQuorumSize = 2;
CountDownLatch countDownLatch = new CountDownLatch(1);
MockRackawareEnsemblePlacementPolicy currPlacementPolicy =
(MockRackawareEnsemblePlacementPolicy) bk.getPlacementPolicy();
currPlacementPolicy.setConditionFirstInvocationLatch(countDownLatch);
currPlacementPolicy.setWriteQuorumSizeToUseForTesting(writeQuorumSize);
BookieSocketAddress bookieToSleep;
try (LedgerHandle lh = bk.createLedger(ensembleSize, writeQuorumSize, ackQuorumSize, digestType, password)) {
CountDownLatch sleepLatchCase1 = new CountDownLatch(1);
CountDownLatch sleepLatchCase2 = new CountDownLatch(1);
// Put all non ensemble bookies to sleep
LOG.info("Putting all non ensemble bookies to sleep.");
for (BookieServer bookieServer : bs) {
try {
if (!lh.getCurrentEnsemble().contains(bookieServer.getLocalAddress())) {
sleepBookie(bookieServer.getLocalAddress(), sleepLatchCase2);
}
} catch (UnknownHostException ignored) {}
}
Thread writeToLedger = new Thread(() -> {
try {
LOG.info("Initiating write for entry");
long entryId = lh.addEntry(data);
LOG.info("Wrote entry with entryId = {}", entryId);
} catch (InterruptedException | BKException ignored) {
}
});
bookieToSleep = lh.getCurrentEnsemble().get(0);
LOG.info("Putting picked bookie to sleep");
sleepBookie(bookieToSleep, sleepLatchCase1);
assertEquals(statsLogger
.getCounter(WRITE_DELAYED_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS)
.get()
.longValue(), 0);
// Trying to write entry
writeToLedger.start();
// Waiting and checking to make sure that write has not succeeded
countDownLatch.await(conf.getAddEntryTimeout(), TimeUnit.SECONDS);
assertEquals("Write succeeded but should not have", -1, lh.lastAddConfirmed);
// Wake the bookie
sleepLatchCase1.countDown();
// Waiting and checking to make sure that write has succeeded
writeToLedger.join(conf.getAddEntryTimeout() * 1000);
assertEquals("Write did not succeed but should have", 0, lh.lastAddConfirmed);
assertEquals(statsLogger
.getCounter(WRITE_DELAYED_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS)
.get()
.longValue(), 1);
// AddEntry thread for second scenario
Thread writeToLedger2 = new Thread(() -> {
try {
LOG.info("Initiating write for entry");
long entryId = lh.addEntry(data);
LOG.info("Wrote entry with entryId = {}", entryId);
} catch (InterruptedException | BKException ignored) {
}
});
bookieToSleep = lh.getCurrentEnsemble().get(1);
LOG.info("Putting picked bookie to sleep");
sleepBookie(bookieToSleep, sleepLatchCase2);
// Trying to write entry
writeToLedger2.start();
// Waiting and checking to make sure that write has failed
writeToLedger2.join((conf.getAddEntryQuorumTimeout() + 2) * 1000);
assertEquals("Write succeeded but should not have", 0, lh.lastAddConfirmed);
sleepLatchCase2.countDown();
assertEquals(statsLogger.getCounter(WRITE_DELAYED_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS).get().longValue(),
2);
assertEquals(statsLogger.getCounter(WRITE_TIMED_OUT_DUE_TO_NOT_ENOUGH_FAULT_DOMAINS).get().longValue(),
1);
}
}
}
|
sijie/bookkeeper
|
bookkeeper-server/src/test/java/org/apache/bookkeeper/client/BookKeeperTest.java
|
Java
|
apache-2.0
| 49,996 |
<?php
class Template
{
protected $template;
protected $variables = array();
public function __construct($template)
{
$this->template = $template;
}
public function __get($key)
{
return $this->variables[$key];
}
public function __set($key, $value)
{
$this->variables[$key] = $value;
}
public function __toString()
{
$oldir = getcwd();
extract($this->variables);
//Utils::debug($this->template);
chdir(dirname($this->template));
ob_start();
include basename($this->template);
chdir($oldir);
return ob_get_clean();
}
}
|
efetepe/magicdocumentation
|
framework/php/Template.php
|
PHP
|
apache-2.0
| 666 |
/*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2017 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides the Design Time Metadata for the sap.uxap.ObjectPageLayout control
sap.ui.define([],
function() {
"use strict";
return {
name : {
singular : function(){
return sap.uxap.i18nModel.getResourceBundle().getText("LAYOUT_CONTROL_NAME");
},
plural : function(){
return sap.uxap.i18nModel.getResourceBundle().getText("LAYOUT_CONTROL__PLURAL");
}
},
aggregations : {
sections : {
domRef : function(oElement) {
return oElement.$("sectionsContainer").get(0);
},
childNames : {
singular : function(){
return sap.uxap.i18nModel.getResourceBundle().getText("SECTION_CONTROL_NAME");
},
plural : function(){
return sap.uxap.i18nModel.getResourceBundle().getText("SECTION_CONTROL_NAME_PLURAL");
}
},
actions : {
move : "moveControls"
}
}
},
scrollContainers : [{
domRef : "> .sapUxAPObjectPageWrapper",
aggregations : ["sections", "headerContent"]
}, {
domRef : function(oElement) {
return oElement.$("vertSB-sb").get(0);
}
}],
cloneDomRef : ":sap-domref > header"
};
}, /* bExport= */ false);
|
thbonk/electron-openui5-boilerplate
|
libs/openui5-runtime/resources/sap/uxap/ObjectPageLayout.designtime-dbg.js
|
JavaScript
|
apache-2.0
| 1,307 |
# frozen_string_literal: true
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require "minitest/autorun"
require "gapic/grpc/service_stub"
require "google/showcase/v1beta1/echo_pb"
require "google/showcase/v1beta1/echo_services_pb"
require "google/showcase/v1beta1/echo"
class Google::Showcase::V1beta1::Echo::OperationsTest < Minitest::Test
class ClientStub
attr_accessor :call_rpc_count, :requests
def initialize response, operation, &block
@response = response
@operation = operation
@block = block
@call_rpc_count = 0
@requests = []
end
def call_rpc *args
@call_rpc_count += 1
@requests << @block&.call(*args)
yield @response, @operation if block_given?
@response
end
end
def test_list_operations
# Create GRPC objects.
grpc_response = Google::Longrunning::ListOperationsResponse.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
filter = "hello world"
page_size = 42
page_token = "hello world"
list_operations_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :list_operations, name
assert_kind_of Google::Longrunning::ListOperationsRequest, request
assert_equal "hello world", request.name
assert_equal "hello world", request.filter
assert_equal 42, request.page_size
assert_equal "hello world", request.page_token
refute_nil options
end
Gapic::ServiceStub.stub :new, list_operations_client_stub do
# Create client
client = Google::Showcase::V1beta1::Echo::Operations.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.list_operations({ name: name, filter: filter, page_size: page_size, page_token: page_token }) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use named arguments
client.list_operations name: name, filter: filter, page_size: page_size, page_token: page_token do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.list_operations Google::Longrunning::ListOperationsRequest.new(name: name, filter: filter, page_size: page_size, page_token: page_token) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.list_operations({ name: name, filter: filter, page_size: page_size, page_token: page_token }, grpc_options) do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.list_operations Google::Longrunning::ListOperationsRequest.new(name: name, filter: filter, page_size: page_size, page_token: page_token), grpc_options do |response, operation|
assert_kind_of Gapic::PagedEnumerable, response
assert_equal grpc_response, response.response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, list_operations_client_stub.call_rpc_count
end
end
def test_get_operation
# Create GRPC objects.
grpc_response = Google::Longrunning::Operation.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
get_operation_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :get_operation, name
assert_kind_of Google::Longrunning::GetOperationRequest, request
assert_equal "hello world", request.name
refute_nil options
end
Gapic::ServiceStub.stub :new, get_operation_client_stub do
# Create client
client = Google::Showcase::V1beta1::Echo::Operations.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.get_operation({ name: name }) do |response, operation|
assert_kind_of Gapic::Operation, response
assert_equal grpc_response, response.grpc_op
assert_equal grpc_operation, operation
end
# Use named arguments
client.get_operation name: name do |response, operation|
assert_kind_of Gapic::Operation, response
assert_equal grpc_response, response.grpc_op
assert_equal grpc_operation, operation
end
# Use protobuf object
client.get_operation Google::Longrunning::GetOperationRequest.new(name: name) do |response, operation|
assert_kind_of Gapic::Operation, response
assert_equal grpc_response, response.grpc_op
assert_equal grpc_operation, operation
end
# Use hash object with options
client.get_operation({ name: name }, grpc_options) do |response, operation|
assert_kind_of Gapic::Operation, response
assert_equal grpc_response, response.grpc_op
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.get_operation Google::Longrunning::GetOperationRequest.new(name: name), grpc_options do |response, operation|
assert_kind_of Gapic::Operation, response
assert_equal grpc_response, response.grpc_op
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, get_operation_client_stub.call_rpc_count
end
end
def test_delete_operation
# Create GRPC objects.
grpc_response = Google::Protobuf::Empty.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
delete_operation_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :delete_operation, name
assert_kind_of Google::Longrunning::DeleteOperationRequest, request
assert_equal "hello world", request.name
refute_nil options
end
Gapic::ServiceStub.stub :new, delete_operation_client_stub do
# Create client
client = Google::Showcase::V1beta1::Echo::Operations.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.delete_operation({ name: name }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.delete_operation name: name do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.delete_operation Google::Longrunning::DeleteOperationRequest.new(name: name) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.delete_operation({ name: name }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.delete_operation Google::Longrunning::DeleteOperationRequest.new(name: name), grpc_options do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, delete_operation_client_stub.call_rpc_count
end
end
def test_cancel_operation
# Create GRPC objects.
grpc_response = Google::Protobuf::Empty.new
grpc_operation = GRPC::ActiveCall::Operation.new nil
grpc_channel = GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure
grpc_options = {}
# Create request parameters for a unary method.
name = "hello world"
cancel_operation_client_stub = ClientStub.new grpc_response, grpc_operation do |name, request, options:|
assert_equal :cancel_operation, name
assert_kind_of Google::Longrunning::CancelOperationRequest, request
assert_equal "hello world", request.name
refute_nil options
end
Gapic::ServiceStub.stub :new, cancel_operation_client_stub do
# Create client
client = Google::Showcase::V1beta1::Echo::Operations.new do |config|
config.credentials = grpc_channel
end
# Use hash object
client.cancel_operation({ name: name }) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use named arguments
client.cancel_operation name: name do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object
client.cancel_operation Google::Longrunning::CancelOperationRequest.new(name: name) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use hash object with options
client.cancel_operation({ name: name }, grpc_options) do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Use protobuf object with options
client.cancel_operation Google::Longrunning::CancelOperationRequest.new(name: name), grpc_options do |response, operation|
assert_equal grpc_response, response
assert_equal grpc_operation, operation
end
# Verify method calls
assert_equal 5, cancel_operation_client_stub.call_rpc_count
end
end
end
|
googleapis/gapic-generator-ruby
|
shared/output/cloud/showcase/test/google/showcase/v1beta1/echo_operations_test.rb
|
Ruby
|
apache-2.0
| 10,911 |
const Long = require('long');
const User = require('./User');
const Role = require('./Role');
const Emoji = require('./Emoji');
const Presence = require('./Presence').Presence;
const GuildMember = require('./GuildMember');
const Constants = require('../util/Constants');
const Collection = require('../util/Collection');
const Util = require('../util/Util');
const Snowflake = require('../util/Snowflake');
/**
* Represents a guild (or a server) on Discord.
* <info>It's recommended to see if a guild is available before performing operations or reading data from it. You can
* check this with `guild.available`.</info>
*/
class Guild {
constructor(client, data) {
/**
* The client that created the instance of the the guild
* @name Guild#client
* @type {Client}
* @readonly
*/
Object.defineProperty(this, 'client', { value: client });
/**
* A collection of members that are in this guild. The key is the member's ID, the value is the member
* @type {Collection<Snowflake, GuildMember>}
*/
this.members = new Collection();
/**
* A collection of channels that are in this guild. The key is the channel's ID, the value is the channel
* @type {Collection<Snowflake, GuildChannel>}
*/
this.channels = new Collection();
/**
* A collection of roles that are in this guild. The key is the role's ID, the value is the role
* @type {Collection<Snowflake, Role>}
*/
this.roles = new Collection();
/**
* A collection of presences in this guild
* @type {Collection<Snowflake, Presence>}
*/
this.presences = new Collection();
if (!data) return;
if (data.unavailable) {
/**
* Whether the guild is available to access. If it is not available, it indicates a server outage
* @type {boolean}
*/
this.available = false;
/**
* The Unique ID of the guild, useful for comparisons
* @type {Snowflake}
*/
this.id = data.id;
} else {
this.available = true;
this.setup(data);
}
}
/**
* Sets up the guild.
* @param {*} data The raw data of the guild
* @private
*/
setup(data) {
/**
* The name of the guild
* @type {string}
*/
this.name = data.name;
/**
* The hash of the guild icon
* @type {?string}
*/
this.icon = data.icon;
/**
* The hash of the guild splash image (VIP only)
* @type {?string}
*/
this.splash = data.splash;
/**
* The region the guild is located in
* @type {string}
*/
this.region = data.region;
/**
* The full amount of members in this guild as of `READY`
* @type {number}
*/
this.memberCount = data.member_count || this.memberCount;
/**
* Whether the guild is "large" (has more than 250 members)
* @type {boolean}
*/
this.large = Boolean('large' in data ? data.large : this.large);
/**
* An array of guild features
* @type {Object[]}
*/
this.features = data.features;
/**
* The ID of the application that created this guild (if applicable)
* @type {?Snowflake}
*/
this.applicationID = data.application_id;
/**
* The time in seconds before a user is counted as "away from keyboard"
* @type {?number}
*/
this.afkTimeout = data.afk_timeout;
/**
* The ID of the voice channel where AFK members are moved
* @type {?string}
*/
this.afkChannelID = data.afk_channel_id;
/**
* Whether embedded images are enabled on this guild
* @type {boolean}
*/
this.embedEnabled = data.embed_enabled;
/**
* The verification level of the guild
* @type {number}
*/
this.verificationLevel = data.verification_level;
/**
* The explicit content filter level of the guild
* @type {number}
*/
this.explicitContentFilter = data.explicit_content_filter;
/**
* The timestamp the client user joined the guild at
* @type {number}
*/
this.joinedTimestamp = data.joined_at ? new Date(data.joined_at).getTime() : this.joinedTimestamp;
this.id = data.id;
this.available = !data.unavailable;
this.features = data.features || this.features || [];
if (data.members) {
this.members.clear();
for (const guildUser of data.members) this._addMember(guildUser, false);
}
if (data.owner_id) {
/**
* The user ID of this guild's owner
* @type {Snowflake}
*/
this.ownerID = data.owner_id;
}
if (data.channels) {
this.channels.clear();
for (const channel of data.channels) this.client.dataManager.newChannel(channel, this);
}
if (data.roles) {
this.roles.clear();
for (const role of data.roles) {
const newRole = new Role(this, role);
this.roles.set(newRole.id, newRole);
}
}
if (data.presences) {
for (const presence of data.presences) {
this._setPresence(presence.user.id, presence);
}
}
this._rawVoiceStates = new Collection();
if (data.voice_states) {
for (const voiceState of data.voice_states) {
this._rawVoiceStates.set(voiceState.user_id, voiceState);
const member = this.members.get(voiceState.user_id);
if (member) {
member.serverMute = voiceState.mute;
member.serverDeaf = voiceState.deaf;
member.selfMute = voiceState.self_mute;
member.selfDeaf = voiceState.self_deaf;
member.voiceSessionID = voiceState.session_id;
member.voiceChannelID = voiceState.channel_id;
this.channels.get(voiceState.channel_id).members.set(member.user.id, member);
}
}
}
if (!this.emojis) {
/**
* A collection of emojis that are in this guild. The key is the emoji's ID, the value is the emoji.
* @type {Collection<Snowflake, Emoji>}
*/
this.emojis = new Collection();
for (const emoji of data.emojis) this.emojis.set(emoji.id, new Emoji(this, emoji));
} else {
this.client.actions.GuildEmojisUpdate.handle({
guild_id: this.id,
emojis: data.emojis,
});
}
}
/**
* The timestamp the guild was created at
* @type {number}
* @readonly
*/
get createdTimestamp() {
return Snowflake.deconstruct(this.id).timestamp;
}
/**
* The time the guild was created
* @type {Date}
* @readonly
*/
get createdAt() {
return new Date(this.createdTimestamp);
}
/**
* The time the client user joined the guild
* @type {Date}
* @readonly
*/
get joinedAt() {
return new Date(this.joinedTimestamp);
}
/**
* The URL to this guild's icon
* @type {?string}
* @readonly
*/
get iconURL() {
if (!this.icon) return null;
return Constants.Endpoints.Guild(this).Icon(this.client.options.http.cdn, this.icon);
}
/**
* The URL to this guild's splash
* @type {?string}
* @readonly
*/
get splashURL() {
if (!this.splash) return null;
return Constants.Endpoints.Guild(this).Splash(this.client.options.http.cdn, this.splash);
}
/**
* The owner of the guild
* @type {GuildMember}
* @readonly
*/
get owner() {
return this.members.get(this.ownerID);
}
/**
* If the client is connected to any voice channel in this guild, this will be the relevant VoiceConnection
* @type {?VoiceConnection}
* @readonly
*/
get voiceConnection() {
if (this.client.browser) return null;
return this.client.voice.connections.get(this.id) || null;
}
/**
* The `#general` TextChannel of the guild
* @type {TextChannel}
* @readonly
*/
get defaultChannel() {
return this.channels.get(this.id);
}
/**
* The position of this guild
* <warn>This is only available when using a user account.</warn>
* @type {?number}
*/
get position() {
if (this.client.user.bot) return null;
if (!this.client.user.settings.guildPositions) return null;
return this.client.user.settings.guildPositions.indexOf(this.id);
}
/**
* The `@everyone` role of the guild
* @type {Role}
* @readonly
*/
get defaultRole() {
return this.roles.get(this.id);
}
/**
* The client user as a GuildMember of this guild
* @type {?GuildMember}
* @readonly
*/
get me() {
return this.members.get(this.client.user.id);
}
/**
* Fetches a collection of roles in the current guild sorted by position
* @type {Collection<Snowflake, Role>}
* @readonly
* @private
*/
get _sortedRoles() {
return this._sortPositionWithID(this.roles);
}
/**
* Returns the GuildMember form of a User object, if the user is present in the guild.
* @param {UserResolvable} user The user that you want to obtain the GuildMember of
* @returns {?GuildMember}
* @example
* // Get the guild member of a user
* const member = guild.member(message.author);
*/
member(user) {
return this.client.resolver.resolveGuildMember(this, user);
}
/**
* Fetch a collection of banned users in this guild.
* @returns {Promise<Collection<Snowflake, User>>}
*/
fetchBans() {
return this.client.rest.methods.getGuildBans(this)
// This entire re-mapping can be removed in the next major release
.then(bans => {
const users = new Collection();
for (const ban of bans.values()) users.set(ban.user.id, ban.user);
return users;
});
}
/**
* Fetch a collection of invites to this guild. Resolves with a collection mapping invites by their codes.
* @returns {Promise<Collection<string, Invite>>}
*/
fetchInvites() {
return this.client.rest.methods.getGuildInvites(this);
}
/**
* Fetch all webhooks for the guild.
* @returns {Collection<Snowflake, Webhook>}
*/
fetchWebhooks() {
return this.client.rest.methods.getGuildWebhooks(this);
}
/**
* Fetch available voice regions.
* @returns {Collection<string, VoiceRegion>}
*/
fetchVoiceRegions() {
return this.client.rest.methods.fetchVoiceRegions(this.id);
}
/**
* Fetch audit logs for this guild.
* @param {Object} [options={}] Options for fetching audit logs
* @param {Snowflake|GuildAuditLogsEntry} [options.before] Limit to entries from before specified entry
* @param {Snowflake|GuildAuditLogsEntry} [options.after] Limit to entries from after specified entry
* @param {number} [options.limit] Limit number of entries
* @param {UserResolvable} [options.user] Only show entries involving this user
* @param {string|number} [options.type] Only show entries involving this action type
* @returns {Promise<GuildAuditLogs>}
*/
fetchAuditLogs(options) {
return this.client.rest.methods.getGuildAuditLogs(this, options);
}
/**
* Adds a user to the guild using OAuth2. Requires the `CREATE_INSTANT_INVITE` permission.
* @param {UserResolvable} user User to add to the guild
* @param {Object} options Options for the addition
* @param {string} options.accessToken An OAuth2 access token for the user with the `guilds.join` scope granted to the
* bot's application
* @param {string} [options.nick] Nickname to give the member (requires `MANAGE_NICKNAMES`)
* @param {Collection<Snowflake, Role>|Role[]|Snowflake[]} [options.roles] Roles to add to the member
* (requires `MANAGE_ROLES`)
* @param {boolean} [options.mute] Whether the member should be muted (requires `MUTE_MEMBERS`)
* @param {boolean} [options.deaf] Whether the member should be deafened (requires `DEAFEN_MEMBERS`)
* @returns {Promise<GuildMember>}
*/
addMember(user, options) {
if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id));
return this.client.rest.methods.putGuildMember(this, user, options);
}
/**
* Fetch a single guild member from a user.
* @param {UserResolvable} user The user to fetch the member for
* @param {boolean} [cache=true] Insert the user into the users cache
* @returns {Promise<GuildMember>}
*/
fetchMember(user, cache = true) {
user = this.client.resolver.resolveUser(user);
if (!user) return Promise.reject(new Error('User is not cached. Use Client.fetchUser first.'));
if (this.members.has(user.id)) return Promise.resolve(this.members.get(user.id));
return this.client.rest.methods.getGuildMember(this, user, cache);
}
/**
* Fetches all the members in the guild, even if they are offline. If the guild has less than 250 members,
* this should not be necessary.
* @param {string} [query=''] Limit fetch to members with similar usernames
* @param {number} [limit=0] Maximum number of members to request
* @returns {Promise<Guild>}
*/
fetchMembers(query = '', limit = 0) {
return new Promise((resolve, reject) => {
if (this.memberCount === this.members.size) {
// Uncomment in v12
// resolve(this.members)
resolve(this);
return;
}
this.client.ws.send({
op: Constants.OPCodes.REQUEST_GUILD_MEMBERS,
d: {
guild_id: this.id,
query,
limit,
},
});
const handler = (members, guild) => {
if (guild.id !== this.id) return;
if (this.memberCount === this.members.size || members.length < 1000) {
this.client.removeListener(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
// Uncomment in v12
// resolve(this.members)
resolve(this);
}
};
this.client.on(Constants.Events.GUILD_MEMBERS_CHUNK, handler);
this.client.setTimeout(() => reject(new Error('Members didn\'t arrive in time.')), 120 * 1000);
});
}
/**
* Performs a search within the entire guild.
* <warn>This is only available when using a user account.</warn>
* @param {MessageSearchOptions} [options={}] Options to pass to the search
* @returns {Promise<Array<Message[]>>}
* An array containing arrays of messages. Each inner array is a search context cluster.
* The message which has triggered the result will have the `hit` property set to `true`.
* @example
* guild.search({
* content: 'discord.js',
* before: '2016-11-17'
* }).then(res => {
* const hit = res.messages[0].find(m => m.hit).content;
* console.log(`I found: **${hit}**, total results: ${res.totalResults}`);
* }).catch(console.error);
*/
search(options = {}) {
return this.client.rest.methods.search(this, options);
}
/**
* The data for editing a guild.
* @typedef {Object} GuildEditData
* @property {string} [name] The name of the guild
* @property {string} [region] The region of the guild
* @property {number} [verificationLevel] The verification level of the guild
* @property {ChannelResolvable} [afkChannel] The AFK channel of the guild
* @property {number} [afkTimeout] The AFK timeout of the guild
* @property {Base64Resolvable} [icon] The icon of the guild
* @property {GuildMemberResolvable} [owner] The owner of the guild
* @property {Base64Resolvable} [splash] The splash screen of the guild
*/
/**
* Updates the guild with new information - e.g. a new name.
* @param {GuildEditData} data The data to update the guild with
* @returns {Promise<Guild>}
* @example
* // Set the guild name and region
* guild.edit({
* name: 'Discord Guild',
* region: 'london',
* })
* .then(updated => console.log(`New guild name ${updated.name} in region ${updated.region}`))
* .catch(console.error);
*/
edit(data) {
return this.client.rest.methods.updateGuild(this, data);
}
/**
* Edit the name of the guild.
* @param {string} name The new name of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild name
* guild.setName('Discord Guild')
* .then(updated => console.log(`Updated guild name to ${guild.name}`))
* .catch(console.error);
*/
setName(name) {
return this.edit({ name });
}
/**
* Edit the region of the guild.
* @param {string} region The new region of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild region
* guild.setRegion('london')
* .then(updated => console.log(`Updated guild region to ${guild.region}`))
* .catch(console.error);
*/
setRegion(region) {
return this.edit({ region });
}
/**
* Edit the verification level of the guild.
* @param {number} verificationLevel The new verification level of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild verification level
* guild.setVerificationLevel(1)
* .then(updated => console.log(`Updated guild verification level to ${guild.verificationLevel}`))
* .catch(console.error);
*/
setVerificationLevel(verificationLevel) {
return this.edit({ verificationLevel });
}
/**
* Edit the AFK channel of the guild.
* @param {ChannelResolvable} afkChannel The new AFK channel
* @returns {Promise<Guild>}
* @example
* // Edit the guild AFK channel
* guild.setAFKChannel(channel)
* .then(updated => console.log(`Updated guild AFK channel to ${guild.afkChannel}`))
* .catch(console.error);
*/
setAFKChannel(afkChannel) {
return this.edit({ afkChannel });
}
/**
* Edit the AFK timeout of the guild.
* @param {number} afkTimeout The time in seconds that a user must be idle to be considered AFK
* @returns {Promise<Guild>}
* @example
* // Edit the guild AFK channel
* guild.setAFKTimeout(60)
* .then(updated => console.log(`Updated guild AFK timeout to ${guild.afkTimeout}`))
* .catch(console.error);
*/
setAFKTimeout(afkTimeout) {
return this.edit({ afkTimeout });
}
/**
* Set a new guild icon.
* @param {Base64Resolvable} icon The new icon of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild icon
* guild.setIcon(fs.readFileSync('./icon.png'))
* .then(updated => console.log('Updated the guild icon'))
* .catch(console.error);
*/
setIcon(icon) {
return this.edit({ icon });
}
/**
* Sets a new owner of the guild.
* @param {GuildMemberResolvable} owner The new owner of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild owner
* guild.setOwner(guild.members.first())
* .then(updated => console.log(`Updated the guild owner to ${updated.owner.username}`))
* .catch(console.error);
*/
setOwner(owner) {
return this.edit({ owner });
}
/**
* Set a new guild splash screen.
* @param {Base64Resolvable} splash The new splash screen of the guild
* @returns {Promise<Guild>}
* @example
* // Edit the guild splash
* guild.setIcon(fs.readFileSync('./splash.png'))
* .then(updated => console.log('Updated the guild splash'))
* .catch(console.error);
*/
setSplash(splash) {
return this.edit({ splash });
}
/**
* @param {number} position Absolute or relative position
* @param {boolean} [relative=false] Whether to position relatively or absolutely
* @returns {Promise<Guild>}
*/
setPosition(position, relative) {
if (this.client.user.bot) {
return Promise.reject(new Error('Setting guild position is only available for user accounts'));
}
return this.client.user.settings.setGuildPosition(this, position, relative);
}
/**
* Marks all messages in this guild as read.
* <warn>This is only available when using a user account.</warn>
* @returns {Promise<Guild>} This guild
*/
acknowledge() {
return this.client.rest.methods.ackGuild(this);
}
/**
* Allow direct messages from guild members.
* @param {boolean} allow Whether to allow direct messages
* @returns {Promise<Guild>}
*/
allowDMs(allow) {
const settings = this.client.user.settings;
if (allow) return settings.removeRestrictedGuild(this);
else return settings.addRestrictedGuild(this);
}
/**
* Bans a user from the guild.
* @param {UserResolvable} user The user to ban
* @param {Object} [options] Ban options.
* @param {number} [options.days=0] Number of days of messages to delete
* @param {string} [options.reason] Reason for banning
* @returns {Promise<GuildMember|User|string>} Result object will be resolved as specifically as possible.
* If the GuildMember cannot be resolved, the User will instead be attempted to be resolved. If that also cannot
* be resolved, the user ID will be the result.
* @example
* // Ban a user by ID (or with a user/guild member object)
* guild.ban('some user ID')
* .then(user => console.log(`Banned ${user.username || user.id || user} from ${guild.name}`))
* .catch(console.error);
*/
ban(user, options = {}) {
if (typeof options === 'number') {
options = { reason: null, days: options };
} else if (typeof options === 'string') {
options = { reason: options, days: 0 };
}
return this.client.rest.methods.banGuildMember(this, user, options);
}
/**
* Unbans a user from the guild.
* @param {UserResolvable} user The user to unban
* @returns {Promise<User>}
* @example
* // Unban a user by ID (or with a user/guild member object)
* guild.unban('some user ID')
* .then(user => console.log(`Unbanned ${user.username} from ${guild.name}`))
* .catch(console.error);
*/
unban(user) {
return this.client.rest.methods.unbanGuildMember(this, user);
}
/**
* Prunes members from the guild based on how long they have been inactive.
* @param {number} days Number of days of inactivity required to kick
* @param {boolean} [dry=false] If true, will return number of users that will be kicked, without actually doing it
* @returns {Promise<number>} The number of members that were/will be kicked
* @example
* // See how many members will be pruned
* guild.pruneMembers(12, true)
* .then(pruned => console.log(`This will prune ${pruned} people!`))
* .catch(console.error);
* @example
* // Actually prune the members
* guild.pruneMembers(12)
* .then(pruned => console.log(`I just pruned ${pruned} people!`))
* .catch(console.error);
*/
pruneMembers(days, dry = false) {
if (typeof days !== 'number') throw new TypeError('Days must be a number.');
return this.client.rest.methods.pruneGuildMembers(this, days, dry);
}
/**
* Syncs this guild (already done automatically every 30 seconds).
* <warn>This is only available when using a user account.</warn>
*/
sync() {
if (!this.client.user.bot) this.client.syncGuilds([this]);
}
/**
* Creates a new channel in the guild.
* @param {string} name The name of the new channel
* @param {string} type The type of the new channel, either `text` or `voice`
* @param {Array<PermissionOverwrites|Object>} overwrites Permission overwrites to apply to the new channel
* @returns {Promise<TextChannel|VoiceChannel>}
* @example
* // Create a new text channel
* guild.createChannel('new-general', 'text')
* .then(channel => console.log(`Created new channel ${channel}`))
* .catch(console.error);
*/
createChannel(name, type, overwrites) {
return this.client.rest.methods.createChannel(this, name, type, overwrites);
}
/**
* The data needed for updating a channel's position.
* @typedef {Object} ChannelPosition
* @property {ChannelResolvable} channel Channel to update
* @property {number} position New position for the channel
*/
/**
* Batch-updates the guild's channels' positions.
* @param {ChannelPosition[]} channelPositions Channel positions to update
* @returns {Promise<Guild>}
* @example
* guild.updateChannels([{ channel: channelID, position: newChannelIndex }])
* .then(guild => console.log(`Updated channel positions for ${guild.id}`))
* .catch(console.error);
*/
setChannelPositions(channelPositions) {
return this.client.rest.methods.updateChannelPositions(this.id, channelPositions);
}
/**
* Creates a new role in the guild with given information
* @param {RoleData} [data] The data to update the role with
* @returns {Promise<Role>}
* @example
* // Create a new role
* guild.createRole()
* .then(role => console.log(`Created role ${role}`))
* .catch(console.error);
* @example
* // Create a new role with data
* guild.createRole({
* name: 'Super Cool People',
* color: 'BLUE',
* })
* .then(role => console.log(`Created role ${role}`))
* .catch(console.error)
*/
createRole(data = {}) {
return this.client.rest.methods.createGuildRole(this, data);
}
/**
* Creates a new custom emoji in the guild.
* @param {BufferResolvable|Base64Resolvable} attachment The image for the emoji
* @param {string} name The name for the emoji
* @param {Collection<Snowflake, Role>|Role[]} [roles] Roles to limit the emoji to
* @returns {Promise<Emoji>} The created emoji
* @example
* // Create a new emoji from a url
* guild.createEmoji('https://i.imgur.com/w3duR07.png', 'rip')
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
* @example
* // Create a new emoji from a file on your computer
* guild.createEmoji('./memes/banana.png', 'banana')
* .then(emoji => console.log(`Created new emoji with name ${emoji.name}!`))
* .catch(console.error);
*/
createEmoji(attachment, name, roles) {
return new Promise(resolve => {
if (typeof attachment === 'string' && attachment.startsWith('data:')) {
resolve(this.client.rest.methods.createEmoji(this, attachment, name, roles));
} else {
this.client.resolver.resolveBuffer(attachment).then(data => {
const dataURI = this.client.resolver.resolveBase64(data);
resolve(this.client.rest.methods.createEmoji(this, dataURI, name, roles));
});
}
});
}
/**
* Delete an emoji.
* @param {Emoji|string} emoji The emoji to delete
* @returns {Promise}
*/
deleteEmoji(emoji) {
if (!(emoji instanceof Emoji)) emoji = this.emojis.get(emoji);
return this.client.rest.methods.deleteEmoji(emoji);
}
/**
* Causes the client to leave the guild.
* @returns {Promise<Guild>}
* @example
* // Leave a guild
* guild.leave()
* .then(g => console.log(`Left the guild ${g}`))
* .catch(console.error);
*/
leave() {
return this.client.rest.methods.leaveGuild(this);
}
/**
* Causes the client to delete the guild.
* @returns {Promise<Guild>}
* @example
* // Delete a guild
* guild.delete()
* .then(g => console.log(`Deleted the guild ${g}`))
* .catch(console.error);
*/
delete() {
return this.client.rest.methods.deleteGuild(this);
}
/**
* Whether this guild equals another guild. It compares all properties, so for most operations
* it is advisable to just compare `guild.id === guild2.id` as it is much faster and is often
* what most users need.
* @param {Guild} guild The guild to compare with
* @returns {boolean}
*/
equals(guild) {
let equal =
guild &&
this.id === guild.id &&
this.available === !guild.unavailable &&
this.splash === guild.splash &&
this.region === guild.region &&
this.name === guild.name &&
this.memberCount === guild.member_count &&
this.large === guild.large &&
this.icon === guild.icon &&
Util.arraysEqual(this.features, guild.features) &&
this.ownerID === guild.owner_id &&
this.verificationLevel === guild.verification_level &&
this.embedEnabled === guild.embed_enabled;
if (equal) {
if (this.embedChannel) {
if (this.embedChannel.id !== guild.embed_channel_id) equal = false;
} else if (guild.embed_channel_id) {
equal = false;
}
}
return equal;
}
/**
* When concatenated with a string, this automatically concatenates the guild's name instead of the guild object.
* @returns {string}
* @example
* // Logs: Hello from My Guild!
* console.log(`Hello from ${guild}!`);
* @example
* // Logs: Hello from My Guild!
* console.log('Hello from ' + guild + '!');
*/
toString() {
return this.name;
}
_addMember(guildUser, emitEvent = true) {
const existing = this.members.has(guildUser.user.id);
if (!(guildUser.user instanceof User)) guildUser.user = this.client.dataManager.newUser(guildUser.user);
guildUser.joined_at = guildUser.joined_at || 0;
const member = new GuildMember(this, guildUser);
this.members.set(member.id, member);
if (this._rawVoiceStates && this._rawVoiceStates.has(member.user.id)) {
const voiceState = this._rawVoiceStates.get(member.user.id);
member.serverMute = voiceState.mute;
member.serverDeaf = voiceState.deaf;
member.selfMute = voiceState.self_mute;
member.selfDeaf = voiceState.self_deaf;
member.voiceSessionID = voiceState.session_id;
member.voiceChannelID = voiceState.channel_id;
if (this.client.channels.has(voiceState.channel_id)) {
this.client.channels.get(voiceState.channel_id).members.set(member.user.id, member);
} else {
this.client.emit('warn', `Member ${member.id} added in guild ${this.id} with an uncached voice channel`);
}
}
/**
* Emitted whenever a user joins a guild.
* @event Client#guildMemberAdd
* @param {GuildMember} member The member that has joined a guild
*/
if (this.client.ws.connection.status === Constants.Status.READY && emitEvent && !existing) {
this.client.emit(Constants.Events.GUILD_MEMBER_ADD, member);
}
return member;
}
_updateMember(member, data) {
const oldMember = Util.cloneObject(member);
if (data.roles) member._roles = data.roles;
if (typeof data.nick !== 'undefined') member.nickname = data.nick;
const notSame = member.nickname !== oldMember.nickname || !Util.arraysEqual(member._roles, oldMember._roles);
if (this.client.ws.connection.status === Constants.Status.READY && notSame) {
/**
* Emitted whenever a guild member changes - i.e. new role, removed role, nickname.
* @event Client#guildMemberUpdate
* @param {GuildMember} oldMember The member before the update
* @param {GuildMember} newMember The member after the update
*/
this.client.emit(Constants.Events.GUILD_MEMBER_UPDATE, oldMember, member);
}
return {
old: oldMember,
mem: member,
};
}
_removeMember(guildMember) {
this.members.delete(guildMember.id);
}
_memberSpeakUpdate(user, speaking) {
const member = this.members.get(user);
if (member && member.speaking !== speaking) {
member.speaking = speaking;
/**
* Emitted once a guild member starts/stops speaking.
* @event Client#guildMemberSpeaking
* @param {GuildMember} member The member that started/stopped speaking
* @param {boolean} speaking Whether or not the member is speaking
*/
this.client.emit(Constants.Events.GUILD_MEMBER_SPEAKING, member, speaking);
}
}
_setPresence(id, presence) {
if (this.presences.get(id)) {
this.presences.get(id).update(presence);
return;
}
this.presences.set(id, new Presence(presence));
}
/**
* Set the position of a role in this guild.
* @param {string|Role} role The role to edit, can be a role object or a role ID
* @param {number} position The new position of the role
* @param {boolean} [relative=false] Position Moves the role relative to its current position
* @returns {Promise<Guild>}
*/
setRolePosition(role, position, relative = false) {
if (typeof role === 'string') {
role = this.roles.get(role);
if (!role) return Promise.reject(new Error('Supplied role is not a role or snowflake.'));
}
position = Number(position);
if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.'));
let updatedRoles = this._sortedRoles.array();
Util.moveElementInArray(updatedRoles, role, position, relative);
updatedRoles = updatedRoles.map((r, i) => ({ id: r.id, position: i }));
return this.client.rest.methods.setRolePositions(this.id, updatedRoles);
}
/**
* Set the position of a channel in this guild.
* @param {string|GuildChannel} channel The channel to edit, can be a channel object or a channel ID
* @param {number} position The new position of the channel
* @param {boolean} [relative=false] Position Moves the channel relative to its current position
* @returns {Promise<Guild>}
*/
setChannelPosition(channel, position, relative = false) {
if (typeof channel === 'string') {
channel = this.channels.get(channel);
if (!channel) return Promise.reject(new Error('Supplied channel is not a channel or snowflake.'));
}
position = Number(position);
if (isNaN(position)) return Promise.reject(new Error('Supplied position is not a number.'));
let updatedChannels = this._sortedChannels(channel.type).array();
Util.moveElementInArray(updatedChannels, channel, position, relative);
updatedChannels = updatedChannels.map((r, i) => ({ id: r.id, position: i }));
return this.client.rest.methods.setChannelPositions(this.id, updatedChannels);
}
/**
* Fetches a collection of channels in the current guild sorted by position.
* @param {string} type The channel type
* @returns {Collection<Snowflake, GuildChannel>}
* @private
*/
_sortedChannels(type) {
return this._sortPositionWithID(this.channels.filter(c => {
if (type === 'voice' && c.type === 'voice') return true;
else if (type !== 'voice' && c.type !== 'voice') return true;
else return type === c.type;
}));
}
/**
* Sorts a collection by object position or ID if the positions are equivalent.
* Intended to be identical to Discord's sorting method.
* @param {Collection} collection The collection to sort
* @returns {Collection}
* @private
*/
_sortPositionWithID(collection) {
return collection.sort((a, b) =>
a.position !== b.position ?
a.position - b.position :
Long.fromString(a.id).sub(Long.fromString(b.id)).toNumber()
);
}
}
module.exports = Guild;
|
aemino/discord.js
|
src/structures/Guild.js
|
JavaScript
|
apache-2.0
| 34,442 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import str
import six
import logging
import filecmp
import os
import re
import sys
import uuid
import json
import time
from nose.plugins.attrib import attr
from nose.tools import assert_raises, assert_equals, assert_less
import tempfile
import shutil
from mock import patch
import synapseclient
import synapseclient.client as client
import synapseclient.utils as utils
import synapseclient.__main__ as cmdline
from synapseclient.evaluation import Evaluation
import integration
from integration import schedule_for_cleanup, QUERY_TIMEOUT_SEC
if six.PY2:
from StringIO import StringIO
else:
from io import StringIO
def setup_module(module):
module.syn = integration.syn
module.project = integration.project
module.parser = cmdline.build_parser()
#used for --description and --descriptionFile tests
module.upload_filename = _create_temp_file_with_cleanup()
module.description_text = "'some description text'"
module.desc_filename = _create_temp_file_with_cleanup(module.description_text)
module.update_description_text = "'SOMEBODY ONCE TOLD ME THE WORLD WAS GONNA ROLL ME I AINT THE SHARPEST TOOL IN THE SHED'"
module.other_user = integration.other_user
def run(*command, **kwargs):
"""
Sends the given command list to the command line client.
:returns: The STDOUT output of the command.
"""
old_stdout = sys.stdout
capturedSTDOUT = StringIO()
syn_client = kwargs.get('syn', syn)
stream_handler = logging.StreamHandler(capturedSTDOUT)
try:
sys.stdout = capturedSTDOUT
syn_client.logger.addHandler(stream_handler)
sys.argv = [item for item in command]
args = parser.parse_args()
args.debug = True
cmdline.perform_main(args, syn_client)
except SystemExit:
pass # Prevent the test from quitting prematurely
finally:
sys.stdout = old_stdout
syn_client.logger.handlers.remove(stream_handler)
capturedSTDOUT = capturedSTDOUT.getvalue()
return capturedSTDOUT
def parse(regex, output):
"""Returns the first match."""
m = re.search(regex, output)
if m:
if len(m.groups()) > 0:
return m.group(1).strip()
else:
raise Exception('ERROR parsing output: "' + str(output) + '"')
def test_command_line_client():
# Create a Project
output = run('synapse',
'--skip-checks',
'create',
'-name',
str(uuid.uuid4()),
'-description',
'test of command line client',
'Project')
project_id = parse(r'Created entity:\s+(syn\d+)\s+', output)
schedule_for_cleanup(project_id)
# Create a File
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'add',
'-name',
'BogusFileEntity',
'-description',
'Bogus data to test file upload',
'-parentid',
project_id,
filename)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Verify that we stored the file in Synapse
f1 = syn.get(file_entity_id)
fh = syn._getFileHandle(f1.dataFileHandleId)
assert fh['concreteType'] == 'org.sagebionetworks.repo.model.file.S3FileHandle'
# Get File from the command line
output = run('synapse',
'--skip-checks',
'get',
file_entity_id)
downloaded_filename = parse(r'Downloaded file:\s+(.*)', output)
schedule_for_cleanup(downloaded_filename)
assert os.path.exists(downloaded_filename)
assert filecmp.cmp(filename, downloaded_filename)
# Update the File
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'store',
'--id',
file_entity_id,
filename)
updated_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)', output)
# Get the File again
output = run('synapse',
'--skip-checks',
'get',
file_entity_id)
downloaded_filename = parse(r'Downloaded file:\s+(.*)', output)
schedule_for_cleanup(downloaded_filename)
assert os.path.exists(downloaded_filename)
assert filecmp.cmp(filename, downloaded_filename)
# Test query
output = ""
start_time = time.time()
while not ('BogusFileEntity' in output and file_entity_id in output):
assert_less(time.time() - start_time, QUERY_TIMEOUT_SEC)
output = run('synapse',
'--skip-checks',
'query',
'select id, name from entity where parentId=="%s"' % project_id)
# Move the file to new folder
folder = syn.store(synapseclient.Folder(parentId=project_id))
output = run('synapse',
'mv',
'--id',
file_entity_id,
'--parentid',
folder.id)
downloaded_filename = parse(r'Moved\s+(.*)', output)
movedFile = syn.get(file_entity_id, downloadFile=False)
assert movedFile.parentId == folder.id
# Test Provenance
repo_url = 'https://github.com/Sage-Bionetworks/synapsePythonClient'
output = run('synapse',
'--skip-checks',
'set-provenance',
'-id',
file_entity_id,
'-name',
'TestActivity',
'-description',
'A very excellent provenance',
'-used',
file_entity_id,
'-executed',
repo_url)
activity_id = parse(r'Set provenance record (\d+) on entity syn\d+', output)
output = run('synapse',
'--skip-checks',
'get-provenance',
'--id',
file_entity_id)
activity = json.loads(output)
assert activity['name'] == 'TestActivity'
assert activity['description'] == 'A very excellent provenance'
used = utils._find_used(activity, lambda used: 'reference' in used)
assert used['reference']['targetId'] == file_entity_id
used = utils._find_used(activity, lambda used: 'url' in used)
assert used['url'] == repo_url
assert used['wasExecuted'] == True
# Note: Tests shouldn't have external dependencies
# but this is a pretty picture of Singapore
singapore_url = 'http://upload.wikimedia.org/wikipedia/commons/' \
'thumb/3/3e/1_singapore_city_skyline_dusk_panorama_2011.jpg' \
'/1280px-1_singapore_city_skyline_dusk_panorama_2011.jpg'
# Test external file handle
output = run('synapse',
'--skip-checks',
'add',
'-name',
'Singapore',
'-description',
'A nice picture of Singapore',
'-parentid',
project_id,
singapore_url)
exteral_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Verify that we created an external file handle
f2 = syn.get(exteral_entity_id)
fh = syn._getFileHandle(f2.dataFileHandleId)
assert fh['concreteType'] == 'org.sagebionetworks.repo.model.file.ExternalFileHandle'
output = run('synapse',
'--skip-checks',
'get',
exteral_entity_id)
downloaded_filename = parse(r'Downloaded file:\s+(.*)', output)
schedule_for_cleanup(downloaded_filename)
assert os.path.exists(downloaded_filename)
# Delete the Project
output = run('synapse',
'--skip-checks',
'delete',
project_id)
def test_command_line_client_annotations():
# Create a Project
output = run('synapse',
'--skip-checks',
'create',
'-name',
str(uuid.uuid4()),
'-description',
'test of command line client',
'Project')
project_id = parse(r'Created entity:\s+(syn\d+)\s+', output)
schedule_for_cleanup(project_id)
# Create a File
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'add',
'-name',
'BogusFileEntity',
'-description',
'Bogus data to test file upload',
'-parentid',
project_id,
filename)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Test setting annotations
output = run('synapse',
'--skip-checks',
'set-annotations',
'--id',
file_entity_id,
'--annotations',
'{"foo": 1, "bar": "1", "baz": [1, 2, 3]}',
)
# Test getting annotations
# check that the three things set are correct
# This test should be adjusted to check for equality of the
# whole annotation dictionary once the issue of other
# attributes (creationDate, eTag, id, uri) being returned is resolved
# See: https://sagebionetworks.jira.com/browse/SYNPY-175
output = run('synapse',
'--skip-checks',
'get-annotations',
'--id',
file_entity_id
)
annotations = json.loads(output)
assert annotations['foo'] == [1]
assert annotations['bar'] == [u"1"]
assert annotations['baz'] == [1, 2, 3]
# Test setting annotations by replacing existing ones.
output = run('synapse',
'--skip-checks',
'set-annotations',
'--id',
file_entity_id,
'--annotations',
'{"foo": 2}',
'--replace'
)
# Test that the annotation was updated
output = run('synapse',
'--skip-checks',
'get-annotations',
'--id',
file_entity_id
)
annotations = json.loads(output)
assert annotations['foo'] == [2]
# Since this replaces the existing annotations, previous values
# Should not be available.
assert_raises(KeyError, lambda key: annotations[key], 'bar')
assert_raises(KeyError, lambda key: annotations[key], 'baz')
# Test running add command to set annotations on a new object
filename2 = utils.make_bogus_data_file()
schedule_for_cleanup(filename2)
output = run('synapse',
'--skip-checks',
'add',
'-name',
'BogusData2',
'-description',
'Bogus data to test file upload with add and add annotations',
'-parentid',
project_id,
'--annotations',
'{"foo": 123}',
filename2)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Test that the annotation was updated
output = run('synapse',
'--skip-checks',
'get-annotations',
'--id',
file_entity_id
)
annotations = json.loads(output)
assert annotations['foo'] == [123]
# Test running store command to set annotations on a new object
filename3 = utils.make_bogus_data_file()
schedule_for_cleanup(filename3)
output = run('synapse',
'--skip-checks',
'store',
'--name',
'BogusData3',
'--description',
'\"Bogus data to test file upload with store and add annotations\"',
'--parentid',
project_id,
'--annotations',
'{"foo": 456}',
filename3)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Test that the annotation was updated
output = run('synapse',
'--skip-checks',
'get-annotations',
'--id',
file_entity_id
)
annotations = json.loads(output)
assert annotations['foo'] == [456]
def test_command_line_store_and_submit():
# Create a Project
output = run('synapse',
'--skip-checks',
'store',
'--name',
str(uuid.uuid4()),
'--description',
'test of store command',
'--type',
'Project')
project_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
schedule_for_cleanup(project_id)
# Create and upload a file
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'store',
'--description',
'Bogus data to test file upload',
'--parentid',
project_id,
'--file',
filename)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Verify that we stored the file in Synapse
f1 = syn.get(file_entity_id)
fh = syn._getFileHandle(f1.dataFileHandleId)
assert fh['concreteType'] == 'org.sagebionetworks.repo.model.file.S3FileHandle'
# Test that entity is named after the file it contains
assert f1.name == os.path.basename(filename)
# Create an Evaluation to submit to
eval = Evaluation(name=str(uuid.uuid4()), contentSource=project_id)
eval = syn.store(eval)
schedule_for_cleanup(eval)
# Submit a bogus file
output = run('synapse',
'--skip-checks',
'submit',
'--evaluation',
eval.id,
'--name',
'Some random name',
'--entity',
file_entity_id)
submission_id = parse(r'Submitted \(id: (\d+)\) entity:\s+', output)
#testing different commmand line options for submitting to an evaluation
#. submitting to an evaluation by evaluationID
output = run('synapse',
'--skip-checks',
'submit',
'--evalID',
eval.id,
'--name',
'Some random name',
'--alias',
'My Team',
'--entity',
file_entity_id)
submission_id = parse(r'Submitted \(id: (\d+)\) entity:\s+', output)
# Update the file
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'store',
'--id',
file_entity_id,
'--file',
filename)
updated_entity_id = parse(r'Updated entity:\s+(syn\d+)', output)
schedule_for_cleanup(updated_entity_id)
# Submit an updated bogus file and this time by evaluation name
output = run('synapse',
'--skip-checks',
'submit',
'--evaluationName',
eval.name,
'--entity',
file_entity_id)
submission_id = parse(r'Submitted \(id: (\d+)\) entity:\s+', output)
# Tests shouldn't have external dependencies, but here it's required
ducky_url = 'https://www.synapse.org/Portal/clear.cache.gif'
# Test external file handle
output = run('synapse',
'--skip-checks',
'store',
'--name',
'Rubber Ducky',
'--description',
'I like rubber duckies',
'--parentid',
project_id,
'--file',
ducky_url)
exteral_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
schedule_for_cleanup(exteral_entity_id)
# Verify that we created an external file handle
f2 = syn.get(exteral_entity_id)
fh = syn._getFileHandle(f2.dataFileHandleId)
assert fh['concreteType'] == 'org.sagebionetworks.repo.model.file.ExternalFileHandle'
#submit an external file to an evaluation and use provenance
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
repo_url = 'https://github.com/Sage-Bionetworks/synapsePythonClient'
output = run('synapse',
'--skip-checks',
'submit',
'--evalID',
eval.id,
'--file',
filename,
'--parent',
project_id,
'--used',
exteral_entity_id,
'--executed',
repo_url
)
submission_id = parse(r'Submitted \(id: (\d+)\) entity:\s+', output)
# Delete project
output = run('synapse',
'--skip-checks',
'delete',
project_id)
def test_command_get_recursive_and_query():
"""Tests the 'synapse get -r' and 'synapse get -q' functions"""
project_entity = project
# Create Folders in Project
folder_entity = syn.store(synapseclient.Folder(name=str(uuid.uuid4()),
parent=project_entity))
folder_entity2 = syn.store(synapseclient.Folder(name=str(uuid.uuid4()),
parent=folder_entity))
# Create and upload two files in sub-Folder
uploaded_paths = []
file_entities = []
for i in range(2):
f = utils.make_bogus_data_file()
uploaded_paths.append(f)
schedule_for_cleanup(f)
file_entity = synapseclient.File(f, parent=folder_entity2)
file_entity = syn.store(file_entity)
file_entities.append(file_entity)
schedule_for_cleanup(f)
#Add a file in the Folder as well
f = utils.make_bogus_data_file()
uploaded_paths.append(f)
schedule_for_cleanup(f)
file_entity = synapseclient.File(f, parent=folder_entity)
file_entity = syn.store(file_entity)
file_entities.append(file_entity)
time.sleep(2) # get -r uses syncFromSynapse() which uses getChildren(), which is not immediately consistent, but faster than chunked queries.
### Test recursive get
output = run('synapse', '--skip-checks',
'get', '-r',
folder_entity.id)
#Verify that we downloaded files:
new_paths = [os.path.join('.', folder_entity2.name, os.path.basename(f)) for f in uploaded_paths[:-1]]
new_paths.append(os.path.join('.', os.path.basename(uploaded_paths[-1])))
schedule_for_cleanup(folder_entity.name)
for downloaded, uploaded in zip(new_paths, uploaded_paths):
assert os.path.exists(downloaded)
assert filecmp.cmp(downloaded, uploaded)
schedule_for_cleanup(downloaded)
time.sleep(3) # get -q uses chunkedQuery which are eventually consistent
### Test query get
### Note: We're not querying on annotations because tests can fail if there
### are lots of jobs queued as happens when staging is syncing
output = run('synapse', '--skip-checks',
'get', '-q', "select id from file where parentId=='%s'" %
folder_entity2.id)
#Verify that we downloaded files from folder_entity2
new_paths = [os.path.join('.', os.path.basename(f)) for f in uploaded_paths[:-1]]
for downloaded, uploaded in zip(new_paths, uploaded_paths[:-1]):
assert os.path.exists(downloaded)
assert filecmp.cmp(downloaded, uploaded)
schedule_for_cleanup(downloaded)
schedule_for_cleanup(new_paths[0])
### Test query get using a Table with an entity column
### This should be replaced when Table File Views are implemented in the client
cols = []
cols.append(synapseclient.Column(name='id', columnType='ENTITYID'))
schema1 = syn.store(synapseclient.Schema(name='Foo Table', columns=cols, parent=project_entity))
schedule_for_cleanup(schema1.id)
data1 =[[x.id] for x in file_entities]
row_reference_set1 = syn.store(synapseclient.RowSet(schema=schema1,
rows=[synapseclient.Row(r) for r in data1]))
time.sleep(3) # get -q uses chunkedQuery which are eventually consistent
### Test Table/View query get
output = run('synapse', '--skip-checks', 'get', '-q',
"select id from %s" % schema1.id)
#Verify that we downloaded files:
new_paths = [os.path.join('.', os.path.basename(f)) for f in uploaded_paths[:-1]]
new_paths.append(os.path.join('.', os.path.basename(uploaded_paths[-1])))
schedule_for_cleanup(folder_entity.name)
for downloaded, uploaded in zip(new_paths, uploaded_paths):
assert os.path.exists(downloaded)
assert filecmp.cmp(downloaded, uploaded)
schedule_for_cleanup(downloaded)
schedule_for_cleanup(new_paths[0])
def test_command_copy():
"""Tests the 'synapse cp' function"""
# Create a Project
project_entity = syn.store(synapseclient.Project(name=str(uuid.uuid4())))
schedule_for_cleanup(project_entity.id)
# Create a Folder in Project
folder_entity = syn.store(synapseclient.Folder(name=str(uuid.uuid4()),
parent=project_entity))
schedule_for_cleanup(folder_entity.id)
# Create and upload a file in Folder
repo_url = 'https://github.com/Sage-Bionetworks/synapsePythonClient'
annots = {'test':['hello_world']}
# Create, upload, and set annotations on a file in Folder
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
file_entity = syn.store(synapseclient.File(filename, parent=folder_entity))
externalURL_entity = syn.store(synapseclient.File(repo_url,name='rand',parent=folder_entity,synapseStore=False))
syn.setAnnotations(file_entity,annots)
syn.setAnnotations(externalURL_entity,annots)
schedule_for_cleanup(file_entity.id)
schedule_for_cleanup(externalURL_entity.id)
### Test cp function
output = run('synapse', '--skip-checks',
'cp',file_entity.id,
'--destinationId',project_entity.id)
output_URL = run('synapse', '--skip-checks',
'cp',externalURL_entity.id,
'--destinationId',project_entity.id)
copied_id = parse(r'Copied syn\d+ to (syn\d+)',output)
copied_URL_id = parse(r'Copied syn\d+ to (syn\d+)',output_URL)
#Verify that our copied files are identical
copied_ent = syn.get(copied_id)
copied_URL_ent = syn.get(copied_URL_id,downloadFile=False)
schedule_for_cleanup(copied_id)
schedule_for_cleanup(copied_URL_id)
copied_ent_annot = syn.getAnnotations(copied_id)
copied_url_annot = syn.getAnnotations(copied_URL_id)
copied_prov = syn.getProvenance(copied_id)['used'][0]['reference']['targetId']
copied_url_prov = syn.getProvenance(copied_URL_id)['used'][0]['reference']['targetId']
#Make sure copied files are the same
assert copied_prov == file_entity.id
assert copied_ent_annot == annots
assert copied_ent.properties.dataFileHandleId == file_entity.properties.dataFileHandleId
#Make sure copied URLs are the same
assert copied_url_prov == externalURL_entity.id
assert copied_url_annot == annots
assert copied_URL_ent.externalURL == repo_url
assert copied_URL_ent.name == 'rand'
assert copied_URL_ent.properties.dataFileHandleId == externalURL_entity.properties.dataFileHandleId
#Verify that errors are being thrown when a
#file is copied to a folder/project that has a file with the same filename
assert_raises(ValueError,run, 'synapse', '--debug', '--skip-checks',
'cp',file_entity.id,
'--destinationId',project_entity.id)
def test_command_line_using_paths():
# Create a Project
project_entity = syn.store(synapseclient.Project(name=str(uuid.uuid4())))
schedule_for_cleanup(project_entity.id)
# Create a Folder in Project
folder_entity = syn.store(synapseclient.Folder(name=str(uuid.uuid4()), parent=project_entity))
# Create and upload a file in Folder
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
file_entity = syn.store(synapseclient.File(filename, parent=folder_entity))
# Verify that we can use show with a filename
output = run('synapse', '--skip-checks', 'show', filename)
id = parse(r'File: %s\s+\((syn\d+)\)\s+' %os.path.split(filename)[1], output)
assert file_entity.id == id
# Verify that limitSearch works by making sure we get the file entity
# that's inside the folder
file_entity2 = syn.store(synapseclient.File(filename, parent=project_entity))
output = run('synapse', '--skip-checks', 'get',
'--limitSearch', folder_entity.id,
filename)
id = parse(r'Associated file: .* with synapse ID (syn\d+)', output)
name = parse(r'Associated file: (.*) with synapse ID syn\d+', output)
assert_equals(file_entity.id, id)
assert utils.equal_paths(name, filename)
#Verify that set-provenance works with filepath
repo_url = 'https://github.com/Sage-Bionetworks/synapsePythonClient'
output = run('synapse', '--skip-checks', 'set-provenance',
'-id', file_entity2.id,
'-name', 'TestActivity',
'-description', 'A very excellent provenance',
'-used', filename,
'-executed', repo_url,
'-limitSearch', folder_entity.id)
activity_id = parse(r'Set provenance record (\d+) on entity syn\d+', output)
output = run('synapse', '--skip-checks', 'get-provenance',
'-id', file_entity2.id)
activity = json.loads(output)
assert activity['name'] == 'TestActivity'
assert activity['description'] == 'A very excellent provenance'
#Verify that store works with provenance specified with filepath
repo_url = 'https://github.com/Sage-Bionetworks/synapsePythonClient'
filename2 = utils.make_bogus_data_file()
schedule_for_cleanup(filename2)
output = run('synapse', '--skip-checks', 'add', filename2,
'-parentid', project_entity.id,
'-used', filename,
'-executed', '%s %s' %(repo_url, filename))
entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
output = run('synapse', '--skip-checks', 'get-provenance',
'-id', entity_id)
activity = json.loads(output)
a = [a for a in activity['used'] if a['wasExecuted']==False]
assert a[0]['reference']['targetId'] in [file_entity.id, file_entity2.id]
#Test associate command
#I have two files in Synapse filename and filename2
path = tempfile.mkdtemp()
schedule_for_cleanup(path)
shutil.copy(filename, path)
shutil.copy(filename2, path)
output = run('synapse', '--skip-checks', 'associate', path, '-r')
output = run('synapse', '--skip-checks', 'show', filename)
def test_table_query():
"""Test command line ability to do table query.
"""
cols = []
cols.append(synapseclient.Column(name='name', columnType='STRING', maximumSize=1000))
cols.append(synapseclient.Column(name='foo', columnType='STRING', enumValues=['foo', 'bar', 'bat']))
cols.append(synapseclient.Column(name='x', columnType='DOUBLE'))
cols.append(synapseclient.Column(name='age', columnType='INTEGER'))
cols.append(synapseclient.Column(name='cartoon', columnType='BOOLEAN'))
project_entity = project
schema1 = syn.store(synapseclient.Schema(name=str(uuid.uuid4()), columns=cols, parent=project_entity))
schedule_for_cleanup(schema1.id)
data1 =[['Chris', 'bar', 11.23, 45, False],
['Jen', 'bat', 14.56, 40, False],
['Jane', 'bat', 17.89, 6, False],
['Henry', 'bar', 10.12, 1, False]]
row_reference_set1 = syn.store(synapseclient.RowSet(schema=schema1,
rows=[synapseclient.Row(r) for r in data1]))
# Test query
output = run('synapse', '--skip-checks', 'query',
'select * from %s' % schema1.id)
output_rows = output.rstrip("\n").split("\n")
# Check the length of the output
assert len(output_rows) == 5, "got %s rows" % (len(output_rows),)
# Check that headers are correct.
# Should be column names in schema plus the ROW_ID and ROW_VERSION
my_headers_set = output_rows[0].split("\t")
expected_headers_set = ["ROW_ID", "ROW_VERSION"] + list(map(lambda x: x.name, cols))
assert my_headers_set == expected_headers_set, "%r != %r" % (my_headers_set, expected_headers_set)
def test_login():
if not other_user['username']:
raise SkipTest("Skipping test for login command: No [test-authentication] in %s" % client.CONFIG_FILE)
alt_syn = synapseclient.Synapse()
with patch.object(alt_syn, "login") as mock_login, patch.object(alt_syn, "getUserProfile", return_value={"userName":"test_user","ownerId":"ownerId"}) as mock_get_user_profile:
output = run('synapse', '--skip-checks', 'login',
'-u', other_user['username'],
'-p', other_user['password'],
'--rememberMe',
syn=alt_syn)
mock_login.assert_called_once_with(other_user['username'], other_user['password'], forced=True, rememberMe=True, silent=False)
mock_get_user_profile.assert_called_once_with()
def test_configPath():
"""Test using a user-specified configPath for Synapse configuration file.
"""
tmp_config_file = tempfile.NamedTemporaryFile(suffix='.synapseConfig', delete=False)
shutil.copyfile(synapseclient.client.CONFIG_FILE, tmp_config_file.name)
# Create a File
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
output = run('synapse',
'--skip-checks',
'--configPath',
tmp_config_file.name,
'add',
'-name',
'BogusFileEntityTwo',
'-description',
'Bogus data to test file upload',
'-parentid',
project.id,
filename)
file_entity_id = parse(r'Created/Updated entity:\s+(syn\d+)\s+', output)
# Verify that we stored the file in Synapse
f1 = syn.get(file_entity_id)
fh = syn._getFileHandle(f1.dataFileHandleId)
assert fh['concreteType'] == 'org.sagebionetworks.repo.model.file.S3FileHandle'
def _description_wiki_check(run_output, expected_description):
entity_id = parse(r'Created.* entity:\s+(syn\d+)\s+', run_output)
wiki = syn.getWiki(entity_id)
assert_equals(expected_description, wiki.markdown)
def _create_temp_file_with_cleanup(specific_file_text = None):
if specific_file_text:
with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as file:
file.write(specific_file_text)
filename = file.name
else:
filename = utils.make_bogus_data_file()
schedule_for_cleanup(filename)
return filename
def test_create__with_description():
output = run('synapse',
'create',
'Folder',
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--description',
description_text
)
_description_wiki_check(output, description_text)
def test_store__with_description():
output = run('synapse',
'store',
upload_filename,
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--description',
description_text
)
_description_wiki_check(output, description_text)
def test_add__with_description():
output = run('synapse',
'add',
upload_filename,
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--description',
description_text
)
_description_wiki_check(output, description_text)
def test_create__with_descriptionFile():
output = run('synapse',
'create',
'Folder',
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
def test_store__with_descriptionFile():
output = run('synapse',
'store',
upload_filename,
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
def test_add__with_descriptionFile():
output = run('synapse',
'add',
upload_filename,
'-name',
str(uuid.uuid4()),
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
def test_create__update_description():
name = str(uuid.uuid4())
output = run('synapse',
'create',
'Folder',
'-name',
name,
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
output = run('synapse',
'create',
'Folder',
'-name',
name,
'-parentid',
project.id,
'--description',
update_description_text
)
_description_wiki_check(output, update_description_text)
def test_store__update_description():
name = str(uuid.uuid4())
output = run('synapse',
'store',
upload_filename,
'-name',
name,
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
output = run('synapse',
'store',
upload_filename,
'-name',
name,
'-parentid',
project.id,
'--description',
update_description_text
)
_description_wiki_check(output, update_description_text)
def test_add__update_description():
name = str(uuid.uuid4())
output = run('synapse',
'add',
upload_filename,
'-name',
name,
'-parentid',
project.id,
'--descriptionFile',
desc_filename
)
_description_wiki_check(output, description_text)
output = run('synapse',
'add',
upload_filename,
'-name',
name,
'-parentid',
project.id,
'--description',
update_description_text
)
_description_wiki_check(output, update_description_text)
|
zimingd/synapsePythonClient
|
tests/integration/test_command_line_client.py
|
Python
|
apache-2.0
| 36,272 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.accumulo.core.metadata;
import org.apache.hadoop.fs.Path;
/**
* Utility class for validation of metadata tablet files.
*/
public class TabletFileUtil {
/**
* Validate if string is a valid path. Return normalized string or throw exception if not valid.
* This was added to facilitate more use of TabletFile over String but this puts the validation in
* one location in the case where TabletFile can't be used.
*/
public static String validate(String path) {
Path p = new Path(path);
if (p.toUri().getScheme() == null) {
throw new IllegalArgumentException("Invalid path provided, no scheme in " + path);
}
return p.toString();
}
public static Path validate(Path path) {
if (path.toUri().getScheme() == null) {
throw new IllegalArgumentException("Invalid path provided, no scheme in " + path);
}
return path;
}
}
|
keith-turner/accumulo
|
core/src/main/java/org/apache/accumulo/core/metadata/TabletFileUtil.java
|
Java
|
apache-2.0
| 1,705 |
package com.codefactoring.android.backlogtracker.sync.fetchers;
import android.util.Log;
import com.codefactoring.android.backlogapi.BacklogApiClient;
import com.codefactoring.android.backlogapi.models.User;
import com.codefactoring.android.backlogtracker.sync.models.BacklogImage;
import com.codefactoring.android.backlogtracker.sync.models.UserDto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.functions.Func1;
public class UserDataFetcher {
public final String LOG_TAG = UserDataFetcher.class.getSimpleName();
private final BacklogApiClient mBacklogApiClient;
public UserDataFetcher(BacklogApiClient backlogApiClient) {
mBacklogApiClient = backlogApiClient;
}
public List<UserDto> getUserList() {
return mBacklogApiClient.getUserOperations().getUserList()
.onErrorReturn(new Func1<Throwable, List<User>>() {
@Override
public List<User> call(Throwable throwable) {
Log.e(LOG_TAG, "Error on getUserList", throwable);
return new ArrayList<>();
}
})
.flatMapIterable(new Func1<List<User>, Iterable<User>>() {
@Override
public Iterable<User> call(List<User> users) {
return users;
}
})
.flatMap(new Func1<User, Observable<UserDto>>() {
@Override
public Observable<UserDto> call(User user) {
final UserDto userDto = new UserDto();
userDto.setId(user.getId());
userDto.setUserId(user.getUserId());
userDto.setName(user.getName());
userDto.setImage(getBacklogImage(user.getId()));
return Observable.just(userDto);
}
})
.toList()
.toBlocking()
.first();
}
private BacklogImage getBacklogImage(final long id) {
return mBacklogApiClient.getUserOperations().getUserIcon(id)
.flatMap(new Func1<ResponseBody, Observable<BacklogImage>>() {
@Override
public Observable<BacklogImage> call(ResponseBody response) {
final String subtype = response.contentType().subtype();
final byte[] bytes;
try {
bytes = response.bytes();
} catch (IOException ex) {
Log.e(LOG_TAG, "Error on reading image", ex);
return null;
}
return Observable.just(new BacklogImage(id + "." + subtype, bytes));
}
})
.onErrorReturn(new Func1<Throwable, BacklogImage>() {
@Override
public BacklogImage call(Throwable throwable) {
Log.e(LOG_TAG, "Error on get Project Icon", throwable);
return null;
}
})
.toBlocking()
.first();
}
}
|
scarrupt/Capstone-Project
|
app/src/main/java/com/codefactoring/android/backlogtracker/sync/fetchers/UserDataFetcher.java
|
Java
|
apache-2.0
| 3,378 |
/*
* Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.autoscaling.model.transform;
import org.w3c.dom.Node;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.util.XpathUtils;
import com.amazonaws.transform.StandardErrorUnmarshaller;
import com.amazonaws.services.autoscaling.model.LimitExceededException;
public class LimitExceededExceptionUnmarshaller extends StandardErrorUnmarshaller {
public LimitExceededExceptionUnmarshaller() {
super(LimitExceededException.class);
}
public AmazonServiceException unmarshall(Node node) throws Exception {
// Bail out if this isn't the right error code that this
// marshaller understands.
String errorCode = parseErrorCode(node);
if (errorCode == null || !errorCode.equals("LimitExceeded"))
return null;
LimitExceededException e = (LimitExceededException)super.unmarshall(node);
return e;
}
}
|
apetresc/aws-sdk-for-java-on-gae
|
src/main/java/com/amazonaws/services/autoscaling/model/transform/LimitExceededExceptionUnmarshaller.java
|
Java
|
apache-2.0
| 1,518 |
package edu.kit.ipd.sdq.kamp.ruledsl.runtime.rule;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
import edu.kit.ipd.sdq.kamp.architecture.AbstractArchitectureVersion;
import edu.kit.ipd.sdq.kamp.propagation.AbstractChangePropagationAnalysis;
import edu.kit.ipd.sdq.kamp.ruledsl.support.ChangePropagationStepRegistry;
import edu.kit.ipd.sdq.kamp.ruledsl.support.IRule;
/**
* This standard (helper) rule is used to measure the time of a given rule.
*
* @author Martin Löper
*
*/
public class StopwatchRule implements IRule {
private final Stopwatch stopwatch;
private final IRule rule;
private final long iterations;
/**
* Creates a Stopwatch (wrapper) rule for the given {@code rule}.
* @param rule the rule which will be observed
*/
public StopwatchRule(IRule rule) {
this(rule, 1);
}
/**
* Creates a Stopwatch (wrapper) rule for the given {@code rule}.
* @param rule the rule which will be observed
* @param iterations the number of times the {@link IRule#apply(AbstractArchitectureVersion, ChangePropagationStepRegistry, AbstractChangePropagationAnalysis)} method of {@code rule} is called
*/
public StopwatchRule(IRule rule, long iterations) {
this.stopwatch = Stopwatch.createUnstarted();
this.rule = rule;
this.iterations = iterations;
}
@Override
public void apply(AbstractArchitectureVersion version, ChangePropagationStepRegistry registry) {
this.stopwatch.start();
for(long i=0; i < this.iterations; i++) {
this.rule.apply(version, registry);
}
this.stopwatch.stop();
}
/**
* Returns the elapsed time in the given time format.
* @see Stopwatch#elapsed(TimeUnit)
* @param timeUnit the time unit which is used to express the elapsed time
* @return the elapsed time in the given time unit
*/
public long getElapsedTime(TimeUnit timeUnit) {
return this.stopwatch.elapsed(timeUnit);
}
/**
* Returns the elapsed time per iteration in the given time format.
* This essentially divides the total time by the number of iterations.
* @param timeUnit timeUnit the time unit which is used to express the elapsed time
* @return the elapsed time per iteration in the given time unit
*/
public long getElapsedTimePerIteration(TimeUnit timeUnit) {
return this.stopwatch.elapsed(timeUnit) / this.iterations;
}
/**
* Returns the elapsed time in a human readable format.
* @see Stopwatch#toString()
* @return the elapsed time (human readable)
*/
public String getElapsedTimeAsString() {
return this.stopwatch.toString();
}
}
|
MartinLoeper/KAMP-DSL
|
edu.kit.ipd.sdq.kamp.ruledsl/src/edu/kit/ipd/sdq/kamp/ruledsl/runtime/rule/StopwatchRule.java
|
Java
|
apache-2.0
| 2,567 |
var when = require('when');
var request = require('request');
var settings = require("../../../../settings");
var log = require("../../../log");
// view components
var view_start = require('../nodes/view/start');
var view_choice = require('../nodes/view/choice');
var view_form = require('../nodes/view/form');
var view_grid = require('../nodes/view/grid');
var view_info = require('../nodes/view/info');
var view_url = require('../nodes/view/url');
var view_zendesk_ticket = require('../nodes/view/zendesk-ticket');
var submit_call = require('../nodes/view/call');
var zopim_chat = require('../nodes/view/zopim_chat');
// action components
var action_submit_email = require('../nodes/action/submit-email');
var action_submit_zendesk_ticket = require('../nodes/action/submit-zendesk-ticket');
var PLIST_DEPLOY = settings.staticPlistSubmittingService;
var PLIST_HOST = settings.staticPlistHostingUrl || "https://designer.ubicall.com/plist/";
if (!PLIST_DEPLOY) {
throw new Error("ws.ubicall.com is abslote use new configuration i.e. config_version=20150920")
}
function extractFlow(flow) {
return when.promise(function(resolve, reject) {
// initialize flow with content of start node
var __flow = view_start.createStart(flow);
for (var i = 0; i < flow.Nodes.length; i++) {
var node = flow.Nodes[i];
switch (node.type) {
case "view-choice":
__flow[node.id] = view_choice.createChoice(node);
break;
case "view-form":
__flow[node.id] = view_form.createForm(node);
break;
case "view-grid":
__flow[node.id] = view_grid.createGrid(node);
break;
case "view-info":
__flow[node.id] = view_info.createInfo(node);
break;
case "view-url":
__flow[node.id] = view_url.createURL(node);
break;
case "view-zendesk-ticket-form":
__flow[node.id] = view_zendesk_ticket.createZendeskForm(node);
break;
case "view-submit-call":
__flow[node.id] = submit_call.createViewCall(node);
break;
case "view-zopim-chat":
__flow[node.id] = zopim_chat.createZopimChat(node);
break;
// action components
case "action-submit-email":
__flow[node.id] = action_submit_email.createActionEmail(node);
break;
case "action-submit-zendesk-ticket":
__flow[node.id] = action_submit_zendesk_ticket.createActionZendeskTicket(node);
break;
// do nothing nodes
case "view-zendesk-help-center":
break;
case "tab":
break;
default:
if (node.type !== "start") { // it aleardy handle outside switch statment
log.info("unknown node " + JSON.stringify(node));
}
}
}
return resolve(__flow);
});
}
function deployFlowOnline(authorization_header, version) {
return when.promise(function(resolve, reject) {
var options = {
url: PLIST_DEPLOY + version,
method: 'POST'
};
if (authorization_header) {
options.headers = options.headers || {};
options.headers['Authorization'] = authorization_header;
}
if (process.env.node_env !== "production") {
log.warn("This info appear because you are not start with production flag");
log.warn(JSON.stringify(options, null, 4));
}
request(options, function(err, response, body) {
if (err || response.statusCode !== 200) {
log.error(err || response.statusCode);
return reject(err || response.statusCode);
} else {
return resolve(body);
}
});
});
}
module.exports = {
extractFlow: extractFlow,
deployFlowOnline: deployFlowOnline
}
|
Ubicall/node-red
|
red/ubicall/plist/utils/index.js
|
JavaScript
|
apache-2.0
| 3,754 |
/**
* @license
* Copyright 2012 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview JavaScript for Blockly's Code demo.
* @author fraser@google.com (Neil Fraser)
*/
'use strict';
/**
* Create a namespace for the application.
*/
var Code = {};
/**
* Lookup for names of supported languages. Keys should be in ISO 639 format.
*/
Code.LANGUAGE_NAME = {
'ar': 'العربية',
'be-tarask': 'Taraškievica',
'br': 'Brezhoneg',
'ca': 'Català',
'cs': 'Česky',
'da': 'Dansk',
'de': 'Deutsch',
'el': 'Ελληνικά',
'en': 'English',
'es': 'Español',
'et': 'Eesti',
'fa': 'فارسی',
'fr': 'Français',
'he': 'עברית',
'hrx': 'Hunsrik',
'hu': 'Magyar',
'ia': 'Interlingua',
'is': 'Íslenska',
'it': 'Italiano',
'ja': '日本語',
'kab': 'Kabyle',
'ko': '한국어',
'mk': 'Македонски',
'ms': 'Bahasa Melayu',
'nb': 'Norsk Bokmål',
'nl': 'Nederlands, Vlaams',
'oc': 'Lenga d\'òc',
'pl': 'Polski',
'pms': 'Piemontèis',
'pt-br': 'Português Brasileiro',
'ro': 'Română',
'ru': 'Русский',
'sc': 'Sardu',
'sk': 'Slovenčina',
'sr': 'Српски',
'sv': 'Svenska',
'ta': 'தமிழ்',
'th': 'ภาษาไทย',
'tlh': 'tlhIngan Hol',
'tr': 'Türkçe',
'uk': 'Українська',
'vi': 'Tiếng Việt',
'zh-hans': '简体中文',
'zh-hant': '正體中文'
};
/**
* List of RTL languages.
*/
Code.LANGUAGE_RTL = ['ar', 'fa', 'he', 'lki'];
/**
* Blockly's main workspace.
* @type {Blockly.WorkspaceSvg}
*/
Code.workspace = null;
/**
* Extracts a parameter from the URL.
* If the parameter is absent default_value is returned.
* @param {string} name The name of the parameter.
* @param {string} defaultValue Value to return if parameter not found.
* @return {string} The parameter value or the default value if not found.
*/
Code.getStringParamFromUrl = function(name, defaultValue) {
var val = location.search.match(new RegExp('[?&]' + name + '=([^&]+)'));
return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue;
};
/**
* Get the language of this user from the URL.
* @return {string} User's language.
*/
Code.getLang = function() {
var lang = Code.getStringParamFromUrl('lang', '');
if (Code.LANGUAGE_NAME[lang] === undefined) {
// Default to English.
lang = 'en';
}
return lang;
};
/**
* Is the current language (Code.LANG) an RTL language?
* @return {boolean} True if RTL, false if LTR.
*/
Code.isRtl = function() {
return Code.LANGUAGE_RTL.indexOf(Code.LANG) != -1;
};
/**
* Load blocks saved on App Engine Storage or in session/local storage.
* @param {string} defaultXml Text representation of default blocks.
*/
Code.loadBlocks = function(defaultXml) {
try {
var loadOnce = window.sessionStorage.loadOnceBlocks;
} catch(e) {
// Firefox sometimes throws a SecurityError when accessing sessionStorage.
// Restarting Firefox fixes this, so it looks like a bug.
var loadOnce = null;
}
if ('BlocklyStorage' in window && window.location.hash.length > 1) {
// An href with #key trigers an AJAX call to retrieve saved blocks.
BlocklyStorage.retrieveXml(window.location.hash.substring(1));
} else if (loadOnce) {
// Language switching stores the blocks during the reload.
delete window.sessionStorage.loadOnceBlocks;
var xml = Blockly.Xml.textToDom(loadOnce);
Blockly.Xml.domToWorkspace(xml, Code.workspace);
} else if (defaultXml) {
// Load the editor with default starting blocks.
var xml = Blockly.Xml.textToDom(defaultXml);
Blockly.Xml.domToWorkspace(xml, Code.workspace);
} else if ('BlocklyStorage' in window) {
// Restore saved blocks in a separate thread so that subsequent
// initialization is not affected from a failed load.
window.setTimeout(BlocklyStorage.restoreBlocks, 0);
}
};
/**
* Save the blocks and reload with a different language.
*/
Code.changeLanguage = function() {
// Store the blocks for the duration of the reload.
// MSIE 11 does not support sessionStorage on file:// URLs.
if (window.sessionStorage) {
var xml = Blockly.Xml.workspaceToDom(Code.workspace);
var text = Blockly.Xml.domToText(xml);
window.sessionStorage.loadOnceBlocks = text;
}
var languageMenu = document.getElementById('languageMenu');
var newLang = encodeURIComponent(
languageMenu.options[languageMenu.selectedIndex].value);
var search = window.location.search;
if (search.length <= 1) {
search = '?lang=' + newLang;
} else if (search.match(/[?&]lang=[^&]*/)) {
search = search.replace(/([?&]lang=)[^&]*/, '$1' + newLang);
} else {
search = search.replace(/\?/, '?lang=' + newLang + '&');
}
window.location = window.location.protocol + '//' +
window.location.host + window.location.pathname + search;
};
/**
* Bind a function to a button's click event.
* On touch enabled browsers, ontouchend is treated as equivalent to onclick.
* @param {!Element|string} el Button element or ID thereof.
* @param {!Function} func Event handler to bind.
*/
Code.bindClick = function(el, func) {
if (typeof el == 'string') {
el = document.getElementById(el);
}
el.addEventListener('click', func, true);
el.addEventListener('touchend', func, true);
};
/**
* Load the Prettify CSS and JavaScript.
*/
Code.importPrettify = function() {
var script = document.createElement('script');
script.setAttribute('src', 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js');
document.head.appendChild(script);
};
/**
* Compute the absolute coordinates and dimensions of an HTML element.
* @param {!Element} element Element to match.
* @return {!Object} Contains height, width, x, and y properties.
* @private
*/
Code.getBBox_ = function(element) {
var height = element.offsetHeight;
var width = element.offsetWidth;
var x = 0;
var y = 0;
do {
x += element.offsetLeft;
y += element.offsetTop;
element = element.offsetParent;
} while (element);
return {
height: height,
width: width,
x: x,
y: y
};
};
/**
* User's language (e.g. "en").
* @type {string}
*/
Code.LANG = Code.getLang();
/**
* List of tab names.
* @private
*/
Code.TABS_ = ['blocks', 'javascript', 'php', 'python', 'dart', 'lua', 'xml'];
Code.selected = 'blocks';
/**
* Switch the visible pane when a tab is clicked.
* @param {string} clickedName Name of tab clicked.
*/
Code.tabClick = function(clickedName) {
// If the XML tab was open, save and render the content.
if (document.getElementById('tab_xml').className == 'tabon') {
var xmlTextarea = document.getElementById('content_xml');
var xmlText = xmlTextarea.value;
var xmlDom = null;
try {
xmlDom = Blockly.Xml.textToDom(xmlText);
} catch (e) {
var q =
window.confirm(MSG['badXml'].replace('%1', e));
if (!q) {
// Leave the user on the XML tab.
return;
}
}
if (xmlDom) {
Code.workspace.clear();
Blockly.Xml.domToWorkspace(xmlDom, Code.workspace);
}
}
if (document.getElementById('tab_blocks').className == 'tabon') {
Code.workspace.setVisible(false);
}
// Deselect all tabs and hide all panes.
for (var i = 0; i < Code.TABS_.length; i++) {
var name = Code.TABS_[i];
document.getElementById('tab_' + name).className = 'taboff';
document.getElementById('content_' + name).style.visibility = 'hidden';
}
// Select the active tab.
Code.selected = clickedName;
document.getElementById('tab_' + clickedName).className = 'tabon';
// Show the selected pane.
document.getElementById('content_' + clickedName).style.visibility =
'visible';
Code.renderContent();
if (clickedName == 'blocks') {
Code.workspace.setVisible(true);
}
Blockly.svgResize(Code.workspace);
};
/**
* Populate the currently selected pane with content generated from the blocks.
*/
Code.renderContent = function() {
var content = document.getElementById('content_' + Code.selected);
// Initialize the pane.
if (content.id == 'content_xml') {
var xmlTextarea = document.getElementById('content_xml');
var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace);
var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
xmlTextarea.value = xmlText;
xmlTextarea.focus();
} else if (content.id == 'content_javascript') {
Code.attemptCodeGeneration(Blockly.JavaScript);
} else if (content.id == 'content_python') {
Code.attemptCodeGeneration(Blockly.Python);
} else if (content.id == 'content_php') {
Code.attemptCodeGeneration(Blockly.PHP);
} else if (content.id == 'content_dart') {
Code.attemptCodeGeneration(Blockly.Dart);
} else if (content.id == 'content_lua') {
Code.attemptCodeGeneration(Blockly.Lua);
}
if (typeof PR == 'object') {
PR.prettyPrint();
}
};
/**
* Attempt to generate the code and display it in the UI, pretty printed.
* @param generator {!Blockly.Generator} The generator to use.
*/
Code.attemptCodeGeneration = function(generator) {
var content = document.getElementById('content_' + Code.selected);
content.textContent = '';
if (Code.checkAllGeneratorFunctionsDefined(generator)) {
var code = generator.workspaceToCode(Code.workspace);
content.textContent = code;
// Remove the 'prettyprinted' class, so that Prettify will recalculate.
content.className = content.className.replace('prettyprinted', '');
}
};
/**
* Check whether all blocks in use have generator functions.
* @param generator {!Blockly.Generator} The generator to use.
*/
Code.checkAllGeneratorFunctionsDefined = function(generator) {
var blocks = Code.workspace.getAllBlocks(false);
var missingBlockGenerators = [];
for (var i = 0; i < blocks.length; i++) {
var blockType = blocks[i].type;
if (!generator[blockType]) {
if (missingBlockGenerators.indexOf(blockType) == -1) {
missingBlockGenerators.push(blockType);
}
}
}
var valid = missingBlockGenerators.length == 0;
if (!valid) {
var msg = 'The generator code for the following blocks not specified for ' +
generator.name_ + ':\n - ' + missingBlockGenerators.join('\n - ');
Blockly.alert(msg); // Assuming synchronous. No callback.
}
return valid;
};
/**
* Initialize Blockly. Called on page load.
*/
Code.init = function() {
Code.initLanguage();
var rtl = Code.isRtl();
var container = document.getElementById('content_area');
var onresize = function(e) {
var bBox = Code.getBBox_(container);
for (var i = 0; i < Code.TABS_.length; i++) {
var el = document.getElementById('content_' + Code.TABS_[i]);
el.style.top = bBox.y + 'px';
el.style.left = bBox.x + 'px';
// Height and width need to be set, read back, then set again to
// compensate for scrollbars.
el.style.height = bBox.height + 'px';
el.style.height = (2 * bBox.height - el.offsetHeight) + 'px';
el.style.width = bBox.width + 'px';
el.style.width = (2 * bBox.width - el.offsetWidth) + 'px';
}
// Make the 'Blocks' tab line up with the toolbox.
if (Code.workspace && Code.workspace.toolbox_.width) {
document.getElementById('tab_blocks').style.minWidth =
(Code.workspace.toolbox_.width - 38) + 'px';
// Account for the 19 pixel margin and on each side.
}
};
window.addEventListener('resize', onresize, false);
// The toolbox XML specifies each category name using Blockly's messaging
// format (eg. `<category name="%{BKY_CATLOGIC}">`).
// These message keys need to be defined in `Blockly.Msg` in order to
// be decoded by the library. Therefore, we'll use the `MSG` dictionary that's
// been defined for each language to import each category name message
// into `Blockly.Msg`.
// TODO: Clean up the message files so this is done explicitly instead of
// through this for-loop.
for (var messageKey in MSG) {
if (messageKey.indexOf('cat') == 0) {
Blockly.Msg[messageKey.toUpperCase()] = MSG[messageKey];
}
}
// Construct the toolbox XML, replacing translated variable names.
var toolboxText = document.getElementById('toolbox').outerHTML;
toolboxText = toolboxText.replace(/(^|[^%]){(\w+)}/g,
function(m, p1, p2) {return p1 + MSG[p2];});
var toolboxXml = Blockly.Xml.textToDom(toolboxText);
Code.workspace = Blockly.inject('content_blocks',
{grid:
{spacing: 25,
length: 3,
colour: '#ccc',
snap: true},
media: '../../media/',
rtl: rtl,
toolbox: toolboxXml,
zoom:
{controls: true,
wheel: true}
});
// Add to reserved word list: Local variables in execution environment (runJS)
// and the infinite loop detection function.
Blockly.JavaScript.addReservedWords('code,timeouts,checkTimeout');
Code.loadBlocks('');
if ('BlocklyStorage' in window) {
// Hook a save function onto unload.
BlocklyStorage.backupOnUnload(Code.workspace);
}
Code.tabClick(Code.selected);
Code.bindClick('trashButton',
function() {Code.discard(); Code.renderContent();});
Code.bindClick('runButton', Code.runJS);
// Disable the link button if page isn't backed by App Engine storage.
var linkButton = document.getElementById('linkButton');
if ('BlocklyStorage' in window) {
BlocklyStorage['HTTPREQUEST_ERROR'] = MSG['httpRequestError'];
BlocklyStorage['LINK_ALERT'] = MSG['linkAlert'];
BlocklyStorage['HASH_ERROR'] = MSG['hashError'];
BlocklyStorage['XML_ERROR'] = MSG['xmlError'];
Code.bindClick(linkButton,
function() {BlocklyStorage.link(Code.workspace);});
} else if (linkButton) {
linkButton.className = 'disabled';
}
for (var i = 0; i < Code.TABS_.length; i++) {
var name = Code.TABS_[i];
Code.bindClick('tab_' + name,
function(name_) {return function() {Code.tabClick(name_);};}(name));
}
onresize();
Blockly.svgResize(Code.workspace);
// Lazy-load the syntax-highlighting.
window.setTimeout(Code.importPrettify, 1);
};
/**
* Initialize the page language.
*/
Code.initLanguage = function() {
// Set the HTML's language and direction.
var rtl = Code.isRtl();
document.dir = rtl ? 'rtl' : 'ltr';
document.head.parentElement.setAttribute('lang', Code.LANG);
// Sort languages alphabetically.
var languages = [];
for (var lang in Code.LANGUAGE_NAME) {
languages.push([Code.LANGUAGE_NAME[lang], lang]);
}
var comp = function(a, b) {
// Sort based on first argument ('English', 'Русский', '简体字', etc).
if (a[0] > b[0]) return 1;
if (a[0] < b[0]) return -1;
return 0;
};
languages.sort(comp);
// Populate the language selection menu.
var languageMenu = document.getElementById('languageMenu');
languageMenu.options.length = 0;
for (var i = 0; i < languages.length; i++) {
var tuple = languages[i];
var lang = tuple[tuple.length - 1];
var option = new Option(tuple[0], lang);
if (lang == Code.LANG) {
option.selected = true;
}
languageMenu.options.add(option);
}
languageMenu.addEventListener('change', Code.changeLanguage, true);
// Inject language strings.
document.title += ' ' + MSG['title'];
document.getElementById('title').textContent = MSG['title'];
document.getElementById('tab_blocks').textContent = MSG['blocks'];
document.getElementById('linkButton').title = MSG['linkTooltip'];
document.getElementById('runButton').title = MSG['runTooltip'];
document.getElementById('trashButton').title = MSG['trashTooltip'];
};
/**
* Execute the user's code.
* Just a quick and dirty eval. Catch infinite loops.
*/
Code.runJS = function() {
Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n';
var timeouts = 0;
var checkTimeout = function() {
if (timeouts++ > 1000000) {
throw MSG['timeout'];
}
};
var code = Blockly.JavaScript.workspaceToCode(Code.workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(MSG['badCode'].replace('%1', e));
}
};
/**
* Discard all blocks from the workspace.
*/
Code.discard = function() {
var count = Code.workspace.getAllBlocks(false).length;
if (count < 2 ||
window.confirm(Blockly.Msg['DELETE_ALL_BLOCKS'].replace('%1', count))) {
Code.workspace.clear();
if (window.location.hash) {
window.location.hash = '';
}
}
};
// Load the Code demo's language strings.
document.write('<script src="msg/' + Code.LANG + '.js"></script>\n');
// Load Blockly's language strings.
document.write('<script src="../../msg/js/' + Code.LANG + '.js"></script>\n');
window.addEventListener('load', Code.init);
|
picklesrus/blockly
|
demos/code/code.js
|
JavaScript
|
apache-2.0
| 17,281 |
package com.bookify.web.models;
import com.bookify.core.Bill;
import com.bookify.core.BillItem;
import java.util.ArrayList;
/**
* Created by idumancic on 11/07/2017.
*/
public class PaymentViewModel {
private Bill bill;
private String username;
private ArrayList<ItemViewModel> billItems;
private String paymentMethod;
private int totalCost;
public Bill getBill() {
return bill;
}
public void setBill(Bill bill) {
this.bill = bill;
}
public ArrayList<ItemViewModel> getBillItems() {
return billItems;
}
public void setBillItems(ArrayList<ItemViewModel> billItems) {
this.billItems = billItems;
}
public String getPaymentMethod() {
return paymentMethod;
}
public void setPaymentMethod(String paymentMethod) {
this.paymentMethod = paymentMethod;
}
public int getTotalCost() {
return totalCost;
}
public void setTotalCost(int totalCost) {
this.totalCost = totalCost;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
|
idumancic/bookify
|
web/src/main/java/com/bookify/web/models/PaymentViewModel.java
|
Java
|
apache-2.0
| 1,184 |
/*
* Copyright 2018 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.netflix.spinnaker.halyard.cli.command.v1.config.deploy.ha;
import com.beust.jcommander.Parameters;
import com.netflix.spinnaker.halyard.cli.command.v1.NestableCommand;
import com.netflix.spinnaker.halyard.cli.services.v1.Daemon;
import com.netflix.spinnaker.halyard.cli.services.v1.OperationHandler;
import java.util.HashMap;
import java.util.Map;
import lombok.AccessLevel;
import lombok.Getter;
@Parameters(separators = "=")
public abstract class AbstractHaServiceEnableDisableCommand extends AbstractHaServiceCommand {
@Override
public String getCommandName() {
return isEnable() ? "enable" : "disable";
}
private String subjunctivePerfectAction() {
return isEnable() ? "enabled" : "disabled";
}
private String indicativePastPerfectAction() {
return isEnable() ? "enabled" : "disabled";
}
protected abstract boolean isEnable();
@Getter(AccessLevel.PROTECTED)
private Map<String, NestableCommand> subcommands = new HashMap<>();
@Override
public String getShortDescription() {
return "Set the "
+ getServiceName()
+ " high availability service as "
+ subjunctivePerfectAction();
}
@Override
protected void executeThis() {
String currentDeployment = getCurrentDeployment();
String serviceName = getServiceName();
boolean enable = isEnable();
new OperationHandler<Void>()
.setSuccessMessage("Successfully " + indicativePastPerfectAction() + " " + serviceName)
.setFailureMesssage("Failed to " + getCommandName() + " " + serviceName)
.setOperation(
Daemon.setHaServiceEnableDisable(currentDeployment, serviceName, !noValidate, enable))
.get();
}
}
|
spinnaker/halyard
|
halyard-cli/src/main/java/com/netflix/spinnaker/halyard/cli/command/v1/config/deploy/ha/AbstractHaServiceEnableDisableCommand.java
|
Java
|
apache-2.0
| 2,298 |
/*
* Copyright (c) 2016 GitHub, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "catch.hpp"
#include "usdt.h"
#include "api/BPF.h"
/* required to insert USDT probes on this very executable --
* we're gonna be testing them live! */
#include "folly/tracing/StaticTracepoint.h"
static int a_probed_function() {
int an_int = 23 + getpid();
void *a_pointer = malloc(4);
FOLLY_SDT(libbcc_test, sample_probe_1, an_int, a_pointer);
free(a_pointer);
return an_int;
}
extern "C" int lib_probed_function();
int call_shared_lib_func() {
return lib_probed_function();
}
TEST_CASE("test finding a probe in our own process", "[usdt]") {
USDT::Context ctx(getpid());
REQUIRE(ctx.num_probes() >= 1);
SECTION("our test probe") {
auto probe = ctx.get("sample_probe_1");
REQUIRE(probe);
if(probe->in_shared_object(probe->bin_path()))
return;
REQUIRE(probe->name() == "sample_probe_1");
REQUIRE(probe->provider() == "libbcc_test");
REQUIRE(probe->bin_path().find("/test_libbcc") != std::string::npos);
REQUIRE(probe->num_locations() == 1);
REQUIRE(probe->num_arguments() == 2);
REQUIRE(probe->need_enable() == false);
REQUIRE(a_probed_function() != 0);
}
}
TEST_CASE("test probe's attributes with C++ API", "[usdt]") {
const ebpf::USDT u("/proc/self/exe", "libbcc_test", "sample_probe_1", "on_event");
REQUIRE(u.binary_path() == "/proc/self/exe");
REQUIRE(u.pid() == -1);
REQUIRE(u.provider() == "libbcc_test");
REQUIRE(u.name() == "sample_probe_1");
REQUIRE(u.probe_func() == "on_event");
}
TEST_CASE("test fine a probe in our own binary with C++ API", "[usdt]") {
ebpf::BPF bpf;
ebpf::USDT u("/proc/self/exe", "libbcc_test", "sample_probe_1", "on_event");
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.code() == 0);
res = bpf.attach_usdt(u);
REQUIRE(res.code() == 0);
res = bpf.detach_usdt(u);
REQUIRE(res.code() == 0);
}
TEST_CASE("test fine probes in our own binary with C++ API", "[usdt]") {
ebpf::BPF bpf;
ebpf::USDT u("/proc/self/exe", "libbcc_test", "sample_probe_1", "on_event");
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.ok());
res = bpf.attach_usdt_all();
REQUIRE(res.ok());
res = bpf.detach_usdt_all();
REQUIRE(res.ok());
}
TEST_CASE("test fine a probe in our Process with C++ API", "[usdt]") {
ebpf::BPF bpf;
ebpf::USDT u(::getpid(), "libbcc_test", "sample_probe_1", "on_event");
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.code() == 0);
res = bpf.attach_usdt(u);
REQUIRE(res.code() == 0);
res = bpf.detach_usdt(u);
REQUIRE(res.code() == 0);
}
TEST_CASE("test find a probe in our process' shared libs with c++ API", "[usdt]") {
ebpf::BPF bpf;
ebpf::USDT u(::getpid(), "libbcc_test", "sample_lib_probe_1", "on_event");
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.msg() == "");
REQUIRE(res.code() == 0);
}
TEST_CASE("test usdt partial init w/ fail init_usdt", "[usdt]") {
ebpf::BPF bpf;
ebpf::USDT u(::getpid(), "libbcc_test", "sample_lib_probe_nonexistent", "on_event");
ebpf::USDT p(::getpid(), "libbcc_test", "sample_lib_probe_1", "on_event");
// We should be able to fail initialization and subsequently do bpf.init w/o USDT
// successfully
auto res = bpf.init_usdt(u);
REQUIRE(res.msg() != "");
REQUIRE(res.code() != 0);
// Shouldn't be necessary to re-init bpf object either after failure to init w/
// bad USDT
res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.msg() != "");
REQUIRE(res.code() != 0);
res = bpf.init_usdt(p);
REQUIRE(res.msg() == "");
REQUIRE(res.code() == 0);
res = bpf.init("int on_event() { return 0; }", {}, {});
REQUIRE(res.msg() == "");
REQUIRE(res.code() == 0);
}
class ChildProcess {
pid_t pid_;
public:
ChildProcess(const char *name, char *const argv[]) {
pid_ = fork();
if (pid_ == 0) {
execvp(name, argv);
exit(0);
}
if (spawned()) {
usleep(250000);
if (kill(pid_, 0) < 0)
pid_ = -1;
}
}
~ChildProcess() {
if (spawned()) {
int status;
kill(pid_, SIGKILL);
if (waitpid(pid_, &status, 0) != pid_)
abort();
}
}
bool spawned() const { return pid_ > 0; }
pid_t pid() const { return pid_; }
};
extern int cmd_scanf(const char *cmd, const char *fmt, ...);
static int probe_num_locations(const char *bin_path, const char *func_name) {
int num_locations;
char cmd[512];
const char *cmdfmt = "readelf -n %s | grep -c \"Name: %s$\"";
sprintf(cmd, cmdfmt, bin_path, func_name);
if (cmd_scanf(cmd, "%d", &num_locations) != 0) {
return -1;
}
return num_locations;
}
static int probe_num_arguments(const char *bin_path, const char *func_name) {
int num_arguments;
char cmd[512];
const char *cmdfmt = "readelf -n %s | grep -m 1 -A 2 \" %s$\" | " \
"tail -1 | cut -d \" \" -f 6- | wc -w";
sprintf(cmd, cmdfmt, bin_path, func_name);
if (cmd_scanf(cmd, "%d", &num_arguments) != 0) {
return -1;
}
return num_arguments;
}
// Unsharing pid namespace requires forking
// this uses pgrep to find the child process, by searching for a process
// that has the unshare as its parent
static int unshared_child_pid(const int ppid) {
int child_pid;
char cmd[512];
const char *cmdfmt = "pgrep -P %d";
sprintf(cmd, cmdfmt, ppid);
if (cmd_scanf(cmd, "%d", &child_pid) != 0) {
return -1;
}
return child_pid;
}
// FIXME This seems like a legitimate bug with probing ruby where the
// ruby symbols are in libruby.so?
TEST_CASE("test listing all USDT probes in Ruby/MRI", "[usdt][!mayfail]") {
size_t mri_probe_count = 0;
SECTION("without a running Ruby process") {
USDT::Context ctx("ruby");
if (!ctx.loaded())
return;
REQUIRE(ctx.num_probes() > 10);
mri_probe_count = ctx.num_probes();
SECTION("GC static probe") {
auto name = "gc__mark__begin";
auto probe = ctx.get(name);
REQUIRE(probe);
REQUIRE(probe->in_shared_object(probe->bin_path()) == true);
REQUIRE(probe->name() == name);
REQUIRE(probe->provider() == "ruby");
auto bin_path = probe->bin_path();
bool bin_path_match =
(bin_path.find("/ruby") != std::string::npos) ||
(bin_path.find("/libruby") != std::string::npos);
REQUIRE(bin_path_match);
int exp_locations, exp_arguments;
exp_locations = probe_num_locations(bin_path.c_str(), name);
exp_arguments = probe_num_arguments(bin_path.c_str(), name);
REQUIRE(probe->num_locations() == exp_locations);
REQUIRE(probe->num_arguments() == exp_arguments);
REQUIRE(probe->need_enable() == true);
}
SECTION("object creation probe") {
auto name = "object__create";
auto probe = ctx.get(name);
REQUIRE(probe);
REQUIRE(probe->in_shared_object(probe->bin_path()) == true);
REQUIRE(probe->name() == name);
REQUIRE(probe->provider() == "ruby");
auto bin_path = probe->bin_path();
bool bin_path_match =
(bin_path.find("/ruby") != std::string::npos) ||
(bin_path.find("/libruby") != std::string::npos);
REQUIRE(bin_path_match);
int exp_locations, exp_arguments;
exp_locations = probe_num_locations(bin_path.c_str(), name);
exp_arguments = probe_num_arguments(bin_path.c_str(), name);
REQUIRE(probe->num_locations() == exp_locations);
REQUIRE(probe->num_arguments() == exp_arguments);
REQUIRE(probe->need_enable() == true);
}
SECTION("array creation probe") {
auto name = "array__create";
auto probe = ctx.get(name);
REQUIRE(probe);
REQUIRE(probe->name() == name);
auto bin_path = probe->bin_path().c_str();
int exp_locations, exp_arguments;
exp_locations = probe_num_locations(bin_path, name);
exp_arguments = probe_num_arguments(bin_path, name);
REQUIRE(probe->num_locations() == exp_locations);
REQUIRE(probe->num_arguments() == exp_arguments);
REQUIRE(probe->need_enable() == true);
}
}
SECTION("with a running Ruby process") {
static char _ruby[] = "ruby";
char *const argv[2] = {_ruby, NULL};
ChildProcess ruby(argv[0], argv);
if (!ruby.spawned())
return;
USDT::Context ctx(ruby.pid());
REQUIRE(ctx.num_probes() >= mri_probe_count);
SECTION("get probe in running process") {
auto name = "gc__mark__begin";
auto probe = ctx.get(name);
REQUIRE(probe);
REQUIRE(probe->in_shared_object(probe->bin_path()) == true);
REQUIRE(probe->name() == name);
REQUIRE(probe->provider() == "ruby");
auto bin_path = probe->bin_path();
bool bin_path_match =
(bin_path.find("/ruby") != std::string::npos) ||
(bin_path.find("/libruby") != std::string::npos);
REQUIRE(bin_path_match);
int exp_locations, exp_arguments;
exp_locations = probe_num_locations(bin_path.c_str(), name);
exp_arguments = probe_num_arguments(bin_path.c_str(), name);
REQUIRE(probe->num_locations() == exp_locations);
REQUIRE(probe->num_arguments() == exp_arguments);
REQUIRE(probe->need_enable() == true);
}
}
}
// These tests are expected to fail if there is no Ruby with dtrace probes
TEST_CASE("test probing running Ruby process in namespaces",
"[usdt][!mayfail]") {
SECTION("in separate mount namespace") {
static char _unshare[] = "unshare";
const char *const argv[4] = {_unshare, "--mount", "ruby", NULL};
ChildProcess unshare(argv[0], (char **const)argv);
if (!unshare.spawned())
return;
int ruby_pid = unshare.pid();
ebpf::BPF bpf;
ebpf::USDT u(ruby_pid, "ruby", "gc__mark__begin", "on_event");
u.set_probe_matching_kludge(1); // Also required for overlayfs...
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.msg() == "");
REQUIRE(res.code() == 0);
res = bpf.attach_usdt(u, ruby_pid);
REQUIRE(res.code() == 0);
res = bpf.detach_usdt(u, ruby_pid);
REQUIRE(res.code() == 0);
}
SECTION("in separate mount namespace and separate PID namespace") {
static char _unshare[] = "unshare";
const char *const argv[8] = {_unshare, "--fork", "--kill-child",
"--mount", "--pid", "--mount-proc",
"ruby", NULL};
ChildProcess unshare(argv[0], (char **const)argv);
if (!unshare.spawned())
return;
int ruby_pid = unshared_child_pid(unshare.pid());
ebpf::BPF bpf;
ebpf::USDT u(ruby_pid, "ruby", "gc__mark__begin", "on_event");
u.set_probe_matching_kludge(1); // Also required for overlayfs...
auto res = bpf.init("int on_event() { return 0; }", {}, {u});
REQUIRE(res.msg() == "");
REQUIRE(res.code() == 0);
res = bpf.attach_usdt(u, ruby_pid);
REQUIRE(res.code() == 0);
res = bpf.detach_usdt(u, ruby_pid);
REQUIRE(res.code() == 0);
struct bcc_symbol sym;
std::string pid_root= "/proc/" + std::to_string(ruby_pid) + "/root/";
std::string module = pid_root + "usr/local/bin/ruby";
REQUIRE(bcc_resolve_symname(module.c_str(), "rb_gc_mark", 0x0, ruby_pid, nullptr, &sym) == 0);
REQUIRE(std::string(sym.module).find(pid_root, 1) == std::string::npos);
}
}
|
tuxology/bcc
|
tests/cc/test_usdt_probes.cc
|
C++
|
apache-2.0
| 12,086 |
import { Component, ElementRef, NgZone, OnInit, ViewChild} from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { EventoModel } from './../../../model/evento.model';
import { TipoIngressoModel } from './../../../model/tipoingresso.model';
import { EventoService } from './../../../service/evento.service';
import * as firebase from 'firebase';
import { } from 'googlemaps';
import { MapsAPILoader } from '@agm/core';
@Component({
selector: 'app-evento-editar',
templateUrl: './evento-editar.component.html'
})
export class EventoEditarComponent implements OnInit {
imagemUrl:string;
idevento:number;
progress:string;
storageRef:any;
public dateMask = [/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/,' ',/\d/,/\d/,':',/\d/,/\d/];
@ViewChild("search")
public searchElementRef: ElementRef;
constructor(
public actroute: ActivatedRoute,
public eventoService:EventoService,
public evento:EventoModel,
public router:Router,
public mapsAPILoader: MapsAPILoader,
public ngZone: NgZone
)
{
this.storageRef = firebase.storage().ref();
}
ngOnInit() {
this.actroute.params.subscribe(
(params: any) => {
this.evento.idevento = params['id'];
this.eventoService.getEvento(this.evento)
.subscribe((evento)=>{
this.evento = evento.json().data[0];
console.log(this.evento);
this.imagemUrl = this.evento.imagem;
})
this.eventoService.getAllTipoIngressos(this.evento)
.subscribe((tipos)=>{
this.evento.tipos = tipos;
console.log(this.evento.tipos);
})
}
);
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
this.ngZone.run(() => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
console.log(autocomplete.getPlace())
//verify result
if (place.geometry === undefined || place.geometry === null) {
return;
}
//set latitude, longitude and zoom
this.evento.latitude = place.geometry.location.lat();
this.evento.longitude = place.geometry.location.lng();
});
});
});
}
uploadImagem($event){
//this.deleteImgStorage();
let files = $event.target.files || $event.srcElement.files;
let file = files[0];
let uploadTask = this.storageRef.child(file.name).put(file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot)=>{
let vlrPorcent = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
this.progress = vlrPorcent.toFixed(2);
},(error)=>{
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
},()=>{
this.imagemUrl = uploadTask.snapshot.downloadURL;
});
}
atualizarDados(evento){
this.evento.imagem = this.imagemUrl;
console.log(this.evento.data);
this.eventoService.atualizarEvento(this.evento.idevento,evento);
}
cancelar(){
this.router.navigate(['/eventos/listar']);
}
novotipo(){
this.evento.tipos.push(new TipoIngressoModel());
}
}
|
Wellington-Junior/ingressos
|
src/app/pages/evento/evento-editar/evento-editar.component.ts
|
TypeScript
|
apache-2.0
| 3,826 |
/**
* Copyright (C) 2012 Ryan W Tenney (ryan@10e.us)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ryantenney.metrics.spring.reporter;
import java.util.Map;
import java.util.regex.Pattern;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
public abstract class AbstractReporterFactoryBean<T> implements FactoryBean<T>, InitializingBean, BeanFactoryAware {
protected static final String FILTER_PATTERN = "filter";
protected static final String FILTER_REF = "filter-ref";
protected static final String PREFIX = "prefix";
protected static final String PREFIX_SUPPLIER_REF = "prefix-supplier-ref";
private MetricRegistry metricRegistry;
private BeanFactory beanFactory;
private ConversionService conversionService;
private Map<String, String> properties;
private T instance;
private boolean enabled = true;
private boolean initialized = false;
@Override
public abstract Class<? extends T> getObjectType();
@Override
public boolean isSingleton() {
return true;
}
@Override
public T getObject() {
if (!this.enabled) {
return null;
}
if (!this.initialized) {
throw new IllegalStateException("Singleton instance not initialized yet");
}
return this.instance;
}
@Override
public void afterPropertiesSet() throws Exception {
this.instance = createInstance();
this.initialized = true;
}
protected abstract T createInstance() throws Exception;
@Override
public void setBeanFactory(final BeanFactory beanFactory) {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory) {
this.conversionService = ((ConfigurableBeanFactory) beanFactory).getConversionService();
}
}
public BeanFactory getBeanFactory() {
return this.beanFactory;
}
public ConversionService getConversionService() {
if (this.conversionService == null) {
this.conversionService = new DefaultConversionService();
}
return this.conversionService;
}
public void setMetricRegistry(final MetricRegistry metricRegistry) {
this.metricRegistry = metricRegistry;
}
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isEnabled() {
return this.enabled;
}
public void setProperties(final Map<String, String> properties) {
this.properties = properties;
}
public Map<String, String> getProperties() {
return properties;
}
protected boolean hasProperty(String key) {
return getProperty(key) != null;
}
protected String getProperty(String key) {
return this.properties.get(key);
}
protected String getProperty(String key, String defaultValue) {
final String value = this.properties.get(key);
if (value == null) {
return defaultValue;
}
return value;
}
protected <V> V getProperty(String key, Class<V> requiredType) {
return getProperty(key, requiredType, null);
}
@SuppressWarnings("unchecked")
protected <V> V getProperty(String key, Class<V> requiredType, V defaultValue) {
final String value = this.properties.get(key);
if (value == null) {
return defaultValue;
}
return (V) getConversionService().convert(value, TypeDescriptor.forObject(value), TypeDescriptor.valueOf(requiredType));
}
protected Object getPropertyRef(String key) {
return getPropertyRef(key, null);
}
protected <V> V getPropertyRef(String key, Class<V> requiredType) {
final String value = this.properties.get(key);
if (value == null) {
return null;
}
return this.beanFactory.getBean(value, requiredType);
}
protected MetricFilter getMetricFilter() {
if (hasProperty(FILTER_PATTERN)) {
return metricFilterPattern(getProperty(FILTER_PATTERN));
}
else if (hasProperty(FILTER_REF)) {
return getPropertyRef(FILTER_REF, MetricFilter.class);
}
return MetricFilter.ALL;
}
protected String getPrefix() {
if (hasProperty(PREFIX)) {
return getProperty(PREFIX);
}
else if (hasProperty(PREFIX_SUPPLIER_REF)) {
return getPropertyRef(PREFIX_SUPPLIER_REF, MetricPrefixSupplier.class).getPrefix();
}
return null;
}
protected MetricFilter metricFilterPattern(String pattern) {
final Pattern filter = Pattern.compile(pattern);
return new MetricFilter() {
@Override
public boolean matches(String name, Metric metric) {
return filter.matcher(name).matches();
}
@Override
public String toString() {
return "[MetricFilter regex=" + filter.pattern() + "]";
}
};
}
}
|
ryantenney/metrics-spring
|
src/main/java/com/ryantenney/metrics/spring/reporter/AbstractReporterFactoryBean.java
|
Java
|
apache-2.0
| 5,530 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.task.app.composedtaskrunner.configuration;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.task.app.composedtaskrunner.ComposedRunnerJobFactory;
import org.springframework.cloud.task.app.composedtaskrunner.ComposedRunnerVisitor;
import org.springframework.cloud.task.app.composedtaskrunner.properties.ComposedTaskProperties;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttribute;
/**
* @author Glenn Renfro
*/
@Configuration
@EnableBatchProcessing
@EnableTask
@EnableConfigurationProperties(ComposedTaskProperties.class)
public class ComposedRunnerVisitorConfiguration {
@Autowired
private StepBuilderFactory steps;
@Autowired
private ComposedTaskProperties composedTaskProperties;
@Bean
public ComposedRunnerJobFactory job() {
return new ComposedRunnerJobFactory(this.composedTaskProperties.getGraph());
}
@Bean
public ComposedRunnerVisitor composedRunnerStack() {
return new ComposedRunnerVisitor();
}
@Bean
public Step AAA_0() {
return createTaskletStep("AAA_0");
}
@Bean
public Step AAA_1() {
return createTaskletStep("AAA_1");
}
@Bean
public Step AAA_2() {
return createTaskletStep("AAA_2");
}
@Bean
public Step BBB_0() {
return createTaskletStep("BBB_0");
}
@Bean
public Step BBB_1() {
return createTaskletStep("BBB_1");
}
@Bean
public Step CCC_0() {
return createTaskletStep("CCC_0");
}
@Bean
public Step DDD_0() {
return createTaskletStep("DDD_0");
}
@Bean
public Step EEE_0() {
return createTaskletStep("EEE_0");
}
@Bean
public Step FFF_0() {
return createTaskletStep("FFF_0");
}
@Bean
public Step LABELA() {
return createTaskletStep("LABELA");
}
@Bean
public Step failedStep_0() {
return createTaskletStepWithListener("failedStep_0",
failedStepExecutionListener());
}
@Bean
public Step successStep() {
return createTaskletStepWithListener("successStep",
successStepExecutionListener());
}
@Bean
public StepExecutionListener failedStepExecutionListener() {
return new StepExecutionListener() {
@Override
public void beforeStep(StepExecution stepExecution) {
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return ExitStatus.FAILED;
}
};
}
@Bean
public StepExecutionListener successStepExecutionListener() {
return new StepExecutionListener() {
@Override
public void beforeStep(StepExecution stepExecution) {
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return ExitStatus.COMPLETED;
}
};
}
@Bean
public TaskExecutor taskExecutor() {
return new ThreadPoolTaskExecutor();
}
private Step createTaskletStepWithListener(final String taskName,
StepExecutionListener stepExecutionListener) {
return this.steps.get(taskName)
.tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
return RepeatStatus.FINISHED;
}
})
.transactionAttribute(getTransactionAttribute())
.listener(stepExecutionListener)
.build();
}
private Step createTaskletStep(final String taskName) {
return this.steps.get(taskName)
.tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
return RepeatStatus.FINISHED;
}
})
.transactionAttribute(getTransactionAttribute())
.build();
}
/**
* Using the default transaction attribute for the job will cause the
* TaskLauncher not to see the latest state in the database but rather
* what is in its transaction. By setting isolation to READ_COMMITTED
* The task launcher can see latest state of the db. Since the changes
* to the task execution are done by the tasks.
* @return DefaultTransactionAttribute with isolation set to READ_COMMITTED.
*/
private TransactionAttribute getTransactionAttribute() {
DefaultTransactionAttribute defaultTransactionAttribute =
new DefaultTransactionAttribute();
defaultTransactionAttribute.setIsolationLevel(
Isolation.READ_COMMITTED.value());
return defaultTransactionAttribute;
}
}
|
mminella/composed-task-runner
|
spring-cloud-starter-task-composedtaskrunner/src/test/java/org/springframework/cloud/task/app/composedtaskrunner/configuration/ComposedRunnerVisitorConfiguration.java
|
Java
|
apache-2.0
| 6,001 |
#include "kernel.h"
#include "ilwisdata.h"
#include "datadefinition.h"
#include "columndefinition.h"
#include "table.h"
#include "visualattributemodel.h"
#include "mapinformationattributesetter.h"
REGISTER_PROPERTYEDITOR("mapinfopropertyeditor",MapInformationPropertySetter)
MapInformationPropertySetter::MapInformationPropertySetter(QObject *parent) :
VisualAttributeEditor("mapinfopropertyeditor",TR("Mouse over Info"),QUrl("MapinfoProperties.qml"), parent)
{
}
MapInformationPropertySetter::~MapInformationPropertySetter()
{
}
bool MapInformationPropertySetter::canUse(const IIlwisObject& obj, const QString& name ) const
{
if (!obj.isValid())
return false;
if(!hasType(obj->ilwisType(), itCOVERAGE))
return false;
return name == VisualAttributeModel::LAYER_ONLY;
}
VisualAttributeEditor *MapInformationPropertySetter::create()
{
return new MapInformationPropertySetter();
}
bool MapInformationPropertySetter::showInfo() const
{
if ( attribute()->layer())
return attribute()->layer()->showInfo();
return true;
}
void MapInformationPropertySetter::setShowInfo(bool yesno)
{
if (!attribute()->layer())
return;
attribute()->layer()->showInfo(yesno);
}
|
ridoo/IlwisCore
|
ilwiscoreui/propertyeditors/mapinformationattributesetter.cpp
|
C++
|
apache-2.0
| 1,233 |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.CodeRefactorings;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.ConvertToInterpolatedString
{
internal abstract class AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider<TInvocationExpressionSyntax, TExpressionSyntax, TArgumentSyntax, TLiteralExpressionSyntax> : CodeRefactoringProvider
where TExpressionSyntax : SyntaxNode
where TInvocationExpressionSyntax : TExpressionSyntax
where TArgumentSyntax : SyntaxNode
where TLiteralExpressionSyntax : SyntaxNode
{
protected abstract SyntaxNode GetInterpolatedString(string text);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
var stringType = semanticModel.Compilation.GetSpecialType(SpecialType.System_String);
if (stringType == null)
{
return;
}
var formatMethods = stringType
.GetMembers(nameof(string.Format))
.OfType<IMethodSymbol>()
.Where(ShouldIncludeFormatMethod)
.ToImmutableArray();
if (formatMethods.Length == 0)
{
return;
}
var syntaxFactsService = context.Document.GetLanguageService<ISyntaxFactsService>();
if (syntaxFactsService == null)
{
return;
}
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (TryFindInvocation(context.Span, root, semanticModel, formatMethods, syntaxFactsService, context.CancellationToken, out var invocation, out var invocationSymbol) &&
IsArgumentListCorrect(syntaxFactsService.GetArgumentsOfInvocationExpression(invocation), invocationSymbol, formatMethods, semanticModel, syntaxFactsService, context.CancellationToken))
{
context.RegisterRefactoring(
new ConvertToInterpolatedStringCodeAction(
FeaturesResources.Convert_to_interpolated_string,
c => CreateInterpolatedString(invocation, context.Document, syntaxFactsService, c)));
}
}
private bool TryFindInvocation(
TextSpan span,
SyntaxNode root,
SemanticModel semanticModel,
ImmutableArray<IMethodSymbol> formatMethods,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken,
out TInvocationExpressionSyntax invocation,
out ISymbol invocationSymbol)
{
invocationSymbol = null;
invocation = root.FindNode(span, getInnermostNodeForTie: true)?.FirstAncestorOrSelf<TInvocationExpressionSyntax>();
while (invocation != null)
{
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation);
if (arguments.Count >= 2)
{
var firstArgumentExpression = syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) as TLiteralExpressionSyntax;
if (firstArgumentExpression != null && syntaxFactsService.IsStringLiteral(firstArgumentExpression.GetFirstToken()))
{
invocationSymbol = semanticModel.GetSymbolInfo(invocation, cancellationToken).Symbol;
if (formatMethods.Contains(invocationSymbol))
{
break;
}
}
}
invocation = invocation.Parent?.FirstAncestorOrSelf<TInvocationExpressionSyntax>();
}
return invocation != null;
}
private bool IsArgumentListCorrect(
SeparatedSyntaxList<TArgumentSyntax>? nullableArguments,
ISymbol invocationSymbol,
ImmutableArray<IMethodSymbol> formatMethods,
SemanticModel semanticModel,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
var arguments = nullableArguments.Value;
var firstExpression = syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) as TLiteralExpressionSyntax;
if (arguments.Count >= 2 &&
firstExpression != null &&
syntaxFactsService.IsStringLiteral(firstExpression.GetFirstToken()))
{
// We do not want to substitute the expression if it is being passed to params array argument
// Example:
// string[] args;
// String.Format("{0}{1}{2}", args);
return IsArgumentListNotPassingArrayToParams(
syntaxFactsService.GetExpressionOfArgument(GetParamsArgument(arguments, syntaxFactsService)),
invocationSymbol,
formatMethods,
semanticModel,
cancellationToken);
}
return false;
}
private async Task<Document> CreateInterpolatedString(
TInvocationExpressionSyntax invocation,
Document document,
ISyntaxFactsService syntaxFactsService,
CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocation);
var literalExpression = syntaxFactsService.GetExpressionOfArgument(GetFormatArgument(arguments, syntaxFactsService)) as TLiteralExpressionSyntax;
var text = literalExpression.GetFirstToken().ToString();
var syntaxGenerator = document.Project.LanguageServices.GetService<SyntaxGenerator>();
var expandedArguments = GetExpandedArguments(semanticModel, arguments, syntaxGenerator, syntaxFactsService);
var interpolatedString = GetInterpolatedString(text);
var newInterpolatedString = VisitArguments(expandedArguments, interpolatedString, syntaxFactsService);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.ReplaceNode(invocation, newInterpolatedString.WithTriviaFrom(invocation));
return document.WithSyntaxRoot(newRoot);
}
private string GetArgumentName(TArgumentSyntax argument, ISyntaxFactsService syntaxFactsService)
=> syntaxFactsService.GetNameForArgument(argument);
private SyntaxNode GetParamsArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService)
=> arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[1];
private TArgumentSyntax GetFormatArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService)
=> arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[0];
private TArgumentSyntax GetArgument(SeparatedSyntaxList<TArgumentSyntax> arguments, int index, ISyntaxFactsService syntaxFactsService)
{
if (arguments.Count > 4)
{
return arguments[index];
}
return arguments.FirstOrDefault(
argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.ParamsArgumentNames[index], StringComparison.OrdinalIgnoreCase))
?? arguments[index];
}
private ImmutableArray<TExpressionSyntax> GetExpandedArguments(
SemanticModel semanticModel,
SeparatedSyntaxList<TArgumentSyntax> arguments,
SyntaxGenerator syntaxGenerator,
ISyntaxFactsService syntaxFactsService)
{
var builder = ArrayBuilder<TExpressionSyntax>.GetInstance();
for (int i = 1; i < arguments.Count; i++)
{
var argumentExpression = syntaxFactsService.GetExpressionOfArgument(GetArgument(arguments, i, syntaxFactsService));
var convertedType = semanticModel.GetTypeInfo(argumentExpression).ConvertedType;
if (convertedType == null)
{
builder.Add(syntaxFactsService.Parenthesize(argumentExpression) as TExpressionSyntax);
}
else
{
var castExpression = syntaxGenerator.CastExpression(convertedType, syntaxFactsService.Parenthesize(argumentExpression)).WithAdditionalAnnotations(Simplifier.Annotation);
builder.Add(castExpression as TExpressionSyntax);
}
}
var expandedArguments = builder.ToImmutableAndFree();
return expandedArguments;
}
private SyntaxNode VisitArguments(
ImmutableArray<TExpressionSyntax> expandedArguments,
SyntaxNode interpolatedString,
ISyntaxFactsService syntaxFactsService)
{
return interpolatedString.ReplaceNodes(syntaxFactsService.GetContentsOfInterpolatedString(interpolatedString), (oldNode, newNode) =>
{
var interpolationSyntaxNode = newNode;
if (interpolationSyntaxNode != null)
{
var literalExpression = syntaxFactsService.GetExpressionOfInterpolation(interpolationSyntaxNode) as TLiteralExpressionSyntax;
if (literalExpression != null && syntaxFactsService.IsNumericLiteralExpression(literalExpression))
{
if (int.TryParse(literalExpression.GetFirstToken().ValueText, out var index))
{
if (index >= 0 && index < expandedArguments.Length)
{
return interpolationSyntaxNode.ReplaceNode(
syntaxFactsService.GetExpressionOfInterpolation(interpolationSyntaxNode),
syntaxFactsService.ConvertToSingleLine(expandedArguments[index], useElasticTrivia: true).WithAdditionalAnnotations(Formatter.Annotation));
}
}
}
}
return newNode;
});
}
private static bool ShouldIncludeFormatMethod(IMethodSymbol methodSymbol)
{
if (!methodSymbol.IsStatic)
{
return false;
}
if (methodSymbol.Parameters.Length == 0)
{
return false;
}
var firstParameter = methodSymbol.Parameters[0];
if (firstParameter?.Name != StringFormatArguments.FormatArgumentName)
{
return false;
}
return true;
}
private static bool IsArgumentListNotPassingArrayToParams(
SyntaxNode expression,
ISymbol invocationSymbol,
ImmutableArray<IMethodSymbol> formatMethods,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var formatMethodsAcceptingParamsArray = formatMethods
.Where(x => x.Parameters.Length > 1 && x.Parameters[1].Type.Kind == SymbolKind.ArrayType);
if (formatMethodsAcceptingParamsArray.Contains(invocationSymbol))
{
return semanticModel.GetTypeInfo(expression, cancellationToken).Type?.Kind != SymbolKind.ArrayType;
}
return true;
}
private class ConvertToInterpolatedStringCodeAction : CodeAction.DocumentChangeAction
{
public ConvertToInterpolatedStringCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) :
base(title, createChangedDocument)
{
}
}
private static class StringFormatArguments
{
public const string FormatArgumentName = "format";
public const string ArgsArgumentName = "args";
public static readonly ImmutableArray<string> ParamsArgumentNames =
ImmutableArray.Create("", "arg0", "arg1", "arg2");
}
}
}
|
kelltrick/roslyn
|
src/Features/Core/Portable/ConvertToInterpolatedString/AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider.cs
|
C#
|
apache-2.0
| 13,484 |
/*
* Copyright 2015 Brent Douglas and other contributors
* as indicated by the @author tags. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.machinecode.chainlink.core.jsl.fluent.task;
import io.machinecode.chainlink.core.jsl.fluent.FluentPropertyReference;
import io.machinecode.chainlink.spi.jsl.task.CheckpointAlgorithm;
/**
* @author <a href="mailto:brent.n.douglas@gmail.com">Brent Douglas</a>
* @since 1.0
*/
public class FluentCheckpointAlgorithm extends FluentPropertyReference<FluentCheckpointAlgorithm> implements CheckpointAlgorithm {
@Override
public FluentCheckpointAlgorithm copy() {
return copy(new FluentCheckpointAlgorithm());
}
}
|
BrentDouglas/chainlink
|
core/src/main/java/io/machinecode/chainlink/core/jsl/fluent/task/FluentCheckpointAlgorithm.java
|
Java
|
apache-2.0
| 1,211 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.classmethod.sparrow.model;
import java.util.List;
import org.springframework.data.repository.query.Param;
import jp.xet.sparwings.spring.data.repository.CreatableRepository;
/**
* Created by mochizukimasao on 2017/04/11.
*
* Calculator repository interface.
*
* @author mochizukimasao
* @since version
*/
public interface LineMessageEntityRepository extends CreatableRepository<LineMessageEntity, String> {
/**
* 引数で受け取るuserIdと一致するoffsetの位置(0始まり)からlimitに指定した数以下の要素を返します
*
* @param userId ユーザーID
* @param offset 読み飛ばす行数
* @param limit 取得行数
* @return offsetからlimitに指定した数以下の要素を返します。一致するデータがない場合は空のコレクションを返します。
*/
List<LineMessageEntity> findByUser(
@Param("userId") String userId, @Param("offset") int offset, @Param("size") int limit);
}
|
classmethod-sandbox/sparrow
|
src/main/java/jp/classmethod/sparrow/model/LineMessageEntityRepository.java
|
Java
|
apache-2.0
| 1,590 |
/*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* InstancePatchStateMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class InstancePatchStateMarshaller {
private static final MarshallingInfo<String> INSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstanceId").build();
private static final MarshallingInfo<String> PATCHGROUP_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PatchGroup").build();
private static final MarshallingInfo<String> BASELINEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("BaselineId").build();
private static final MarshallingInfo<String> SNAPSHOTID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("SnapshotId").build();
private static final MarshallingInfo<String> OWNERINFORMATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OwnerInformation").build();
private static final MarshallingInfo<Integer> INSTALLEDCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstalledCount").build();
private static final MarshallingInfo<Integer> INSTALLEDOTHERCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("InstalledOtherCount").build();
private static final MarshallingInfo<Integer> MISSINGCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("MissingCount").build();
private static final MarshallingInfo<Integer> FAILEDCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("FailedCount").build();
private static final MarshallingInfo<Integer> NOTAPPLICABLECOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("NotApplicableCount").build();
private static final MarshallingInfo<java.util.Date> OPERATIONSTARTTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OperationStartTime").build();
private static final MarshallingInfo<java.util.Date> OPERATIONENDTIME_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("OperationEndTime").build();
private static final MarshallingInfo<String> OPERATION_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("Operation").build();
private static final InstancePatchStateMarshaller instance = new InstancePatchStateMarshaller();
public static InstancePatchStateMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(InstancePatchState instancePatchState, ProtocolMarshaller protocolMarshaller) {
if (instancePatchState == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(instancePatchState.getInstanceId(), INSTANCEID_BINDING);
protocolMarshaller.marshall(instancePatchState.getPatchGroup(), PATCHGROUP_BINDING);
protocolMarshaller.marshall(instancePatchState.getBaselineId(), BASELINEID_BINDING);
protocolMarshaller.marshall(instancePatchState.getSnapshotId(), SNAPSHOTID_BINDING);
protocolMarshaller.marshall(instancePatchState.getOwnerInformation(), OWNERINFORMATION_BINDING);
protocolMarshaller.marshall(instancePatchState.getInstalledCount(), INSTALLEDCOUNT_BINDING);
protocolMarshaller.marshall(instancePatchState.getInstalledOtherCount(), INSTALLEDOTHERCOUNT_BINDING);
protocolMarshaller.marshall(instancePatchState.getMissingCount(), MISSINGCOUNT_BINDING);
protocolMarshaller.marshall(instancePatchState.getFailedCount(), FAILEDCOUNT_BINDING);
protocolMarshaller.marshall(instancePatchState.getNotApplicableCount(), NOTAPPLICABLECOUNT_BINDING);
protocolMarshaller.marshall(instancePatchState.getOperationStartTime(), OPERATIONSTARTTIME_BINDING);
protocolMarshaller.marshall(instancePatchState.getOperationEndTime(), OPERATIONENDTIME_BINDING);
protocolMarshaller.marshall(instancePatchState.getOperation(), OPERATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
dagnir/aws-sdk-java
|
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/InstancePatchStateMarshaller.java
|
Java
|
apache-2.0
| 5,993 |
/*****************************************************************************************************
*
* Authors:
*
* <b> Java SDK for CWL </b>
*
* @author Paul Grosu (pgrosu@gmail.com), Northeastern University
* @version 0.20
* @since April 28, 2016
*
* <p> Alternate SDK (via Avro):
*
* Denis Yuen (denis.yuen@gmail.com)
*
* CWL Draft:
*
* Peter Amstutz (peter.amstutz@curoverse.com), Curoverse
* Nebojsa Tijanic (nebojsa.tijanic@sbgenomics.com), Seven Bridges Genomics
*
* Contributors:
*
* Luka Stojanovic (luka.stojanovic@sbgenomics.com), Seven Bridges Genomics
* John Chilton (jmchilton@gmail.com), Galaxy Project, Pennsylvania State University
* Michael R. Crusoe (crusoe@ucdavis.edu), University of California, Davis
* Herve Menager (herve.menager@gmail.com), Institut Pasteur
* Maxim Mikheev (mikhmv@biodatomics.com), BioDatomics
* Stian Soiland-Reyes (soiland-reyes@cs.manchester.ac.uk), University of Manchester
*
*****************************************************************************************************/
package org.commonwl.lang;
/*****************************************************************************************************
*
* An output parameter for a CommandLineTool.
*/
public class CommandOutputParameter extends OutputParameter {
/*****************************************************************************************************
*
* Specify valid types of data that may be assigned to this parameter.
*/
Object type = null;
/*****************************************************************************************************
*
* Describes how to handle the outputs of a process.
*/
CommandOutputBinding outputBinding = null;
/*****************************************************************************************************
*
* The unique identifier for this parameter object.
*/
String id = null;
/*****************************************************************************************************
*
* Only valid when `type: File` or is an array of `items: File`. A value of `true` indicates that the file is read or written sequentially without seeking. An implementation may use this flag to indicate whether it is valid to stream file contents using a named pipe. Default: `false`.
*/
Boolean streamable = null;
/*****************************************************************************************************
*
* Only valid when `type: File` or is an array of `items: File`. For input parameters, this must be one or more IRIs of concept nodes that represents file formats which are allowed as input to this parameter, preferrably defined within an ontology. If no ontology is available, file formats may be tested by exact match. For output parameters, this is the file format that will be assigned to the output parameter.
*/
Object format = null;
/*****************************************************************************************************
*
* A documentation string for this type, or an array of strings which should be concatenated.
*/
Object doc = null;
/*****************************************************************************************************
*
* Only valid when `type: File` or is an array of `items: File`. Describes files that must be included alongside the primary file(s). If the value is an expression, the value of `self` in the expression must be the primary input or output File to which this binding applies. If the value is a string, it specifies that the following pattern should be applied to the primary file: 1. If string begins with one or more caret `^` characters, for each caret, remove the last file extension from the path (the last period `.` and all following characters). If there are no file extensions, the path is unchanged. 2. Append the remainder of the string to the end of the file path.
*/
Object secondaryFiles = null;
/*****************************************************************************************************
*
* A short, human-readable label of this object.
*/
String label = null;
public CommandOutputParameter() { super(); }
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputArraySchema type.
*
*/
public void settype( CommandOutputArraySchema value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a stderr type.
*
*/
public void settype( stderr value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a String array.
*
*/
public void settype( String [] value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputArraySchema array.
*
*/
public void settype( CommandOutputArraySchema [] value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CWLType array.
*
*/
public void settype( CWLType [] value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputRecordSchema array.
*
*/
public void settype( CommandOutputRecordSchema [] value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CWLType type.
*
*/
public void settype( CWLType value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a stdout type.
*
*/
public void settype( stdout value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputEnumSchema type.
*
*/
public void settype( CommandOutputEnumSchema value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a String type.
*
*/
public void settype( String value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputRecordSchema type.
*
*/
public void settype( CommandOutputRecordSchema value ) {
type = value;
}
/*****************************************************************************************************
*
* This method sets the value of type.
*
* @param value will update type, which is a CommandOutputEnumSchema array.
*
*/
public void settype( CommandOutputEnumSchema [] value ) {
type = value;
}
/*****************************************************************************************************
*
* This method returns the value of type.
*
* @return This method will return the value of type, which is a Object type.
*
*/
public Object gettype() {
return type;
}
/*****************************************************************************************************
*
* This method sets the value of outputBinding.
*
* @param value will update outputBinding, which is a CommandOutputBinding type.
*
*/
public void setoutputBinding( CommandOutputBinding value ) {
outputBinding = value;
}
/*****************************************************************************************************
*
* This method returns the value of outputBinding.
*
* @return This method will return the value of outputBinding, which is a CommandOutputBinding type.
*
*/
public CommandOutputBinding getoutputBinding() {
return outputBinding;
}
/*****************************************************************************************************
*
* This method sets the value of id.
*
* @param value will update id, which is a String type.
*
*/
public void setid( String value ) {
id = value;
}
/*****************************************************************************************************
*
* This method returns the value of id.
*
* @return This method will return the value of id, which is a String type.
*
*/
public String getid() {
return id;
}
/*****************************************************************************************************
*
* This method sets the value of streamable.
*
* @param value will update streamable, which is a Boolean type.
*
*/
public void setstreamable( Boolean value ) {
streamable = value;
}
/*****************************************************************************************************
*
* This method returns the value of streamable.
*
* @return This method will return the value of streamable, which is a Boolean type.
*
*/
public Boolean getstreamable() {
return streamable;
}
/*****************************************************************************************************
*
* This method sets the value of format.
*
* @param value will update format, which is a Expression array.
*
*/
public void setformat( Expression [] value ) {
format = value;
}
/*****************************************************************************************************
*
* This method sets the value of format.
*
* @param value will update format, which is a String type.
*
*/
public void setformat( String value ) {
format = value;
}
/*****************************************************************************************************
*
* This method sets the value of format.
*
* @param value will update format, which is a String array.
*
*/
public void setformat( String [] value ) {
format = value;
}
/*****************************************************************************************************
*
* This method returns the value of format.
*
* @return This method will return the value of format, which is a Object type.
*
*/
public Object getformat() {
return format;
}
/*****************************************************************************************************
*
* This method sets the value of doc.
*
* @param value will update doc, which is a String type.
*
*/
public void setdoc( String value ) {
doc = value;
}
/*****************************************************************************************************
*
* This method sets the value of doc.
*
* @param value will update doc, which is a String array.
*
*/
public void setdoc( String [] value ) {
doc = value;
}
/*****************************************************************************************************
*
* This method returns the value of doc.
*
* @return This method will return the value of doc, which is a Object type.
*
*/
public Object getdoc() {
return doc;
}
/*****************************************************************************************************
*
* This method sets the value of secondaryFiles.
*
* @param value will update secondaryFiles, which is a Expression array.
*
*/
public void setsecondaryFiles( Expression [] value ) {
secondaryFiles = value;
}
/*****************************************************************************************************
*
* This method sets the value of secondaryFiles.
*
* @param value will update secondaryFiles, which is a String type.
*
*/
public void setsecondaryFiles( String value ) {
secondaryFiles = value;
}
/*****************************************************************************************************
*
* This method sets the value of secondaryFiles.
*
* @param value will update secondaryFiles, which is a String array.
*
*/
public void setsecondaryFiles( String [] value ) {
secondaryFiles = value;
}
/*****************************************************************************************************
*
* This method sets the value of secondaryFiles.
*
* @param value will update secondaryFiles, which is a Expression type.
*
*/
public void setsecondaryFiles( Expression value ) {
secondaryFiles = value;
}
/*****************************************************************************************************
*
* This method returns the value of secondaryFiles.
*
* @return This method will return the value of secondaryFiles, which is a Object type.
*
*/
public Object getsecondaryFiles() {
return secondaryFiles;
}
/*****************************************************************************************************
*
* This method sets the value of label.
*
* @param value will update label, which is a String type.
*
*/
public void setlabel( String value ) {
label = value;
}
/*****************************************************************************************************
*
* This method returns the value of label.
*
* @return This method will return the value of label, which is a String type.
*
*/
public String getlabel() {
return label;
}
}
|
common-workflow-language/cwljava
|
sdk-and-javadoc-generation/org/commonwl/lang/CommandOutputParameter.java
|
Java
|
apache-2.0
| 14,693 |
package io.quarkus.maven.it.assertions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.File;
import java.io.FileInputStream;
import java.util.Optional;
import java.util.Properties;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.Profile;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import io.quarkus.devtools.project.QuarkusProjectHelper;
import io.quarkus.devtools.testing.RegistryClientTestHelper;
import io.quarkus.maven.utilities.MojoUtils;
import io.quarkus.platform.tools.ToolsConstants;
import io.quarkus.registry.catalog.ExtensionCatalog;
public class SetupVerifier {
public static void assertThatJarExists(File archive) throws Exception {
JarVerifier jarVerifier = new JarVerifier(archive);
jarVerifier.assertThatJarIsCreated();
jarVerifier.assertThatJarHasManifest();
}
public static void assertThatJarContainsFile(File archive, String file) throws Exception {
JarVerifier jarVerifier = new JarVerifier(archive);
jarVerifier.assertThatFileIsContained(file);
}
public static void assertThatJarDoesNotContainFile(File archive, String file) throws Exception {
JarVerifier jarVerifier = new JarVerifier(archive);
jarVerifier.assertThatFileIsNotContained(file);
}
public static void assertThatJarContainsFileWithContent(File archive, String path, String... lines) throws Exception {
JarVerifier jarVerifier = new JarVerifier(archive);
jarVerifier.assertThatFileContains(path, lines);
}
public static void verifySetup(File pomFile) throws Exception {
assertNotNull(pomFile, "Unable to find pom.xml");
MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
Model model = xpp3Reader.read(new FileInputStream(pomFile));
MavenProject project = new MavenProject(model);
Optional<Plugin> maybe = hasPlugin(project, ToolsConstants.IO_QUARKUS + ":" + ToolsConstants.QUARKUS_MAVEN_PLUGIN);
assertThat(maybe).isNotEmpty();
//Check if the properties have been set correctly
Properties properties = model.getProperties();
assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_GROUP_ID_NAME)).isTrue();
assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_ARTIFACT_ID_NAME)).isTrue();
assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLATFORM_VERSION_NAME)).isTrue();
assertThat(properties.containsKey(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_NAME)).isTrue();
// Check plugin is set
Plugin plugin = maybe.orElseThrow(() -> new AssertionError("Plugin expected"));
assertThat(plugin).isNotNull().satisfies(p -> {
assertThat(p.getArtifactId()).isEqualTo(ToolsConstants.QUARKUS_MAVEN_PLUGIN);
assertThat(p.getGroupId()).isEqualTo(ToolsConstants.IO_QUARKUS);
assertThat(p.getVersion()).isEqualTo(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_VALUE);
});
// Check build execution Configuration
assertThat(plugin.getExecutions()).hasSize(1).allSatisfy(execution -> {
assertThat(execution.getGoals()).containsExactly("build");
assertThat(execution.getConfiguration()).isNull();
});
// Check profile
assertThat(model.getProfiles()).hasSize(1);
Profile profile = model.getProfiles().get(0);
assertThat(profile.getId()).isEqualTo("native");
Plugin actual = profile.getBuild().getPluginsAsMap()
.get(ToolsConstants.IO_QUARKUS + ":" + ToolsConstants.QUARKUS_MAVEN_PLUGIN);
assertThat(actual).isNotNull();
assertThat(actual.getExecutions()).hasSize(1).allSatisfy(exec -> {
assertThat(exec.getGoals()).containsExactly("native-image");
assertThat(exec.getConfiguration()).isInstanceOf(Xpp3Dom.class)
.satisfies(o -> assertThat(o.toString()).contains("enableHttpUrlHandler"));
});
}
public static Optional<Plugin> hasPlugin(MavenProject project, String pluginKey) {
Optional<Plugin> optPlugin = project.getBuildPlugins().stream()
.filter(plugin -> pluginKey.equals(plugin.getKey()))
.findFirst();
if (!optPlugin.isPresent() && project.getPluginManagement() != null) {
optPlugin = project.getPluginManagement().getPlugins().stream()
.filter(plugin -> pluginKey.equals(plugin.getKey()))
.findFirst();
}
return optPlugin;
}
public static void verifySetupWithVersion(File pomFile) throws Exception {
MavenXpp3Reader xpp3Reader = new MavenXpp3Reader();
Model model = xpp3Reader.read(new FileInputStream(pomFile));
MavenProject project = new MavenProject(model);
Properties projectProps = project.getProperties();
assertNotNull(projectProps);
assertFalse(projectProps.isEmpty());
final String quarkusVersion = getPlatformDescriptor().getQuarkusCoreVersion();
assertEquals(quarkusVersion, projectProps.getProperty(MojoUtils.TEMPLATE_PROPERTY_QUARKUS_PLUGIN_VERSION_NAME));
}
private static ExtensionCatalog getPlatformDescriptor() throws Exception {
RegistryClientTestHelper.enableRegistryClientTestConfig();
try {
return QuarkusProjectHelper.getCatalogResolver().resolveExtensionCatalog();
} finally {
RegistryClientTestHelper.disableRegistryClientTestConfig();
}
}
}
|
quarkusio/quarkus
|
test-framework/maven/src/main/java/io/quarkus/maven/it/assertions/SetupVerifier.java
|
Java
|
apache-2.0
| 5,917 |
/*
* Copyright 2021 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.migration.wfly.task.subsystem.microprofile;
import org.jboss.migration.core.jboss.JBossExtensionNames;
import org.jboss.migration.core.jboss.JBossSubsystemNames;
import org.jboss.migration.wfly10.config.management.ProfileResource;
import org.jboss.migration.wfly10.config.task.management.subsystem.AddSubsystemResourceSubtaskBuilder;
import org.jboss.migration.wfly10.config.task.management.subsystem.AddSubsystemResources;
/**
* @author emmartins
*/
public class WildFly23_0AddMicroprofileJwtSmallryeSubsystem<S> extends AddSubsystemResources<S> {
public WildFly23_0AddMicroprofileJwtSmallryeSubsystem() {
super(JBossExtensionNames.MICROPROFILE_JWT_SMALLRYE, new SubtaskBuilder<>());
// do not add subsystem config to "standalone-load-balancer.xml" config
skipPolicyBuilders(getSkipPolicyBuilder(),
buildParameters -> context -> buildParameters.getServerConfiguration().getConfigurationPath().getPath().endsWith("standalone-load-balancer.xml"));
}
static class SubtaskBuilder<S> extends AddSubsystemResourceSubtaskBuilder<S> {
SubtaskBuilder() {
super(JBossSubsystemNames.MICROPROFILE_JWT_SMALLRYE);
// do not add subsystem config to profile "load-balancer"
skipPolicyBuilder(buildParameters -> context -> buildParameters.getResource().getResourceType() == ProfileResource.RESOURCE_TYPE && buildParameters.getResource().getResourceName().equals("load-balancer"));
}
}
}
|
emmartins/wildfly-server-migration
|
servers/wildfly23.0/src/main/java/org/jboss/migration/wfly/task/subsystem/microprofile/WildFly23_0AddMicroprofileJwtSmallryeSubsystem.java
|
Java
|
apache-2.0
| 2,097 |
package p321
import (
"github.com/stretchr/testify/assert"
"testing"
)
func Test0(t *testing.T) {
assert.Equal(t, []int{5, 4}, maxOneArray([]int{5, 2, 3, 4, 1}, 2))
assert.Equal(t, []int{6}, maxOneArray([]int{2, 4, 6, 5}, 1))
assert.Equal(t, []int{6, 5}, maxOneArray([]int{2, 4, 6, 5}, 2))
assert.Equal(t, []int{4, 6, 5}, maxOneArray([]int{2, 4, 6, 5}, 3))
assert.Equal(t, []int{2, 4, 6, 5}, maxOneArray([]int{2, 4, 6, 5}, 4))
}
func Test1(t *testing.T) {
assert.Equal(t, []int{9, 8, 6, 5, 3}, maxNumber([]int{3, 4, 6, 5}, []int{9, 1, 2, 5, 8, 3}, 5))
}
|
baishuai/leetcode
|
algorithms/p321/321_test.go
|
GO
|
apache-2.0
| 565 |
# frozen_string_literal: true
# encoding: utf-8
# Copyright (C) 2018-2020 MongoDB Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
module Mongo
module Operation
class Aggregate
# A MongoDB aggregate operation sent as an op message.
#
# @api private
#
# @since 2.5.2
class OpMsg < OpMsgBase
include CausalConsistencySupported
include ExecutableTransactionLabel
include PolymorphicResult
end
end
end
end
|
mongodb/mongo-ruby-driver
|
lib/mongo/operation/aggregate/op_msg.rb
|
Ruby
|
apache-2.0
| 983 |
// Copyright 2018 NetApp, Inc. All Rights Reserved.
package main
import (
"os"
"github.com/netapp/trident/cli/cmd"
)
func main() {
cmd.ExitCode = cmd.ExitCodeSuccess
if err := cmd.RootCmd.Execute(); err != nil {
cmd.SetExitCodeFromError(err)
}
os.Exit(cmd.ExitCode)
}
|
NetApp/trident
|
cli/main.go
|
GO
|
apache-2.0
| 282 |
package ru.stqa.pft.mantis.appmanager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.BrowserType;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Objects;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* Created by Александр on 06.11.2016.
*/
public class ApplicationManager {
WebDriver wd;
private final Properties properties;
private String browser;
public ApplicationManager(String browser){
this.browser = browser;
properties = new Properties();
}
public void init() throws IOException {
//String browser = BrowserType.CHROME;
String target = System.getProperty("target", "local");
properties.load(new FileReader(new File(String.format("L:/Devel/java_pft/addressbook-web-tests/src/test/resources/%s.properties", target))));
if (Objects.equals(browser, BrowserType.FIREFOX)) {
wd = new FirefoxDriver();
} else if (Objects.equals(browser, BrowserType.CHROME)){
wd = new ChromeDriver();
} else if (Objects.equals(browser, BrowserType.IE)){
wd = new InternetExplorerDriver();
}
wd.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
wd.get(properties.getProperty("web.baseUrl"));
}
public void stop() {
wd.quit();
}
}
|
martyanova/java_pft
|
mantis-tests/src/test/java/ru/stqa/pft/mantis/appmanager/ApplicationManager.java
|
Java
|
apache-2.0
| 1,475 |
class Fluentd
module Setting
class BufferMemory
include Fluentd::Setting::Plugin
register_plugin("buffer", "memory")
def self.initial_params
{}
end
def common_options
[]
end
def advanced_options
[]
end
end
end
end
|
fluent/fluentd-ui
|
app/models/fluentd/setting/buffer_memory.rb
|
Ruby
|
apache-2.0
| 302 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.elasticache.model.transform;
import java.util.ArrayList;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.elasticache.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* DescribeUpdateActionsResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeUpdateActionsResultStaxUnmarshaller implements Unmarshaller<DescribeUpdateActionsResult, StaxUnmarshallerContext> {
public DescribeUpdateActionsResult unmarshall(StaxUnmarshallerContext context) throws Exception {
DescribeUpdateActionsResult describeUpdateActionsResult = new DescribeUpdateActionsResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 2;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return describeUpdateActionsResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("Marker", targetDepth)) {
describeUpdateActionsResult.setMarker(StringStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("UpdateActions", targetDepth)) {
describeUpdateActionsResult.withUpdateActions(new ArrayList<UpdateAction>());
continue;
}
if (context.testExpression("UpdateActions/UpdateAction", targetDepth)) {
describeUpdateActionsResult.withUpdateActions(UpdateActionStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return describeUpdateActionsResult;
}
}
}
}
private static DescribeUpdateActionsResultStaxUnmarshaller instance;
public static DescribeUpdateActionsResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeUpdateActionsResultStaxUnmarshaller();
return instance;
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-elasticache/src/main/java/com/amazonaws/services/elasticache/model/transform/DescribeUpdateActionsResultStaxUnmarshaller.java
|
Java
|
apache-2.0
| 3,071 |
using System.ComponentModel.DataAnnotations;
namespace ChatSystem.Server.Models.Account
{
public class AddExternalLoginBindingModel
{
[Required]
[Display(Name = "External access token")]
public string ExternalAccessToken { get; set; }
}
}
|
deyantodorov/Zeus-WebServicesCould-TeamWork
|
Source/ChatSystem/Server/ChatSystem.Server/Models/Account/AddExternalLoginBindingModel.cs
|
C#
|
apache-2.0
| 278 |
package mtag
import (
"github.com/mabetle/mcore"
"strings"
)
// label tag format:
// label="zh='' en=''"
// GetLabelTag returns field "label" tag value.
func GetLabelTag(v interface{}, fieldName string) (string, bool) {
return GetTag(v, fieldName, "label")
}
// parse string to KeyValue map.
func ParseKeyValueMap(value string) map[string]string {
result := make(map[string]string)
rows := strings.Split(value, " ")
for _, row := range rows {
// skip blank
if strings.TrimSpace(row) == "" {
continue
}
kv := strings.Split(row, "=")
if len(kv) == 2 {
k := strings.TrimSpace(kv[0])
v := strings.TrimSpace(kv[1])
v = strings.Trim(v, "'")
v = strings.Trim(v, "\"")
v = strings.TrimSpace(v)
result[k] = v
}
}
return result
}
// GetLocaleLabel returns field label by locale.
// locale format: en en_US / zh zh_CN zh_HK etc.
func GetLocaleLabel(v interface{}, fieldName string, locale string) string {
labelValue, e := GetLabelTag(v, fieldName)
// not exist
if !e {
return mcore.ToLabel(fieldName)
}
locale = strings.Replace(locale, "-", "_", -1)
lang := strings.Split(locale, "_")[0]
m := ParseKeyValueMap(labelValue)
// include lang_coutry locale
if v, ok := m[locale]; ok {
return v
}
// include lang
if v, ok := m[lang]; ok {
return v
}
// defult en
if v, ok := m["en"]; ok {
return v
}
// default return
return mcore.ToLabel(fieldName)
}
// GetLabelZH
func GetLabelZH(v interface{}, fieldName string) string {
return GetLocaleLabel(v, fieldName, "zh")
}
// GetLabelEN
func GetLabelEN(v interface{}, fieldName string) string {
return GetLocaleLabel(v, fieldName, "en")
}
|
mabetle/mcore
|
mtag/tag_label.go
|
GO
|
apache-2.0
| 1,652 |
from __future__ import unicode_literals
import pygst
pygst.require('0.10')
import gst # noqa
from mopidy.audio import output
import logging
logger = logging.getLogger(__name__)
# This variable is a global that is set by the Backend
# during initialization from the extension properties
encoder = 'identity'
class RtpSink(gst.Bin):
def __init__(self):
super(RtpSink, self).__init__()
# These elements are 'always on' even if nobody is
# subscribed to listen. It streamlines the process
# of adding/removing listeners.
queue = gst.element_factory_make('queue')
rate = gst.element_factory_make('audiorate')
enc = gst.element_factory_make(encoder)
pay = gst.element_factory_make('rtpgstpay')
# Re-use of the audio output bin which handles
# dynamic element addition/removal nicely
self.tee = output.AudioOutput()
self.add_many(queue, rate, enc, pay, self.tee)
gst.element_link_many(queue, rate, enc, pay, self.tee)
pad = queue.get_pad('sink')
ghost_pad = gst.GhostPad('sink', pad)
self.add_pad(ghost_pad)
def add(self, host, port):
b = gst.Bin()
queue = gst.element_factory_make('queue')
udpsink = gst.element_factory_make('udpsink')
udpsink.set_property('host', host)
udpsink.set_property('port', port)
# Both async and sync must be true to avoid seek
# timestamp sync problems
udpsink.set_property('sync', True)
udpsink.set_property('async', True)
b.add_many(queue, udpsink)
gst.element_link_many(queue, udpsink)
pad = queue.get_pad('sink')
ghost_pad = gst.GhostPad('sink', pad)
b.add_pad(ghost_pad)
ident = str(port) + '@' + host
self.tee.add_sink(ident, b)
def remove(self, host, port):
ident = str(port) + '@' + host
self.tee.remove_sink(ident)
|
liamw9534/mopidy-rtp
|
mopidy_rtp/sink.py
|
Python
|
apache-2.0
| 1,944 |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.simplesystemsmanagement.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.simplesystemsmanagement.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DescribePatchPropertiesRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DescribePatchPropertiesRequestProtocolMarshaller implements Marshaller<Request<DescribePatchPropertiesRequest>, DescribePatchPropertiesRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("AmazonSSM.DescribePatchProperties").serviceName("AWSSimpleSystemsManagement").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DescribePatchPropertiesRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DescribePatchPropertiesRequest> marshall(DescribePatchPropertiesRequest describePatchPropertiesRequest) {
if (describePatchPropertiesRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DescribePatchPropertiesRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, describePatchPropertiesRequest);
protocolMarshaller.startMarshalling();
DescribePatchPropertiesRequestMarshaller.getInstance().marshall(describePatchPropertiesRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
jentfoo/aws-sdk-java
|
aws-java-sdk-ssm/src/main/java/com/amazonaws/services/simplesystemsmanagement/model/transform/DescribePatchPropertiesRequestProtocolMarshaller.java
|
Java
|
apache-2.0
| 2,847 |
/*
#
# Copyright 2014 The Trustees of Indiana University
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
*/
package edu.indiana.d2i.komadu.ingest.db;
public class TableAttributeData {
/**
* enum to keep data types of the value to be inserted
* add to this list if a new type is needed
*/
public static enum DataType {
STRING,
INT,
LONG,
FLOAT,
DOUBLE,
SHORT,
DATE,
TIME,
TIMESTAMP
}
private String attributeName;
private Object value;
private DataType type;
public TableAttributeData(String attributeName, Object value, DataType type) {
this.attributeName = attributeName;
this.value = value;
this.type = type;
}
public String getAttributeName() {
return attributeName;
}
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public DataType getType() {
return type;
}
public void setType(DataType type) {
this.type = type;
}
}
|
Data-to-Insight-Center/komadu
|
service-core/src/main/java/edu/indiana/d2i/komadu/ingest/db/TableAttributeData.java
|
Java
|
apache-2.0
| 1,714 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AC_ServiceClient.ACServiceReference;
using AC_SessionReport;
namespace AC_ServiceClient
{
public class ACServiceSessionReportHandler : ISessionReportHandler
{
public void HandleReport(SessionReport report)
{
ACServiceClient client = new ACServiceClient();
client.PostResult(report);
}
}
}
|
flitzi/AC_SERVER_APPS
|
AC_ServiceClient/ACServiceSessionReportHandler.cs
|
C#
|
apache-2.0
| 494 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.runtime.webmonitor.utils;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.router.Handler;
import io.netty.handler.codec.http.router.Router;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.net.SSLUtils;
import org.apache.flink.runtime.webmonitor.HttpRequestHandler;
import org.apache.flink.runtime.webmonitor.PipelineErrorHandler;
import org.apache.flink.util.Preconditions;
import org.slf4j.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import java.io.File;
import java.net.InetSocketAddress;
/**
* This classes encapsulates the boot-strapping of netty for the web-frontend.
*/
public class WebFrontendBootstrap {
private final Router router;
private final Logger log;
private final File uploadDir;
private final SSLContext serverSSLContext;
private final ServerBootstrap bootstrap;
private final Channel serverChannel;
public WebFrontendBootstrap(
Router router,
Logger log,
File directory,
SSLContext sslContext,
String configuredAddress,
int configuredPort,
final Configuration config) throws InterruptedException {
this.router = Preconditions.checkNotNull(router);
this.log = Preconditions.checkNotNull(log);
this.uploadDir = directory;
this.serverSSLContext = sslContext;
ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
Handler handler = new Handler(WebFrontendBootstrap.this.router);
// SSL should be the first handler in the pipeline
if (serverSSLContext != null) {
SSLEngine sslEngine = serverSSLContext.createSSLEngine();
SSLUtils.setSSLVerAndCipherSuites(sslEngine, config);
sslEngine.setUseClientMode(false);
ch.pipeline().addLast("ssl", new SslHandler(sslEngine));
}
ch.pipeline()
.addLast(new HttpServerCodec())
.addLast(new ChunkedWriteHandler())
.addLast(new HttpRequestHandler(uploadDir))
.addLast(handler.name(), handler)
.addLast(new PipelineErrorHandler(WebFrontendBootstrap.this.log));
}
};
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
this.bootstrap = new ServerBootstrap();
this.bootstrap
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(initializer);
ChannelFuture ch;
if (configuredAddress == null) {
ch = this.bootstrap.bind(configuredPort);
} else {
ch = this.bootstrap.bind(configuredAddress, configuredPort);
}
this.serverChannel = ch.sync().channel();
InetSocketAddress bindAddress = (InetSocketAddress) serverChannel.localAddress();
String address = bindAddress.getAddress().getHostAddress();
int port = bindAddress.getPort();
this.log.info("Web frontend listening at {}" + ':' + "{}", address, port);
}
public ServerBootstrap getBootstrap() {
return bootstrap;
}
public int getServerPort() {
Channel server = this.serverChannel;
if (server != null) {
try {
return ((InetSocketAddress) server.localAddress()).getPort();
}
catch (Exception e) {
log.error("Cannot access local server port", e);
}
}
return -1;
}
public void shutdown() {
if (this.serverChannel != null) {
this.serverChannel.close().awaitUninterruptibly();
}
if (bootstrap != null) {
if (bootstrap.group() != null) {
bootstrap.group().shutdownGracefully();
}
if (bootstrap.childGroup() != null) {
bootstrap.childGroup().shutdownGracefully();
}
}
}
}
|
oscarceballos/flink-1.3.2
|
flink-runtime-web/src/main/java/org/apache/flink/runtime/webmonitor/utils/WebFrontendBootstrap.java
|
Java
|
apache-2.0
| 4,828 |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main() {
// [START cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* The project-specific location in which to generate random bytes.
* For example, "projects/my-project/locations/us-central1".
*/
// const location = 'abc123'
/**
* The length in bytes of the amount of randomness to retrieve. Minimum 8
* bytes, maximum 1024 bytes.
*/
// const lengthBytes = 1234
/**
* The ProtectionLevel google.cloud.kms.v1.ProtectionLevel to use when
* generating the random data. Currently, only
* HSM google.cloud.kms.v1.ProtectionLevel.HSM protection level is
* supported.
*/
// const protectionLevel = {}
// Imports the Kms library
const {KeyManagementServiceClient} = require('@google-cloud/kms').v1;
// Instantiates a client
const kmsClient = new KeyManagementServiceClient();
async function callGenerateRandomBytes() {
// Construct request
const request = {
};
// Run request
const response = await kmsClient.generateRandomBytes(request);
console.log(response);
}
callGenerateRandomBytes();
// [END cloudkms_v1_generated_KeyManagementService_GenerateRandomBytes_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
googleapis/nodejs-kms
|
samples/generated/v1/key_management_service.generate_random_bytes.js
|
JavaScript
|
apache-2.0
| 2,228 |
package ru.job4j.toDoList.model.dao;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import ru.job4j.toDoList.model.entity.Item;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
public class HiberStorage implements Storage {
private static final Logger LOGGER = LogManager.getLogger(HiberStorage.class);
private static AtomicInteger NEXT_ID = new AtomicInteger(-1);
private static final HiberStorage INSTANCE = new HiberStorage();
private final SessionFactory factory;
private HiberStorage() {
factory = new Configuration().configure().buildSessionFactory();
}
public static HiberStorage getInstance() {
return INSTANCE;
}
private <T> T tx(final Function<Session, T> command) {
final Session session = factory.openSession();
final Transaction tx = session.beginTransaction();
try {
return command.apply(session);
} catch (final Exception e) {
session.getTransaction().rollback();
throw e;
} finally {
tx.commit();
session.close();
}
}
@Override
public Item add(Item item) {
item.setId(NEXT_ID.getAndIncrement());
item.setCreated(new Timestamp(new Date().getTime()));
return tx(session -> {
session.save(item);
return item;
});
}
@Override
public Item update(Item item) {
return tx(session -> {
session.update(item);
return item;
});
}
@Override
public void delete(Item item) {
tx(session -> {
session.delete(item);
return null;
});
}
@Override
public List findAll() {
return tx(session -> session.createQuery("FROM Item i ORDER BY i.id").list());
}
@Override
public void doneItem(int id) {
tx(session -> {
Item item = session.get(Item.class, id);
item.setDone(true);
return null;
});
}
}
|
Mrsananabos/ashveytser
|
chapter_009/src/main/java/ru/job4j/toDoList/model/dao/HiberStorage.java
|
Java
|
apache-2.0
| 2,289 |
import { AbstractSimpleComponent } from './AbstractSimpleComponent';
import { AllowedTokens } from './AllowedTokens';
/**
* Scalar component used to represent a categorical value as a simple token
* identifying a term in a code space
*/
export class SweCategory extends AbstractSimpleComponent {
/**
* Value is optional, to enable structure to act as a schema for values
* provided using other encodings
*/
value: string;
/**
* Name of the dictionary where the possible values for this component are
* listed and defined
*/
codeSpace: string;
constraint: AllowedTokens;
}
|
autermann/smle
|
src/app/model/swe/SweCategory.ts
|
TypeScript
|
apache-2.0
| 604 |
package cn.com.warlock.wisp.core.plugin.processor.support.filter;
import cn.com.warlock.wisp.core.dto.MysqlEntryWrap;
import cn.com.warlock.wisp.core.exception.WispProcessorException;
public interface IEntryFilterChain {
void doFilter(MysqlEntryWrap entry) throws WispProcessorException;
}
|
warlock-china/wisp
|
wisp-core/src/main/java/cn/com/warlock/wisp/core/plugin/processor/support/filter/IEntryFilterChain.java
|
Java
|
apache-2.0
| 298 |
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codenergic.theskeleton.post;
import org.codenergic.theskeleton.core.data.AuditingEntityRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface PostRepository extends AuditingEntityRepository<PostEntity> {
Page<PostEntity> findByPosterId(String posterId, Pageable pageable);
Page<PostEntity> findByResponseToId(String postId, Pageable pageable);
@Query("from PostEntity p where p.content like %?1% order by p.createdDate desc")
Page<PostEntity> findByContentContaining(String title, Pageable pageable);
}
|
codenergic/theskeleton
|
src/main/java/org/codenergic/theskeleton/post/PostRepository.java
|
Java
|
apache-2.0
| 1,323 |
/*
* Copyright 2016 Bear Giles <bgiles@coyotesong.com>
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.coyotesong.demo.cxf;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan("com.coyotesong.demo.cxf")
public class ApacheCxfWss4jApplication implements ApplicationContextAware {
private static ApplicationContext ctx;
public void setApplicationContext(ApplicationContext ctx) {
this.ctx = ctx;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) ctx.getBean(name);
}
public static void main(String[] args) {
SpringApplication.run(ApacheCxfWss4jApplication.class, args);
}
}
|
beargiles/cheat-sheet
|
webservices/Apache-CXF/apache-cxf-wss4j-interceptors/src/main/java/com/coyotesong/demo/cxf/ApacheCxfWss4jApplication.java
|
Java
|
apache-2.0
| 1,721 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 DBeaver Corp and others
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.model;
/**
* Virtual object.
* Object which doesn't exist in database but exist on client side.
* Virtual schemas can be created for some drivers (e.g. Phoenix)
*/
public interface DBPVirtualObject
{
boolean isVirtual();
}
|
Sargul/dbeaver
|
plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/DBPVirtualObject.java
|
Java
|
apache-2.0
| 917 |
try
{
if (Koadic.JOBKEY != "stage")
{
if (Koadic.isHTA())
{
//HKCU\SOFTWARE\Microsoft\Internet Explorer\Style\MaxScriptStatements = 0xFFFFFFFF
var path = "SOFTWARE\\Microsoft\\Internet Explorer\\Styles";
var key = "MaxScriptStatements";
Koadic.registry.write(Koadic.registry.HKCU, path, key, 0xFFFFFFFF, Koadic.registry.DWORD);
}
Koadic.work.report(Koadic.user.info());
try {
Koadic.work.fork("");
} catch (e) {
Koadic.work.error(e)
}
Koadic.exit();
}
else
{
if (Koadic.isHTA())
DoWorkTimeout();
else
DoWorkLoop();
}
}
catch (e)
{
// todo: critical error reporting
Koadic.work.error(e);
}
function DoWork()
{
var epoch = new Date().getTime();
var expire = parseInt(Koadic.EXPIRE);
if (epoch > expire)
{
return false;
}
try
{
var work = Koadic.work.get();
// 201 = x64 or x86
// 202 = force x86
if (work.status == 501 || work.status == 502)
{
if (work.responseText.length > 0) {
var jobkey = work.responseText;
Koadic.work.fork(jobkey, work.status == 502);
}
}
else // if (work.status == 500) // kill code
{
return false;
}
}
catch (e)
{
return false;
}
return true;
}
function DoWorkLoop()
{
while (DoWork())
;
Koadic.exit();
}
function DoWorkTimeout()
{
for (var i = 0; i < 10; ++i)
{
if (!DoWork())
{
Koadic.exit();
return;
}
}
//window.setTimeout(DoWorkTimeoutCallback, 0);
Koadic.work.fork("");
Koadic.exit();
}
|
zerosum0x0/koadic
|
data/stager/js/stage.js
|
JavaScript
|
apache-2.0
| 1,812 |
package profitbricks
import (
"context"
"github.com/ionos-cloud/sdk-go/v5"
"net/http"
)
// Lan object
type Lan struct {
ID string `json:"id,omitempty"`
PBType string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Metadata *Metadata `json:"metadata,omitempty"`
Properties LanProperties `json:"properties,omitempty"`
Entities *LanEntities `json:"entities,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"statuscode,omitempty"`
}
// LanProperties object
type LanProperties struct {
Name string `json:"name,omitempty"`
Public bool `json:"public,omitempty"`
IPFailover *[]IPFailover `json:"ipFailover,omitempty"`
PCC string `json:"pcc,omitempty"`
}
// LanEntities object
type LanEntities struct {
Nics *LanNics `json:"nics,omitempty"`
}
// IPFailover object
type IPFailover struct {
NicUUID string `json:"nicUuid,omitempty"`
IP string `json:"ip,omitempty"`
}
// LanNics object
type LanNics struct {
ID string `json:"id,omitempty"`
PBType string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Nic `json:"items,omitempty"`
}
// Lans object
type Lans struct {
ID string `json:"id,omitempty"`
PBType string `json:"type,omitempty"`
Href string `json:"href,omitempty"`
Items []Lan `json:"items,omitempty"`
Response string `json:"Response,omitempty"`
Headers *http.Header `json:"headers,omitempty"`
StatusCode int `json:"statuscode,omitempty"`
}
// ListLans returns a Collection for lans in the Datacenter
func (c *Client) ListLans(dcid string) (*Lans, error) {
ctx, cancel := c.GetContext()
if cancel != nil {
defer cancel()
}
rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansGet(ctx, dcid).Execute()
ret := Lans{}
if errConvert := convertToCompat(&rsp, &ret); errConvert != nil {
return nil, errConvert
}
fillInResponse(&ret, apiResponse)
return &ret, err
/*
url := lansPath(dcid)
ret := &Lans{}
err := c.Get(url, ret, http.StatusOK)
return ret, err
*/
}
// CreateLan creates a lan in the datacenter
// from a jason []byte and returns a Instance struct
func (c *Client) CreateLan(dcid string, request Lan) (*Lan, error) {
input := ionoscloud.LanPost{}
if errConvert := convertToCore(&request, &input); errConvert != nil {
return nil, errConvert
}
ctx, cancel := c.GetContext()
if cancel != nil {
defer cancel()
}
rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansPost(ctx, dcid).Lan(input).Execute()
ret := Lan{}
if errConvert := convertToCompat(&rsp, &ret); errConvert != nil {
return nil, errConvert
}
fillInResponse(&ret, apiResponse)
return &ret, err
/*
url := lansPath(dcid)
ret := &Lan{}
err := c.Post(url, request, ret, http.StatusAccepted)
return ret, err
*/
}
// CreateLanAndWait creates a lan, waits for the request to finish and returns a refreshed lan
// Note that an error does not necessarily means that the resource has not been created.
// If err & res are not nil, a resource with res.ID exists, but an error occurred either while waiting for
// the request or when refreshing the resource.
func (c *Client) CreateLanAndWait(ctx context.Context, dcid string, request Lan) (res *Lan, err error) {
res, err = c.CreateLan(dcid, request)
if err != nil {
return
}
if err = c.WaitTillProvisionedOrCanceled(ctx, res.Headers.Get("location")); err != nil {
return
}
var lan *Lan
if lan, err = c.GetLan(dcid, res.ID); err != nil {
return
} else {
return lan, err
}
}
// GetLan pulls data for the lan where id = lanid returns an Instance struct
func (c *Client) GetLan(dcid, lanid string) (*Lan, error) {
ctx, cancel := c.GetContext()
if cancel != nil {
defer cancel()
}
rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansFindById(ctx, dcid, lanid).Execute()
ret := Lan{}
if errConvert := convertToCompat(&rsp, &ret); errConvert != nil {
return nil, errConvert
}
fillInResponse(&ret, apiResponse)
return &ret, err
/*
url := lanPath(dcid, lanid)
ret := &Lan{}
err := c.Get(url, ret, http.StatusOK)
return ret, err
*/
}
// UpdateLan does a partial update to a lan using json from []byte json returns a Instance struct
func (c *Client) UpdateLan(dcid string, lanid string, obj LanProperties) (*Lan, error) {
input := ionoscloud.LanProperties{}
if errConvert := convertToCore(&obj, &input); errConvert != nil {
return nil, errConvert
}
ctx, cancel := c.GetContext()
if cancel != nil {
defer cancel()
}
rsp, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansPatch(ctx, dcid, lanid).Lan(input).Execute()
ret := Lan{}
if errConvert := convertToCompat(&rsp, &ret); errConvert != nil {
return nil, errConvert
}
fillInResponse(&ret, apiResponse)
return &ret, err
/*
url := lanPath(dcid, lanid)
ret := &Lan{}
err := c.Patch(url, obj, ret, http.StatusAccepted)
return ret, err
*/
}
// UpdateLanAndWait creates a lan, waits for the request to finish and returns a refreshed lan
// Note that an error does not necessarily means that the resource has not been updated.
// If err & res are not nil, a resource with res.ID exists, but an error occurred either while waiting for
// the request or when refreshing the resource.
func (c *Client) UpdateLanAndWait(ctx context.Context, dcid, lanid string, props LanProperties) (res *Lan, err error) {
res, err = c.UpdateLan(dcid, lanid, props)
if err != nil {
return
}
if err = c.WaitTillProvisionedOrCanceled(ctx, res.Headers.Get("location")); err != nil {
return
}
var lan *Lan
if lan, err = c.GetLan(dcid, res.ID); err != nil {
return
} else {
return lan, err
}
}
// DeleteLan deletes a lan where id == lanid
func (c *Client) DeleteLan(dcid, lanid string) (*http.Header, error) {
ctx, cancel := c.GetContext()
if cancel != nil {
defer cancel()
}
_, apiResponse, err := c.CoreSdk.LanApi.DatacentersLansDelete(ctx, dcid, lanid).Execute()
if apiResponse != nil {
return &apiResponse.Header, err
} else {
return nil, err
}
/*
url := lanPath(dcid, lanid)
ret := &http.Header{}
err := c.Delete(url, ret, http.StatusAccepted)
return ret, err
*/
}
// DeleteLanAndWait deletes given lan and waits for the request to finish
func (c *Client) DeleteLanAndWait(ctx context.Context, dcid, lanid string) error {
rsp, err := c.DeleteLan(dcid, lanid)
if err != nil {
return err
}
return c.WaitTillProvisionedOrCanceled(ctx, rsp.Get("location"))
}
|
profitbricks/profitbricks-sdk-go
|
lan.go
|
GO
|
apache-2.0
| 6,599 |
package me.wangkang.spring.messaging;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
|
iwangkang/spring
|
spring-framework-example/spring-messaging-example/src/main/java/me/wangkang/spring/messaging/App.java
|
Java
|
apache-2.0
| 191 |
package com.hiwhitley.chapter01;
/**
* Created by hiwhitley on 2016/10/27.
*/
public class Pet {
private String type;
public Pet(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
|
hiwhitley/CodingEveryDay
|
src/com/hiwhitley/chapter01/Pet.java
|
Java
|
apache-2.0
| 248 |
/*
* Copyright 2016 Black Duck Software, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blackducksoftware.ohcount4j;
import java.util.ArrayList;
import java.util.List;
import com.blackducksoftware.ohcount4j.scan.ActionScriptScanner;
import com.blackducksoftware.ohcount4j.scan.AdaScanner;
import com.blackducksoftware.ohcount4j.scan.AssemblyScanner;
import com.blackducksoftware.ohcount4j.scan.AugeasScanner;
import com.blackducksoftware.ohcount4j.scan.AutoconfScanner;
import com.blackducksoftware.ohcount4j.scan.AutomakeScanner;
import com.blackducksoftware.ohcount4j.scan.AwkScanner;
import com.blackducksoftware.ohcount4j.scan.BatScanner;
import com.blackducksoftware.ohcount4j.scan.BfkScanner;
import com.blackducksoftware.ohcount4j.scan.BfkppScanner;
import com.blackducksoftware.ohcount4j.scan.BinaryScanner;
import com.blackducksoftware.ohcount4j.scan.BlitzMaxScanner;
import com.blackducksoftware.ohcount4j.scan.BooScanner;
import com.blackducksoftware.ohcount4j.scan.CMakeScanner;
import com.blackducksoftware.ohcount4j.scan.CStyleScanner;
import com.blackducksoftware.ohcount4j.scan.ClearSilverTemplateScanner;
import com.blackducksoftware.ohcount4j.scan.ClojureScanner;
import com.blackducksoftware.ohcount4j.scan.CobolScanner;
import com.blackducksoftware.ohcount4j.scan.CoffeeScriptScanner;
import com.blackducksoftware.ohcount4j.scan.ColdFusionScanner;
import com.blackducksoftware.ohcount4j.scan.CoqScanner;
import com.blackducksoftware.ohcount4j.scan.DScanner;
import com.blackducksoftware.ohcount4j.scan.DclScanner;
import com.blackducksoftware.ohcount4j.scan.EiffelScanner;
import com.blackducksoftware.ohcount4j.scan.ElixirScanner;
import com.blackducksoftware.ohcount4j.scan.ErlangScanner;
import com.blackducksoftware.ohcount4j.scan.FSharpScanner;
import com.blackducksoftware.ohcount4j.scan.FactorScanner;
import com.blackducksoftware.ohcount4j.scan.ForthScanner;
import com.blackducksoftware.ohcount4j.scan.FortranFixedScanner;
import com.blackducksoftware.ohcount4j.scan.FortranFreeScanner;
import com.blackducksoftware.ohcount4j.scan.GenericCodeScanner;
import com.blackducksoftware.ohcount4j.scan.HTMLScanner;
import com.blackducksoftware.ohcount4j.scan.HamlScanner;
import com.blackducksoftware.ohcount4j.scan.HaskellScanner;
import com.blackducksoftware.ohcount4j.scan.IdlPvwaveScanner;
import com.blackducksoftware.ohcount4j.scan.JspScanner;
import com.blackducksoftware.ohcount4j.scan.LispScanner;
import com.blackducksoftware.ohcount4j.scan.LogtalkScanner;
import com.blackducksoftware.ohcount4j.scan.LuaScanner;
import com.blackducksoftware.ohcount4j.scan.MakeScanner;
import com.blackducksoftware.ohcount4j.scan.MathematicaScanner;
import com.blackducksoftware.ohcount4j.scan.MatlabScanner;
import com.blackducksoftware.ohcount4j.scan.MetapostWithTexScanner;
import com.blackducksoftware.ohcount4j.scan.MetafontScanner;
import com.blackducksoftware.ohcount4j.scan.ModulaScanner;
import com.blackducksoftware.ohcount4j.scan.OCamlScanner;
import com.blackducksoftware.ohcount4j.scan.PascalScanner;
import com.blackducksoftware.ohcount4j.scan.PerlScanner;
import com.blackducksoftware.ohcount4j.scan.PhpScanner;
import com.blackducksoftware.ohcount4j.scan.PrologScanner;
import com.blackducksoftware.ohcount4j.scan.PythonScanner;
import com.blackducksoftware.ohcount4j.scan.RebolScanner;
import com.blackducksoftware.ohcount4j.scan.RexxScanner;
import com.blackducksoftware.ohcount4j.scan.RubyScanner;
import com.blackducksoftware.ohcount4j.scan.Scanner;
import com.blackducksoftware.ohcount4j.scan.SchemeScanner;
import com.blackducksoftware.ohcount4j.scan.ShellScanner;
import com.blackducksoftware.ohcount4j.scan.SmalltalkScanner;
import com.blackducksoftware.ohcount4j.scan.SqlScanner;
import com.blackducksoftware.ohcount4j.scan.TclScanner;
import com.blackducksoftware.ohcount4j.scan.TexScanner;
import com.blackducksoftware.ohcount4j.scan.VimScriptScanner;
import com.blackducksoftware.ohcount4j.scan.VisualBasicScanner;
import com.blackducksoftware.ohcount4j.scan.XmlScanner;
public enum Language implements LanguageCategory {
/*
* All languages must be defined here.
*
* Each language must declare three mandatory properties:
*
* - The language's official display name (niceName)
* - The category of the language, one of BUILD, LOGIC, MARKUP, UNKNOWN
* - A Scanner subclass capable of parsing this language
*/
ACTIONSCRIPT("ActionScript", LOGIC, ActionScriptScanner.class),
ADA("Ada", LOGIC, AdaScanner.class),
ASPX_CSHARP("ASP.NET (C#)", LOGIC, GenericCodeScanner.class), // TODO.
ASPX_VB("ASP.NET (VB)", LOGIC, GenericCodeScanner.class), // TODO.
ASSEMBLY("Assembly", LOGIC, AssemblyScanner.class),
AUGEAS("Augeas", LOGIC, AugeasScanner.class),
AUTOCONF("Autoconf", BUILD, AutoconfScanner.class),
AUTOMAKE("Automake", BUILD, AutomakeScanner.class),
AWK("Awk", LOGIC, AwkScanner.class),
BAT("Windows Batch", LOGIC, BatScanner.class),
BFPP("Brainfuck++", LOGIC, BfkppScanner.class),
BINARY("Binary", LOGIC, BinaryScanner.class),
BLITZMAX("BlitzMax", LOGIC, BlitzMaxScanner.class),
BOO("Boo", LOGIC, BooScanner.class),
BRAINFUCK("Brainfuck", LOGIC, BfkScanner.class),
C("C", LOGIC, CStyleScanner.class),
CHAISCRIPT("ChaiScript", LOGIC, CStyleScanner.class),
CLASSIC_BASIC("Classic BASIC", LOGIC, GenericCodeScanner.class), // TODO.
CLEARSILVER("ClearSilver", LOGIC, ClearSilverTemplateScanner.class),
CLOJURE("Clojure", LOGIC, ClojureScanner.class),
COBOL("COBOL", LOGIC, CobolScanner.class),
COFFEESCRIPT("CoffeeScript", LOGIC, CoffeeScriptScanner.class),
COLDFUSION("ColdFusion", MARKUP, ColdFusionScanner.class),
CPP("C++", LOGIC, CStyleScanner.class),
CMake("CMake", BUILD, CMakeScanner.class),
CSHARP("C#", LOGIC, CStyleScanner.class),
COQ("Coq", LOGIC, CoqScanner.class),
CSS("CSS", MARKUP, CStyleScanner.class),
CUDA("CUDA", LOGIC, CStyleScanner.class),
D("D", LOGIC, DScanner.class),
DYLAN("Dylan", LOGIC, CStyleScanner.class),
DCL("DCL", LOGIC, DclScanner.class),
EBUILD("Ebuild", BUILD, ShellScanner.class),
EC("eC", LOGIC, CStyleScanner.class),
ECMASCRIPT("ECMAScript", LOGIC, CStyleScanner.class),
EIFFEL("Eiffel", LOGIC, EiffelScanner.class),
ELIXIR("Elixir", LOGIC, ElixirScanner.class),
EMACSLISP("Emacs Lisp", LOGIC, LispScanner.class),
ERLANG("Erlang", LOGIC, ErlangScanner.class),
FACTOR("Factor", LOGIC, FactorScanner.class),
EXHERES("Exheres", LOGIC, ShellScanner.class),
FORTH("Forth", LOGIC, ForthScanner.class),
FORTRANFIXED("Fortran (Fixed-Format)", LOGIC, FortranFixedScanner.class),
FORTRANFREE("Fortran (Free-Format)", LOGIC, FortranFreeScanner.class),
FSHARP("F#", LOGIC, FSharpScanner.class),
GENIE("Genie", LOGIC, CStyleScanner.class),
GLSL("OpenGL Shading Language", LOGIC, CStyleScanner.class),
GOLANG("Go", LOGIC, CStyleScanner.class),
GROOVY("Groovy", LOGIC, CStyleScanner.class),
HAML("Haml", MARKUP, HamlScanner.class),
HAXE("HaXe", LOGIC, CStyleScanner.class),
HTML("HTML", MARKUP, HTMLScanner.class),
HASKELL("Haskell", LOGIC, HaskellScanner.class),
IDL_PVWAVE("IDL/PV-WAVE/GDL", LOGIC, IdlPvwaveScanner.class),
JAM("Jam", BUILD, ShellScanner.class),
JAVA("Java", LOGIC, CStyleScanner.class),
JAVASCRIPT("JavaScript", LOGIC, CStyleScanner.class),
JSP("JSP", LOGIC, JspScanner.class),
KOTLIN("Kotlin", LOGIC, CStyleScanner.class),
LIMBO("Limbo", LOGIC, CStyleScanner.class),
LISP("Lisp", LOGIC, LispScanner.class),
LOGTALK("Logtalk", LOGIC, LogtalkScanner.class),
LUA("Lua", LOGIC, LuaScanner.class),
MAKE("Make", BUILD, MakeScanner.class),
MATHEMATICA("Mathematica", LOGIC, MathematicaScanner.class),
MATLAB("Matlab", LOGIC, MatlabScanner.class),
METAPOST("MetaPost", MARKUP, MetapostWithTexScanner.class),
METAFONT("MetaFont", MARKUP, MetafontScanner.class),
MODULA2("Modula 2", LOGIC, ModulaScanner.class),
MODULA3("Modula 3", LOGIC, ModulaScanner.class),
OBJECTIVE_C("Objective-C", LOGIC, CStyleScanner.class),
OCAML("OCaml", LOGIC, OCamlScanner.class),
OCTAVE("Octave", LOGIC, MatlabScanner.class), // TODO. Octave also supports # comments
PASCAL("Pascal", LOGIC, PascalScanner.class),
PERL("Perl", LOGIC, PerlScanner.class),
PHP("Php", LOGIC, PhpScanner.class),
PUPPET("Puppet", LOGIC, GenericCodeScanner.class), // TODO.
PROLOG("Prolog", LOGIC, PrologScanner.class),
PYTHON("Python", LOGIC, PythonScanner.class),
R("R", LOGIC, GenericCodeScanner.class), // TODO.
REBOL("REBOL", LOGIC, RebolScanner.class),
REXX("Rexx", LOGIC, RexxScanner.class),
RUBY("Ruby", LOGIC, RubyScanner.class),
SCALA("Scala", LOGIC, CStyleScanner.class),
SWIFT("Swift", LOGIC, CStyleScanner.class),
SCHEME("Scheme", LOGIC, SchemeScanner.class),
SHELL("Shell", LOGIC, ShellScanner.class),
SMALLTALK("Smalltalk", LOGIC, SmalltalkScanner.class),
SQL("SQL", LOGIC, SqlScanner.class),
STRUCTURED_BASIC("Structured Basic", LOGIC, VisualBasicScanner.class),
TCL("Tcl", LOGIC, TclScanner.class),
TEX("TeX/LaTeX", MARKUP, TexScanner.class),
UNKNOWN("Unknown", CATEGORY_UNKNOWN, GenericCodeScanner.class),
VB("VisualBasic", LOGIC, VisualBasicScanner.class),
VBSCRIPT("VBScript", LOGIC, VisualBasicScanner.class),
VIMSCRIPT("Vimscript", LOGIC, VimScriptScanner.class),
XML("XML", MARKUP, XmlScanner.class),
XMLSCHEMA("XML Schema", MARKUP, XmlScanner.class),
XSLT("XSL Transformation", MARKUP, XmlScanner.class);
/*
* Optional properties of languages are declared here.
*
* At a minimum, a language should define one or more file
* extensions or filenames associated with the language.
*
* You may also declare additional names (beyond the uname
* and niceName) by which the language might be known.
* These aliases can be matched against things like Emacs
* mode headers or shebang directives.
*/
static {
ACTIONSCRIPT.extension("as");
ADA.extensions("ada", "adb");
ASPX_CSHARP.extension("aspx");
ASPX_VB.extension("aspx");
ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80");
AUGEAS.extensions("aug");
AUTOCONF.extensions("autoconf", "ac", "m4"); // m4 (unix macro processor)
AUTOMAKE.extensions("am");
AWK.extension("awk");
BAT.extension("bat");
BFPP.extensions("bfpp");
BINARY.extensions("inc", "st");
BLITZMAX.extension("bmx");
BOO.extension("boo");
BRAINFUCK.extension("bf");
C.extensions("c", "h");
CHAISCRIPT.extension("chai");
CLASSIC_BASIC.extensions("b", "bas");
CLEARSILVER.extension("cs");
CLOJURE.extensions("clj", "cljs", "cljc");
CMake.extensions("cmake").filename("CMakeLists.txt");
COBOL.extension("cbl");
COFFEESCRIPT.extension("coffee");
COLDFUSION.extensions("cfc", "cfm");
CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx");
COQ.extension("v");
CSHARP.aliases("C#", "cs").extension("cs");
CSS.extension("css");
CUDA.extensions("cu", "cuh");
D.extension("d");
DYLAN.extension("dylan");
DCL.extension("com");
EBUILD.extensions("ebuild", "kdebuild-1", "eclass");
EC.extensions("ec", "eh");
ECMASCRIPT.extension("es");
EIFFEL.extension("e");
ELIXIR.extensions("ex", "exs");
EMACSLISP.extension("el");
ERLANG.extension("erl");
EXHERES.extensions("exheres-0", "exheres-1", "exlib");
FACTOR.extension("factor");
FORTH.extensions("fr", "4th");
FORTRANFIXED.extensions("i", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FORTRANFREE.extensions("i90", "f", "f03", "f08", "f77", "f90", "f95", "for", "fpp", "ftn");
FSHARP.extension("fs");
GENIE.extension("gs");
GLSL.extensions("frag", "glsl", "vert");
GOLANG.extensions("go");
GROOVY.extension("groovy");
HAML.extension("haml");
HAXE.extension("hx");
HTML.extensions("htm", "html");
HASKELL.extensions("hs", "lhs");
JAM.filenames("Jamfile", "Jamrules");
JAVA.extension("java");
JAVASCRIPT.alias("js").extension("js");
JSP.extension("jsp");
KOTLIN.extensions("kt", "kts");
LIMBO.extensions("b", "m");
LOGTALK.extension("lgt");
LUA.extension("lua");
MAKE.filename("Makefile").extensions("mk", "pro");
MATHEMATICA.extensions("nb", "nbs");
METAPOST.extension("mp");
METAFONT.extensions("mf");
MODULA2.extensions("mod", "m2");
MODULA3.extensions("m3", "i3");
OBJECTIVE_C.extensions("m", "h");
OCAML.extensions("ml", "mli");
OCTAVE.extensions("m", "octave");
PASCAL.extensions("pas", "pp");
PERL.extensions("pl", "pm");
PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps");
IDL_PVWAVE.extension("pro");
PROLOG.extension("pl");
PUPPET.extension("pp");
PYTHON.extension("py");
R.extension("r");
REBOL.extensions("r", "r3", "reb", "rebol");
REXX.extensions("cmd", "exec", "rexx");
RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile");
SCALA.extensions("scala", "sc");
SWIFT.extensions("swift");
SCHEME.extensions("scm", "ss");
SHELL.extensions("bash", "sh");
SMALLTALK.extension("st");
SQL.extension("sql");
STRUCTURED_BASIC.extensions("b", "bas", "bi");
TCL.extension("tcl");
TEX.extension("tex");
VB.extensions("bas", "frm", "frx", "vb", "vba");
VBSCRIPT.extensions("vbs", "vbe");
VIMSCRIPT.extension("vim").aliases("Vim Script", "VimL");
XML.extensions("asx", "csproj", "xml", "mxml");
XMLSCHEMA.extension("xsd");
XSLT.extensions("xsl", "xslt");
}
private final String niceName;
private final String category;
private final Class<? extends Scanner> scannerClass;
private final List<String> extensions;
private final List<String> filenames;
private final List<String> aliases;
Language(String niceName, String category, Class<? extends Scanner> scannerClass) {
this.niceName = niceName;
this.category = category;
this.scannerClass = scannerClass;
extensions = new ArrayList<String>();
filenames = new ArrayList<String>();
aliases = new ArrayList<String>();
}
public String uname() {
return toString().toLowerCase();
}
public String niceName() {
return niceName;
}
public String category() {
return category;
}
public Class<? extends Scanner> scannerClass() {
return scannerClass;
}
public Scanner makeScanner() {
try {
Scanner scanner = scannerClass.newInstance();
scanner.setDefaultLanguage(this);
return scanner;
} catch (InstantiationException e) {
throw new OhcountException(e);
} catch (IllegalAccessException e) {
throw new OhcountException(e);
}
}
private Language extension(String ext) {
extensions.add(ext);
return this;
}
private Language extensions(String... exts) {
for (String ext : exts) {
extension(ext);
}
return this;
}
public List<String> getExtensions() {
return new ArrayList<String>(extensions);
}
private Language filename(String filename) {
filenames.add(filename);
return this;
}
private Language filenames(String... filenames) {
for (String filename : filenames) {
filename(filename);
}
return this;
}
public List<String> getFilenames() {
return new ArrayList<String>(filenames);
}
private Language alias(String alias) {
aliases.add(alias);
return this;
}
private Language aliases(String... aliases) {
for (String alias : aliases) {
alias(alias);
}
return this;
}
public List<String> getAliases() {
return new ArrayList<String>(aliases);
}
}
|
blackducksoftware/ohcount4j
|
src/main/java/com/blackducksoftware/ohcount4j/Language.java
|
Java
|
apache-2.0
| 16,986 |
package pl.itdonat.demo.wsfbd.encryption;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import pl.itdonat.demo.wsfbd.encryption.encode.EncodeData;
import pl.itdonat.demo.wsfbd.encryption.encode.EncodeService;
import java.util.List;
/**
* Created by r.szarejko on 2017-03-22.
*/
@Controller
@RequestMapping("/crypto")
public class CryptoController {
private final EncodeService encodeService;
public CryptoController(EncodeService encodeService) {
this.encodeService = encodeService;
}
@GetMapping
public String get(Model model){
model.addAttribute("plainText", "");
return "crypto";
}
@PostMapping
public String post(Model model, @RequestParam String plainText){
List<EncodeData> encodeData = encodeService.prepareEncodedValueByAlgorithmMap(plainText);
model.addAttribute("valueList", encodeData);
model.addAttribute("plainText", plainText);
return "crypto";
}
@PostMapping("/broke")
@ResponseBody
public String postBroke(@RequestParam String hash, @RequestParam Algorithm algorithm){
String bruteForce = encodeService.bruteForce(hash, algorithm);
return bruteForce;
}
@GetMapping("/broke1")
@ResponseBody
public String postBroke(Model model){
return "7654321";
}
}
|
RobertSzarejko/WebSecurityForBackendDev
|
web-security-demo/src/main/java/pl/itdonat/demo/wsfbd/encryption/CryptoController.java
|
Java
|
apache-2.0
| 1,419 |
/**
* Copyright 2011-2021 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.operator;
import java.text.MessageFormat;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import javax.annotation.Generated;
import javax.lang.model.SourceVersion;
import com.asakusafw.operator.description.AnnotationDescription;
import com.asakusafw.operator.description.ClassDescription;
import com.asakusafw.operator.description.Descriptions;
import com.asakusafw.operator.description.ValueDescription;
/**
* Available constant values in this project.
* @since 0.9.0
* @version 0.9.1
*/
public final class Constants {
private static final String BASE = "com.asakusafw.vocabulary."; //$NON-NLS-1$
private static ClassDescription classOf(String name) {
return new ClassDescription(BASE + name);
}
/**
* {@code OperatorHelper} annotation type name.
*/
public static final ClassDescription TYPE_ANNOTATION_HELPER = classOf("operator.OperatorHelper"); //$NON-NLS-1$
/**
* {@code In} type name.
*/
public static final ClassDescription TYPE_IN = classOf("flow.In"); //$NON-NLS-1$
/**
* {@code Out} type name.
*/
public static final ClassDescription TYPE_OUT = classOf("flow.Out"); //$NON-NLS-1$
/**
* {@code Source} type name.
*/
public static final ClassDescription TYPE_SOURCE = classOf("flow.Source"); //$NON-NLS-1$
/**
* {@code View} type name.
* @since 0.9.1
*/
public static final ClassDescription TYPE_VIEW =
new ClassDescription("com.asakusafw.runtime.core.View"); //$NON-NLS-1$
/**
* {@code GroupView} type name.
* @since 0.9.1
*/
public static final ClassDescription TYPE_GROUP_VIEW =
new ClassDescription("com.asakusafw.runtime.core.GroupView"); //$NON-NLS-1$
/**
* {@code Result} type name.
*/
public static final ClassDescription TYPE_RESULT =
new ClassDescription("com.asakusafw.runtime.core.Result"); //$NON-NLS-1$
/**
* {@code Key} type name.
*/
public static final ClassDescription TYPE_KEY = classOf("model.Key"); //$NON-NLS-1$
/**
* {@code Joined} type name.
*/
public static final ClassDescription TYPE_JOINED = classOf("model.Joined"); //$NON-NLS-1$
/**
* {@code Summarized} type name.
*/
public static final ClassDescription TYPE_SUMMARIZED = classOf("model.Summarized"); //$NON-NLS-1$
/**
* {@code FlowPart} annotation type name.
*/
public static final ClassDescription TYPE_FLOW_PART = classOf("flow.FlowPart"); //$NON-NLS-1$
/**
* {@code FlowDescription} type name.
*/
public static final ClassDescription TYPE_FLOW_DESCRIPTION = classOf("flow.FlowDescription"); //$NON-NLS-1$
/**
* {@code Import} type name.
*/
public static final ClassDescription TYPE_IMPORT = classOf("flow.Import"); //$NON-NLS-1$
/**
* {@code Export} type name.
*/
public static final ClassDescription TYPE_EXPORT = classOf("flow.Export"); //$NON-NLS-1$
/**
* {@code ImporterDescription} type name.
*/
public static final ClassDescription TYPE_IMPORTER_DESC = classOf("external.ImporterDescription"); //$NON-NLS-1$
/**
* {@code ExporterDescription} type name.
*/
public static final ClassDescription TYPE_EXPORTER_DESC = classOf("external.ExporterDescription"); //$NON-NLS-1$
/**
* {@code FlowElementBuilder} type name.
*/
public static final ClassDescription TYPE_ELEMENT_BUILDER =
classOf("flow.builder.FlowElementBuilder"); //$NON-NLS-1$
/**
* singleton name of flow-part factory method.
*/
public static final String NAME_FLOW_PART_FACTORY_METHOD = "create"; //$NON-NLS-1$
/**
* Simple name pattern for operator implementation class (0: simple name of operator class).
*/
private static final String PATTERN_IMPLEMENTATION_CLASS = "{0}Impl"; //$NON-NLS-1$
/**
* Simple name pattern for operator factory class (0: simple name of operator/flow-part class).
*/
private static final String PATTERN_FACTORY_CLASS = "{0}Factory"; //$NON-NLS-1$
/**
* Simple name pattern for built-in operator annotation class (0: simple name).
*/
private static final String PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS = BASE + "operator.{0}"; //$NON-NLS-1$
/**
* The generator ID.
*/
public static final String GENERATOR_ID = "com.asakusafw.operator"; //$NON-NLS-1$
/**
* The generator name.
*/
public static final String GENERATOR_NAME = "Asakusa Operator DSL Compiler"; //$NON-NLS-1$
/**
* The generator version.
*/
public static final String GENERATOR_VERSION = "3.0.0"; //$NON-NLS-1$
/**
* Returns the implementation class name of target class with the specified name.
* @param simpleName the simple class name of the operator annotation
* @return qualified name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getBuiltinOperatorClass(String simpleName) {
Objects.requireNonNull(simpleName, "simpleName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_BUILTIN_OPERATOR_ANNOTATION_CLASS, simpleName));
}
/**
* Returns the implementation class name of target class with the specified name.
* @param originalName the original class name
* @return related implementation class name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getImplementationClass(CharSequence originalName) {
Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_IMPLEMENTATION_CLASS, originalName));
}
/**
* Returns the factory class name of target class with the specified name.
* @param originalName the original class name
* @return related factory class name
* @throws IllegalArgumentException if some parameters were {@code null}
*/
public static ClassDescription getFactoryClass(CharSequence originalName) {
Objects.requireNonNull(originalName, "originalName must not be null"); //$NON-NLS-1$
return new ClassDescription(MessageFormat.format(PATTERN_FACTORY_CLASS, originalName));
}
/**
* Returns the current supported source version.
* @return the supported version
*/
public static SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
/**
* Returns {@link Generated} annotation.
* @return the annotation
*/
public static AnnotationDescription getGenetedAnnotation() {
Map<String, ValueDescription> elements = new LinkedHashMap<>();
elements.put("value", Descriptions.valueOf(new String[] { //$NON-NLS-1$
GENERATOR_ID
}));
elements.put("comments", //$NON-NLS-1$
Descriptions.valueOf(MessageFormat.format(
"generated by {0} {1}", //$NON-NLS-1$
GENERATOR_NAME, GENERATOR_VERSION)));
return new AnnotationDescription(Descriptions.classOf(Generated.class), elements);
}
private Constants() {
return;
}
}
|
asakusafw/asakusafw
|
operator/core/src/main/java/com/asakusafw/operator/Constants.java
|
Java
|
apache-2.0
| 8,005 |
<?php
/**
* This file is part of the SevenShores/NetSuite library
* AND originally from the NetSuite PHP Toolkit.
*
* New content:
* @package ryanwinchester/netsuite-php
* @copyright Copyright (c) Ryan Winchester
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
* @link https://github.com/ryanwinchester/netsuite-php
*
* Original content:
* @copyright Copyright (c) NetSuite Inc.
* @license https://raw.githubusercontent.com/ryanwinchester/netsuite-php/master/original/NetSuite%20Application%20Developer%20License%20Agreement.txt
* @link http://www.netsuite.com/portal/developers/resources/suitetalk-sample-applications.shtml
*
* generated: 2019-06-12 10:27:00 AM PDT
*/
namespace NetSuite\Classes;
class FairValuePriceSearchBasic extends SearchRecordBasic {
public $currency;
public $endDate;
public $externalId;
public $externalIdString;
public $fairValue;
public $fairValueFormula;
public $fairValueRangePolicy;
public $highValue;
public $highValuePercent;
public $internalId;
public $internalIdNumber;
public $isVsoePrice;
public $item;
public $itemRevenueCategory;
public $lowValue;
public $lowValuePercent;
public $startDate;
public $unitsType;
static $paramtypesmap = array(
"currency" => "SearchMultiSelectField",
"endDate" => "SearchDateField",
"externalId" => "SearchMultiSelectField",
"externalIdString" => "SearchStringField",
"fairValue" => "SearchDoubleField",
"fairValueFormula" => "SearchMultiSelectField",
"fairValueRangePolicy" => "SearchEnumMultiSelectField",
"highValue" => "SearchDoubleField",
"highValuePercent" => "SearchDoubleField",
"internalId" => "SearchMultiSelectField",
"internalIdNumber" => "SearchLongField",
"isVsoePrice" => "SearchBooleanField",
"item" => "SearchMultiSelectField",
"itemRevenueCategory" => "SearchMultiSelectField",
"lowValue" => "SearchDoubleField",
"lowValuePercent" => "SearchDoubleField",
"startDate" => "SearchDateField",
"unitsType" => "SearchMultiSelectField",
);
}
|
fungku/netsuite-php
|
src/Classes/FairValuePriceSearchBasic.php
|
PHP
|
apache-2.0
| 2,206 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.metatron.discovery.common;
import com.facebook.presto.jdbc.PrestoArray;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
/**
* Created by kyungtaak on 2016. 10. 11..
*/
public class ResultSetSerializer extends JsonSerializer<ResultSet> {
public static class ResultSetSerializerException extends JsonProcessingException {
private static final long serialVersionUID = -914957626413580734L;
public ResultSetSerializerException(Throwable cause) {
super(cause);
}
}
@Override
public Class<ResultSet> handledType() {
return ResultSet.class;
}
@Override
public void serialize(ResultSet rs, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
try {
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
String[] columnNames = new String[numColumns];
int[] columnTypes = new int[numColumns];
for (int i = 0; i < columnNames.length; i++) {
columnNames[i] = rsmd.getColumnLabel(i + 1);
columnTypes[i] = rsmd.getColumnType(i + 1);
}
jgen.writeStartArray();
while (rs.next()) {
boolean b;
long l;
double d;
jgen.writeStartObject();
for (int i = 0; i < columnNames.length; i++) {
jgen.writeFieldName(columnNames[i]);
switch (columnTypes[i]) {
case Types.INTEGER:
l = rs.getInt(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.BIGINT:
l = rs.getLong(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.DECIMAL:
case Types.NUMERIC:
jgen.writeNumber(rs.getBigDecimal(i + 1));
break;
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
d = rs.getDouble(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(d);
}
break;
case Types.NVARCHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
jgen.writeString(rs.getString(i + 1));
break;
case Types.BOOLEAN:
case Types.BIT:
b = rs.getBoolean(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeBoolean(b);
}
break;
case Types.BINARY:
case Types.VARBINARY:
case Types.LONGVARBINARY:
jgen.writeBinary(rs.getBytes(i + 1));
break;
case Types.TINYINT:
case Types.SMALLINT:
l = rs.getShort(i + 1);
if (rs.wasNull()) {
jgen.writeNull();
} else {
jgen.writeNumber(l);
}
break;
case Types.DATE:
Date date = rs.getDate(i + 1);
if(date == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getDate(i + 1), jgen);
}
break;
case Types.TIME:
case Types.TIME_WITH_TIMEZONE:
Time time = rs.getTime(i + 1);
if(time == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getTime(i + 1), jgen);
}
break;
case Types.TIMESTAMP:
case Types.TIMESTAMP_WITH_TIMEZONE:
Timestamp ts = rs.getTimestamp(i + 1);
if(ts == null) {
jgen.writeNull();
} else {
provider.defaultSerializeDateValue(rs.getTimestamp(i + 1), jgen);
}
break;
case Types.BLOB:
Blob blob = rs.getBlob(i);
provider.defaultSerializeValue(blob.getBinaryStream(), jgen);
blob.free();
break;
case Types.CLOB:
Clob clob = rs.getClob(i);
provider.defaultSerializeValue(clob.getCharacterStream(), jgen);
clob.free();
break;
case Types.ARRAY:
if(rs.getObject(i + 1) instanceof PrestoArray) {
provider.defaultSerializeValue(((PrestoArray) rs.getObject(i + 1)).getArray(), jgen);
} else {
provider.defaultSerializeValue(rs.getArray(i + 1), jgen);
}
break;
case Types.STRUCT:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type STRUCT");
case Types.DISTINCT:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type DISTINCT");
case Types.REF:
throw new RuntimeException("ResultSetSerializer not yet implemented for SQL type REF");
case Types.JAVA_OBJECT:
default:
provider.defaultSerializeValue(rs.getObject(i + 1), jgen);
break;
}
}
jgen.writeEndObject();
}
jgen.writeEndArray();
} catch (SQLException e) {
throw new ResultSetSerializerException(e);
}
}
}
|
metatron-app/metatron-discovery
|
discovery-server/src/main/java/app/metatron/discovery/common/ResultSetSerializer.java
|
Java
|
apache-2.0
| 6,631 |
//------------------------------------------------------------------------------
// <automatisch generiert>
// Dieser Code wurde von einem Tool generiert.
//
// Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn
// der Code neu generiert wird.
// </automatisch generiert>
//------------------------------------------------------------------------------
namespace YAF.Controls
{
public partial class EditUsersInfo
{
/// <summary>
/// LocalizedLabel1-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.LocalizedLabel LocalizedLabel1;
/// <summary>
/// HelpLabel1-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel1;
/// <summary>
/// Name-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Name;
/// <summary>
/// HelpLabel2-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel2;
/// <summary>
/// DisplayName-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox DisplayName;
/// <summary>
/// HelpLabel3-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel3;
/// <summary>
/// Email-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Email;
/// <summary>
/// HelpLabel4-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel4;
/// <summary>
/// RankID-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList RankID;
/// <summary>
/// IsHostAdminRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsHostAdminRow;
/// <summary>
/// HelpLabel15-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel15;
/// <summary>
/// Moderated-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox Moderated;
/// <summary>
/// HelpLabel5-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel5;
/// <summary>
/// IsHostAdminX-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsHostAdminX;
/// <summary>
/// IsCaptchaExcludedRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsCaptchaExcludedRow;
/// <summary>
/// HelpLabel6-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel6;
/// <summary>
/// IsCaptchaExcluded-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsCaptchaExcluded;
/// <summary>
/// IsExcludedFromActiveUsersRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsExcludedFromActiveUsersRow;
/// <summary>
/// HelpLabel7-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel7;
/// <summary>
/// IsExcludedFromActiveUsers-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsExcludedFromActiveUsers;
/// <summary>
/// HelpLabel8-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel8;
/// <summary>
/// IsApproved-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsApproved;
/// <summary>
/// ApproveHolder-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder ApproveHolder;
/// <summary>
/// ApproveUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.ThemeButton ApproveUser;
/// <summary>
/// DisabledHolder-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder DisabledHolder;
/// <summary>
/// HelpLabel16-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel16;
/// <summary>
/// UnDisableUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox UnDisableUser;
/// <summary>
/// IsGuestRow-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder IsGuestRow;
/// <summary>
/// HelpLabel9-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel9;
/// <summary>
/// IsGuestX-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsGuestX;
/// <summary>
/// HelpLabel10-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel10;
/// <summary>
/// Joined-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox Joined;
/// <summary>
/// HelpLabel11-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel11;
/// <summary>
/// LastVisit-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox LastVisit;
/// <summary>
/// HelpLabel12-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel12;
/// <summary>
/// IsFacebookUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsFacebookUser;
/// <summary>
/// HelpLabel13-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel13;
/// <summary>
/// IsTwitterUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsTwitterUser;
/// <summary>
/// HelpLabel14-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.HelpLabel HelpLabel14;
/// <summary>
/// IsGoogleUser-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox IsGoogleUser;
/// <summary>
/// Save-Steuerelement.
/// </summary>
/// <remarks>
/// Automatisch generiertes Feld.
/// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
/// </remarks>
protected global::YAF.Web.Controls.ThemeButton Save;
}
}
|
YAFNET/YAFNET
|
yafsrc/YetAnotherForum.NET/Controls/EditUsersInfo.ascx.designer.cs
|
C#
|
apache-2.0
| 14,587 |
import { Trans } from "@lingui/macro";
import classNames from "classnames/dedupe";
import * as React from "react";
type Action = {
className?: string;
clickHandler?: (e?: any) => void;
disabled?: boolean;
label?: string;
node?: React.ReactNode;
};
class FullScreenModalHeaderActions extends React.Component<{
actions: Action[];
className?: string;
type: "primary" | "secondary";
}> {
getActions() {
const { actions } = this.props;
if (!actions || actions.length === 0) {
return null;
}
return actions.map(
({ className, clickHandler, label, node, disabled }, index) => {
if (node) {
return node;
}
const classes = classNames("button flush-top", className);
return (
<button
className={classes}
disabled={disabled}
key={index}
onClick={clickHandler}
>
<Trans id={label} />
</button>
);
}
);
}
render() {
const classes = classNames(
`modal-full-screen-actions modal-full-screen-actions-${this.props.type} flush-vertical`,
this.props.className
);
return <div className={classes}>{this.getActions()}</div>;
}
}
export default FullScreenModalHeaderActions;
|
dcos/dcos-ui
|
src/js/components/modals/FullScreenModalHeaderActions.tsx
|
TypeScript
|
apache-2.0
| 1,285 |
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconExposurePlus1(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M10 7H8v4H4v2h4v4h2v-4h4v-2h-4V7zm10 11h-2V7.38L15 8.4V6.7L19.7 5h.3v13z"/>
</g>
</Icon>
);
}
IconExposurePlus1.displayName = 'IconExposurePlus1';
IconExposurePlus1.category = 'image';
|
mineral-ui/mineral-ui
|
packages/mineral-ui-icons/src/IconExposurePlus1.js
|
JavaScript
|
apache-2.0
| 553 |
/*
* Copyright (c) 2015. Pokevian Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pokevian.app.smartfleet.service.floatinghead;
import android.content.Context;
import android.os.Build;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import org.apache.log4j.Logger;
import java.util.HashMap;
import java.util.Locale;
/**
* Created by dg.kim on 2015-04-13.
*/
public class TtsHandler {
private static final String TAG = "TtsHandler";
private TextToSpeech mTts;
private final Callbacks mCallbacks;
public TtsHandler(Context context, Callbacks callbacks) {
mTts = new TextToSpeech(context, new TtsInitListener());
mCallbacks = callbacks;
}
public void shutdown() {
if (mTts != null) {
mTts.stop();
mTts.shutdown();
mTts = null;
}
}
public boolean speak(CharSequence text) {
if (mTts != null) {
String utteranceId = String.valueOf(Math.random());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
} else {
HashMap<String, String> params = new HashMap<>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, utteranceId);
mTts.speak(text.toString(), TextToSpeech.QUEUE_FLUSH, params);
}
mCallbacks.onTtsStart(utteranceId);
return true;
} else {
return false;
}
}
public void stopSpeak() {
if (mTts != null && mTts.isSpeaking()) {
mTts.stop();
}
}
private void setUtteranceListener() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
mTts.setOnUtteranceProgressListener(new UtteranceProgressListener() {
@Override
public void onStart(String utteranceId) {
Logger.getLogger(TAG).info("tts start");
}
@Override
public void onDone(String utteranceId) {
Logger.getLogger(TAG).info("tts done");
mCallbacks.onTtsDone(utteranceId);
}
@Override
public void onError(String utteranceId) {
Logger.getLogger(TAG).info("tts error");
mCallbacks.onTtsDone(utteranceId);
}
});
} else {
mTts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
@Override
public void onUtteranceCompleted(String utteranceId) {
Logger.getLogger(TAG).info("tts done");
mCallbacks.onTtsDone(utteranceId);
}
});
}
}
private class TtsInitListener implements TextToSpeech.OnInitListener {
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTts.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Logger.getLogger(TAG).warn(Locale.getDefault() + " is not supported!");
mTts.shutdown();
mTts = null;
mCallbacks.onTtsInit(false);
} else {
Logger.getLogger(TAG).warn(Locale.getDefault() + "TTS initialized");
setUtteranceListener();
mCallbacks.onTtsInit(true);
}
} else {
Logger.getLogger(TAG).warn(Locale.getDefault() + "failed to initialize TTS");
}
}
}
public interface Callbacks {
void onTtsInit(boolean result);
void onTtsStart(String utteranceId);
void onTtsDone(String utteranceId);
}
}
|
Pokevian/caroolive-app
|
app/src/main/java/com/pokevian/app/smartfleet/service/floatinghead/TtsHandler.java
|
Java
|
apache-2.0
| 4,562 |
using System.Data.Entity;
using System.Linq;
using Moq;
using Riganti.Utils.Infrastructure.Core;
using Xunit;
namespace Riganti.Utils.Infrastructure.EntityFramework.Tests.Repository
{
public class EntityFrameworkRepositoryTests
{
private static readonly EpisodeEntity[] episodesSeriesOne =
{
new EpisodeEntity {Id = 1, Series = 1, Title = "Open Government"},
new EpisodeEntity {Id = 2, Series = 1, Title = "The Official Visit"},
new EpisodeEntity {Id = 3, Series = 1, Title = "The Economy Drive"},
new EpisodeEntity {Id = 4, Series = 1, Title = "Big Brother"},
new EpisodeEntity {Id = 5, Series = 1, Title = "The Writing on the Wall"},
new EpisodeEntity {Id = 6, Series = 1, Title = "The Right to Know"},
new EpisodeEntity {Id = 7, Series = 1, Title = "Jobs for the Boys"}
};
private static readonly QuoteEntity[] quotes =
{
new QuoteEntity {Id = 1, Text = " It is not for a humble mortal such as I to speculate on the complex and elevated deliberations of the mighty."},
};
private readonly Mock<YesMinisterDbContext> dbContextMock;
private readonly EntityFrameworkRepository<EpisodeEntity, int> episodeRepositorySUT;
private readonly EntityFrameworkRepository<QuoteEntity, int> quoteRepositorySUT;
private readonly Mock<IDbSet<EpisodeEntity>> episodesDbSetMock;
private readonly Mock<IDbSet<QuoteEntity>> quotesDbSetMock;
public EntityFrameworkRepositoryTests()
{
var dbContextMockFactory = new DbContextMockFactory();
dbContextMock = dbContextMockFactory.CreateDbContextMock<YesMinisterDbContext>();
episodesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, EpisodeEntity, int>(episodesSeriesOne, context => context.Episodes);
quotesDbSetMock = dbContextMock.SetupDbSet<YesMinisterDbContext, QuoteEntity, int>(quotes, context => context.Quotes);
episodeRepositorySUT = CreateEntityFrameworkRepository<EpisodeEntity>();
quoteRepositorySUT = CreateEntityFrameworkRepository<QuoteEntity>();
}
[Fact]
public void InitializeNew_ReturnsNotNullItem()
{
var newEpisode = episodeRepositorySUT.InitializeNew();
Assert.NotNull(newEpisode);
}
[Fact]
public void Insert_OneItem_CallDbSetAddMethod()
{
var newEpisode = new EpisodeEntity { Id = 10, Title = "Inserted item" };
episodeRepositorySUT.Insert(newEpisode);
episodesDbSetMock.Verify(set => set.Add(newEpisode), Times.Once);
}
[Fact]
public void Insert_MultipleItems_NewItemShouldBeInDbSetLocal()
{
var newEpisode1 = new EpisodeEntity { Id = 10, Title = "Inserted item 1" };
var newEpisode2 = new EpisodeEntity { Id = 11, Title = "Inserted item 2" };
var newEpisode3 = new EpisodeEntity { Id = 12, Title = "Inserted item 3" };
var newEpisodes = new[] { newEpisode1, newEpisode2, newEpisode3 };
episodeRepositorySUT.Insert(newEpisodes);
Assert.Contains(newEpisode1, episodesDbSetMock.Object.Local);
Assert.Contains(newEpisode2, episodesDbSetMock.Object.Local);
Assert.Contains(newEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void Delete_OneItem_SetEntityStateToModified()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void Delete_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 };
episodeRepositorySUT.Delete(deletedEpisodes);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void DeleteById_OneItem_ShouldDeleteItemFromDbSetLocal()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void DeleteById_OneItem_ShouldCallRemove()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once);
}
[Fact]
public void DeleteById_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id };
episodeRepositorySUT.Delete(deletedEpisodesIds);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDelete_OneItem_SetDeletedDate()
{
var deletedQuote = quotes[0];
quoteRepositorySUT.Delete(deletedQuote);
var quoteById = quoteRepositorySUT.GetById(deletedQuote.Id);
Assert.NotNull(quoteById.DeletedDate);
}
[Fact]
public void SoftDelete_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodes = new[] { deletedEpisode1, deletedEpisode2, deletedEpisode3 };
episodeRepositorySUT.Delete(deletedEpisodes);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDeleteById_OneItem_ShouldDeleteItemFromDbSetLocal()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
Assert.DoesNotContain(deletedEpisode, episodesDbSetMock.Object.Local);
}
[Fact]
public void SoftDeleteById_OneItem_ShouldCallRemove()
{
var deletedEpisode = episodesSeriesOne[1];
episodeRepositorySUT.Delete(deletedEpisode.Id);
episodesDbSetMock.Verify(set => set.Remove(It.Is<EpisodeEntity>(entity => entity.Id == deletedEpisode.Id)), Times.Once);
}
[Fact]
public void SoftDeleteById_MultipleItems_SetEntityStateToModified()
{
var deletedEpisode1 = episodesSeriesOne[1];
var deletedEpisode2 = episodesSeriesOne[2];
var deletedEpisode3 = episodesSeriesOne[3];
var deletedEpisodesIds = new[] { deletedEpisode1.Id, deletedEpisode2.Id, deletedEpisode3.Id };
episodeRepositorySUT.Delete(deletedEpisodesIds);
Assert.DoesNotContain(deletedEpisode1, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode2, episodesDbSetMock.Object.Local);
Assert.DoesNotContain(deletedEpisode3, episodesDbSetMock.Object.Local);
}
[Fact]
public void GetById_OneItem_ReturnsCorrectItem()
{
var id = 1;
var expectedEpisode = episodesSeriesOne.Single(e => e.Id == id);
var episode = episodeRepositorySUT.GetById(id);
Assert.Equal(expectedEpisode, episode);
}
[Fact]
public void GetByIds_MultipleItems_ReturnsCorrectItem()
{
var id1 = 1;
var id2 = 2;
var id3 = 3;
var expectedEpisode1 = episodesSeriesOne.Single(e => e.Id == id1);
var expectedEpisode2 = episodesSeriesOne.Single(e => e.Id == id2);
var expectedEpisode3 = episodesSeriesOne.Single(e => e.Id == id3);
var episodes = episodeRepositorySUT.GetByIds(new[] { 1, 2, 3 });
Assert.Contains(expectedEpisode1, episodes);
Assert.Contains(expectedEpisode2, episodes);
Assert.Contains(expectedEpisode3, episodes);
}
private EntityFrameworkRepository<TEntity, int> CreateEntityFrameworkRepository<TEntity>() where TEntity : class, IEntity<int>, new()
{
var unitOfWorkRegistryStub = new ThreadLocalUnitOfWorkRegistry();
var unitOfWorkProvider = new EntityFrameworkUnitOfWorkProvider(unitOfWorkRegistryStub,
CreateYesMinisterDbContext);
IDateTimeProvider dateTimeProvider = new UtcDateTimeProvider();
var unitOfWork = new EntityFrameworkUnitOfWork(unitOfWorkProvider, CreateYesMinisterDbContext,
DbContextOptions.ReuseParentContext);
unitOfWorkRegistryStub.RegisterUnitOfWork(unitOfWork);
return new EntityFrameworkRepository<TEntity, int>(unitOfWorkProvider, dateTimeProvider);
}
private YesMinisterDbContext CreateYesMinisterDbContext()
{
return dbContextMock.Object;
}
}
}
|
riganti/infrastructure
|
src/Infrastructure/Tests/Riganti.Utils.Infrastructure.EntityFramework.Tests/Repository/EntityFrameworkRepositoryTests.cs
|
C#
|
apache-2.0
| 10,020 |
Ti.UI.setBackgroundColor('#fff');
var inicio = Ti.UI.createWindow({
backgroundColor:'#fff'
});
var titulo = Ti.UI.createLabel({
text:'UAM',
width:'300dp',
height:'50dp',
left:'10dp',
top:'100dp',
font:{fontSize:30,
fontFamily:'Helvetica Neue'},
textAlign:'center',
});
inicio.add(titulo);
var data = [{title:'Ingresar'},{title:'Registrarse'}];
var opciones = Ti.UI.createTableView({
width:'300dp',
height:'100dp',
top:'180dp',
left:'10dp',
data:data,
color:'#000'
});
inicio.add(opciones);
opciones.addEventListener('click', function(e){
if(e.index==0){
var vIng = Ti.UI.createWindow({
url:'/ui/ingresar'
});
vIng.open({modal:true});
}
else{
alert('Registrar' +e.index);
Ti.API.info('Estoy en la opcion registrarse'+ e.index);
}
});
inicio.open();
|
addieljuarez/TallerUAM
|
Resources/app.js
|
JavaScript
|
apache-2.0
| 789 |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.qpid.proton.amqp.transport;
import java.util.Map;
import org.apache.qpid.proton.amqp.Symbol;
public final class ErrorCondition
{
private Symbol _condition;
private String _description;
private Map _info;
public Symbol getCondition()
{
return _condition;
}
public void setCondition(Symbol condition)
{
if( condition == null )
{
throw new NullPointerException("the condition field is mandatory");
}
_condition = condition;
}
public String getDescription()
{
return _description;
}
public void setDescription(String description)
{
_description = description;
}
public Map getInfo()
{
return _info;
}
public void setInfo(Map info)
{
_info = info;
}
@Override
public String toString()
{
return "Error{" +
"_condition=" + _condition +
", _description='" + _description + '\'' +
", _info=" + _info +
'}';
}
}
|
chirino/proton
|
proton-j/proton-api/src/main/java/org/apache/qpid/proton/amqp/transport/ErrorCondition.java
|
Java
|
apache-2.0
| 1,885 |
package com.icfcc.db.orderhelper;
import com.icfcc.db.orderhelper.sqlsource.*;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.builder.annotation.ProviderSqlSource;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.scripting.xmltags.DynamicSqlSource;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import java.util.Properties;
/**
* 排序辅助类
*
* @author liuzh
* @since 2015-06-26
*/
@SuppressWarnings({"rawtypes", "unchecked"})
@Intercepts(@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}))
public class OrderByHelper implements Interceptor {
private static final ThreadLocal<String> ORDER_BY = new ThreadLocal<String>();
public static String getOrderBy() {
String orderBy = ORDER_BY.get();
if (orderBy == null || orderBy.length() == 0) {
return null;
}
return orderBy;
}
/**
* 增加排序
*
* @param orderBy
*/
public static void orderBy(String orderBy) {
ORDER_BY.set(orderBy);
}
/**
* 清除本地变量
*/
public static void clear() {
ORDER_BY.remove();
}
/**
* 是否已经处理过
*
* @param ms
* @return
*/
public static boolean hasOrderBy(MappedStatement ms) {
if (ms.getSqlSource() instanceof OrderBySqlSource) {
return true;
}
return false;
}
/**
* 不支持注解形式(ProviderSqlSource)的增加order by
*
* @param invocation
* @throws Throwable
*/
public static void processIntercept(Invocation invocation) throws Throwable {
final Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
if (!hasOrderBy(ms)) {
MetaObject msObject = SystemMetaObject.forObject(ms);
//判断是否自带order by,自带的情况下作为默认排序
SqlSource sqlSource = ms.getSqlSource();
if (sqlSource instanceof StaticSqlSource) {
msObject.setValue("sqlSource", new OrderByStaticSqlSource((StaticSqlSource) sqlSource));
} else if (sqlSource instanceof RawSqlSource) {
msObject.setValue("sqlSource", new OrderByRawSqlSource((RawSqlSource) sqlSource));
} else if (sqlSource instanceof ProviderSqlSource) {
msObject.setValue("sqlSource", new OrderByProviderSqlSource((ProviderSqlSource) sqlSource));
} else if (sqlSource instanceof DynamicSqlSource) {
msObject.setValue("sqlSource", new OrderByDynamicSqlSource((DynamicSqlSource) sqlSource));
} else {
throw new RuntimeException("无法处理该类型[" + sqlSource.getClass() + "]的SqlSource");
}
}
}
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
if (getOrderBy() != null) {
processIntercept(invocation);
}
return invocation.proceed();
} finally {
clear();
}
}
@Override
public Object plugin(Object target) {
if (target instanceof Executor) {
return Plugin.wrap(target, this);
} else {
return target;
}
}
@Override
public void setProperties(Properties properties) {
}
}
|
Gitpiece/ssm
|
ssm-db-support/src/main/java/com/icfcc/db/orderhelper/OrderByHelper.java
|
Java
|
apache-2.0
| 3,806 |
package ru.tr1al.dao;
import ru.tr1al.model.Model;
public interface DAO<T extends Model> {
Class<T> getEntityClass();
}
|
Tr1aL/utils
|
src/main/java/ru/tr1al/dao/DAO.java
|
Java
|
apache-2.0
| 127 |
package test
import (
"bufio"
"os"
"testing"
)
import manager "github.com/tiagofalcao/GoNotebook/manager"
func Benchmark(b *testing.B, input string, caseTask manager.Task) {
i, err := os.Open(input)
if err != nil {
b.Errorf("Can't open %s", input)
}
var o NilWriter
b.ResetTimer()
for x := 0; x < b.N; x++ {
manager.NewManagerIO(caseTask, bufio.NewReader(i), o)
}
i.Close()
}
|
tiagofalcao/GoNotebook
|
manager/test/benchmark.go
|
GO
|
apache-2.0
| 423 |
package com.example.views;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import android.widget.ViewSwitcher.ViewFactory;
public class V_ViewSwitcher extends GhostActivity {
private ViewSwitcher switcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uistudy_view_switcher);
switcher = this.findViewSwitcher(R.id.viewSwitcher);
//===给swticher设置View工厂,当调用switcher.getNextView()时,就是返回 factory.makeView()创建的View
//===这里给一个TextView,让swticher切换多个TextView
switcher.setFactory(new ViewFactory() {
@Override
public View makeView() {
return new TextView(V_ViewSwitcher.this);
}
});
}
private int count = 0;
//====消息响应:下一个
public void next(View v){
count++;
switcher.setInAnimation(this, R.anim.slide_in_right); //切换组件:显示过程的动画
switcher.setOutAnimation(this, R.anim.slide_out_left); //切换组件:隐藏过程的动画
TextView textView = (TextView) switcher.getNextView();
textView.setText("This is "+count+"!!!");
textView.setTextSize(22);
textView.setTextColor(0xffff0000);
switcher.showNext();
}
//====消息响应:上一个
public void prev(View v){
count--;
switcher.setInAnimation(this, R.anim.slide_in_left); //切换组件:显示过程的动画
switcher.setOutAnimation(this, R.anim.slide_out_right); //切换组件:隐藏过程的动画
TextView textView = (TextView) switcher.getNextView();
textView.setText("This is "+count+"!!!");
textView.setTextSize(22);
textView.setTextColor(0xffff0000);
switcher.showPrevious();
}
}
|
cowthan/AyoWeibo
|
sample/back/src/com/example/views/V_ViewSwitcher.java
|
Java
|
apache-2.0
| 1,766 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Knowit.EPiModules.ImageScaling.Sample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Knowit.EPiModules.ImageScaling.Sample")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4afc5705-c5ba-4f1d-97e2-81020c83c492")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
knowit/Knowit.EPiModules.ImageScaling
|
sample/Properties/AssemblyInfo.cs
|
C#
|
apache-2.0
| 1,410 |
package gov.va.med.imaging.storage.cache;
import java.util.Iterator;
import java.util.regex.Pattern;
import gov.va.med.imaging.storage.cache.events.GroupLifecycleListener;
import gov.va.med.imaging.storage.cache.exceptions.CacheException;
/**
*
* i.e. A Group may contain other Group instances, which contain other Group instances,
* which eventually contain Instance.
*
*/
public interface Group
extends MutableNamedObject, GroupAndInstanceAncestor, GroupSet, InstanceSet
{
// A group name must be 1 to 64 chars, start with a letter and contain letters, numbers, dashes and underscores
public static Pattern NamePattern = Pattern.compile( "[a-zA-Z][a-zA-Z0-9-_]{0,63}" );
/**
* Return some human readable identifier for this group.
* This must be unique within the parent group, not necessarily across all groups.
* @return
*/
@Override
public String getName();
public java.util.Date getLastAccessed()
throws CacheException;
public long getSize()
throws CacheException;
// ===========================================================================
// Methods that recursively walk down the Region/Group/Instance graph are
// defined in GroupAndInstanceAncestor
// ===========================================================================
// ===========================================================================
// Methods operating on the child Group of this Group are defined in GroupSet
// ===========================================================================
// =====================================================================================
// Methods operating on child Instance are defined in InstanceSet
// =====================================================================================
// =====================================================================================
// Eviction Methods
// =====================================================================================
public int evaluateAndEvictChildGroups(EvictionJudge<Group> judge)
throws CacheException;
// ======================================================================================================
// Listener Management
// ======================================================================================================
public abstract void registerListener(GroupLifecycleListener listener);
public abstract void unregisterListener(GroupLifecycleListener listener);
}
|
VHAINNOVATIONS/Telepathology
|
Source/Java/CacheAPI/main/src/java/gov/va/med/imaging/storage/cache/Group.java
|
Java
|
apache-2.0
| 2,459 |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.retail.v2.model;
/**
* Product captures all metadata information of items to be recommended or searched.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Retail API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudRetailV2Product extends com.google.api.client.json.GenericJson {
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2CustomAttribute used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2CustomAttribute.class);
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2Audience audience;
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String availability;
/**
* The available quantity of the item.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.Integer availableQuantity;
/**
* The timestamp when this Product becomes available for SearchService.Search.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String availableTime;
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> brands;
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> categories;
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> collectionMemberIds;
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2ColorInfo colorInfo;
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> conditions;
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String description;
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String expireTime;
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2FulfillmentInfo used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2FulfillmentInfo.class);
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String gtin;
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String id;
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Image> images;
static {
// hack to force ProGuard to consider GoogleCloudRetailV2Image used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudRetailV2Image.class);
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String languageCode;
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> materials;
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String name;
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> patterns;
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2PriceInfo priceInfo;
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String primaryProductId;
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Promotion> promotions;
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String publishTime;
/**
* The rating of this product.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleCloudRetailV2Rating rating;
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String retrievableFields;
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> sizes;
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> tags;
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String title;
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private String ttl;
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String type;
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String uri;
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudRetailV2Product> variants;
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* @return value or {@code null} for none
*/
public java.util.Map<String, GoogleCloudRetailV2CustomAttribute> getAttributes() {
return attributes;
}
/**
* Highly encouraged. Extra product attributes to be included. For example, for products, this
* could include the store name, vendor, style, color, etc. These are very strong signals for
* recommendation model, thus we highly recommend providing the attributes here. Features that can
* take on one of a limited number of possible values. Two types of features can be set are:
* Textual features. some examples would be the brand/maker of a product, or country of a
* customer. Numerical features. Some examples would be the height/weight of a product, or age of
* a customer. For example: `{ "vendor": {"text": ["vendor123", "vendor456"]}, "lengths_cm":
* {"numbers":[2.3, 15.4]}, "heights_cm": {"numbers":[8.1, 6.4]} }`. This field needs to pass all
* below criteria, otherwise an INVALID_ARGUMENT error is returned: * Max entries count: 200. *
* The key must be a UTF-8 encoded string with a length limit of 128 characters. * For indexable
* attribute, the key must match the pattern: `a-zA-Z0-9*`. For example, `key0LikeThis` or
* `KEY_1_LIKE_THIS`. * For text attributes, at most 400 values are allowed. Empty values are not
* allowed. Each value must be a non-empty UTF-8 encoded string with a length limit of 256
* characters. * For number attributes, at most 400 values are allowed.
* @param attributes attributes or {@code null} for none
*/
public GoogleCloudRetailV2Product setAttributes(java.util.Map<String, GoogleCloudRetailV2CustomAttribute> attributes) {
this.attributes = attributes;
return this;
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2Audience getAudience() {
return audience;
}
/**
* The target group associated with a given audience (e.g. male, veterans, car owners, musicians,
* etc.) of the product.
* @param audience audience or {@code null} for none
*/
public GoogleCloudRetailV2Product setAudience(GoogleCloudRetailV2Audience audience) {
this.audience = audience;
return this;
}
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* @return value or {@code null} for none
*/
public java.lang.String getAvailability() {
return availability;
}
/**
* The online availability of the Product. Default to Availability.IN_STOCK. Corresponding
* properties: Google Merchant Center property
* [availability](https://support.google.com/merchants/answer/6324448). Schema.org property
* [Offer.availability](https://schema.org/availability).
* @param availability availability or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailability(java.lang.String availability) {
this.availability = availability;
return this;
}
/**
* The available quantity of the item.
* @return value or {@code null} for none
*/
public java.lang.Integer getAvailableQuantity() {
return availableQuantity;
}
/**
* The available quantity of the item.
* @param availableQuantity availableQuantity or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailableQuantity(java.lang.Integer availableQuantity) {
this.availableQuantity = availableQuantity;
return this;
}
/**
* The timestamp when this Product becomes available for SearchService.Search.
* @return value or {@code null} for none
*/
public String getAvailableTime() {
return availableTime;
}
/**
* The timestamp when this Product becomes available for SearchService.Search.
* @param availableTime availableTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setAvailableTime(String availableTime) {
this.availableTime = availableTime;
return this;
}
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getBrands() {
return brands;
}
/**
* The brands of the product. A maximum of 30 brands are allowed. Each brand must be a UTF-8
* encoded string with a length limit of 1,000 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [brand](https://support.google.com/merchants/answer/6324351). Schema.org property
* [Product.brand](https://schema.org/brand).
* @param brands brands or {@code null} for none
*/
public GoogleCloudRetailV2Product setBrands(java.util.List<java.lang.String> brands) {
this.brands = brands;
return this;
}
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCategories() {
return categories;
}
/**
* Product categories. This field is repeated for supporting one product belonging to several
* parallel categories. Strongly recommended using the full path for better search /
* recommendation quality. To represent full path of category, use '>' sign to separate different
* hierarchies. If '>' is part of the category name, please replace it with other character(s).
* For example, if a shoes product belongs to both ["Shoes & Accessories" -> "Shoes"] and ["Sports
* & Fitness" -> "Athletic Clothing" -> "Shoes"], it could be represented as: "categories": [
* "Shoes & Accessories > Shoes", "Sports & Fitness > Athletic Clothing > Shoes" ] Must be set for
* Type.PRIMARY Product otherwise an INVALID_ARGUMENT error is returned. At most 250 values are
* allowed per Product. Empty values are not allowed. Each value must be a UTF-8 encoded string
* with a length limit of 5,000 characters. Otherwise, an INVALID_ARGUMENT error is returned.
* Corresponding properties: Google Merchant Center property google_product_category. Schema.org
* property [Product.category] (https://schema.org/category). [mc_google_product_category]:
* https://support.google.com/merchants/answer/6324436
* @param categories categories or {@code null} for none
*/
public GoogleCloudRetailV2Product setCategories(java.util.List<java.lang.String> categories) {
this.categories = categories;
return this;
}
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getCollectionMemberIds() {
return collectionMemberIds;
}
/**
* The id of the collection members when type is Type.COLLECTION. Non-existent product ids are
* allowed. The type of the members must be either Type.PRIMARY or Type.VARIANT otherwise and
* INVALID_ARGUMENT error is thrown. Should not set it for other types. A maximum of 1000 values
* are allowed. Otherwise, an INVALID_ARGUMENT error is return.
* @param collectionMemberIds collectionMemberIds or {@code null} for none
*/
public GoogleCloudRetailV2Product setCollectionMemberIds(java.util.List<java.lang.String> collectionMemberIds) {
this.collectionMemberIds = collectionMemberIds;
return this;
}
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2ColorInfo getColorInfo() {
return colorInfo;
}
/**
* The color of the product. Corresponding properties: Google Merchant Center property
* [color](https://support.google.com/merchants/answer/6324487). Schema.org property
* [Product.color](https://schema.org/color).
* @param colorInfo colorInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setColorInfo(GoogleCloudRetailV2ColorInfo colorInfo) {
this.colorInfo = colorInfo;
return this;
}
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getConditions() {
return conditions;
}
/**
* The condition of the product. Strongly encouraged to use the standard values: "new",
* "refurbished", "used". A maximum of 1 value is allowed per Product. Each value must be a UTF-8
* encoded string with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is
* returned. Corresponding properties: Google Merchant Center property
* [condition](https://support.google.com/merchants/answer/6324469). Schema.org property
* [Offer.itemCondition](https://schema.org/itemCondition).
* @param conditions conditions or {@code null} for none
*/
public GoogleCloudRetailV2Product setConditions(java.util.List<java.lang.String> conditions) {
this.conditions = conditions;
return this;
}
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* @return value or {@code null} for none
*/
public java.lang.String getDescription() {
return description;
}
/**
* Product description. This field must be a UTF-8 encoded string with a length limit of 5,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [description](https://support.google.com/merchants/answer/6324468).
* Schema.org property [Product.description](https://schema.org/description).
* @param description description or {@code null} for none
*/
public GoogleCloudRetailV2Product setDescription(java.lang.String description) {
this.description = description;
return this;
}
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* @return value or {@code null} for none
*/
public String getExpireTime() {
return expireTime;
}
/**
* The timestamp when this product becomes unavailable for SearchService.Search. If it is set, the
* Product is not available for SearchService.Search after expire_time. However, the product can
* still be retrieved by ProductService.GetProduct and ProductService.ListProducts. expire_time
* must be later than available_time and publish_time, otherwise an INVALID_ARGUMENT error is
* thrown. Corresponding properties: Google Merchant Center property
* [expiration_date](https://support.google.com/merchants/answer/6324499).
* @param expireTime expireTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setExpireTime(String expireTime) {
this.expireTime = expireTime;
return this;
}
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2FulfillmentInfo> getFulfillmentInfo() {
return fulfillmentInfo;
}
/**
* Fulfillment information, such as the store IDs for in-store pickup or region IDs for different
* shipping methods. All the elements must have distinct FulfillmentInfo.type. Otherwise, an
* INVALID_ARGUMENT error is returned.
* @param fulfillmentInfo fulfillmentInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setFulfillmentInfo(java.util.List<GoogleCloudRetailV2FulfillmentInfo> fulfillmentInfo) {
this.fulfillmentInfo = fulfillmentInfo;
return this;
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* @return value or {@code null} for none
*/
public java.lang.String getGtin() {
return gtin;
}
/**
* The Global Trade Item Number (GTIN) of the product. This field must be a UTF-8 encoded string
* with a length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. This
* field must be a Unigram. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [gtin](https://support.google.com/merchants/answer/6324461). Schema.org property
* [Product.isbn](https://schema.org/isbn), [Product.gtin8](https://schema.org/gtin8),
* [Product.gtin12](https://schema.org/gtin12), [Product.gtin13](https://schema.org/gtin13), or
* [Product.gtin14](https://schema.org/gtin14). If the value is not a valid GTIN, an
* INVALID_ARGUMENT error is returned.
* @param gtin gtin or {@code null} for none
*/
public GoogleCloudRetailV2Product setGtin(java.lang.String gtin) {
this.gtin = gtin;
return this;
}
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* @return value or {@code null} for none
*/
public java.lang.String getId() {
return id;
}
/**
* Immutable. Product identifier, which is the final component of name. For example, this field is
* "id_1", if name is
* `projects/locations/global/catalogs/default_catalog/branches/default_branch/products/id_1`.
* This field must be a UTF-8 encoded string with a length limit of 128 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant Center property
* [id](https://support.google.com/merchants/answer/6324405). Schema.org property
* [Product.sku](https://schema.org/sku).
* @param id id or {@code null} for none
*/
public GoogleCloudRetailV2Product setId(java.lang.String id) {
this.id = id;
return this;
}
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Image> getImages() {
return images;
}
/**
* Product images for the product.Highly recommended to put the main image to the first. A maximum
* of 300 images are allowed. Corresponding properties: Google Merchant Center property
* [image_link](https://support.google.com/merchants/answer/6324350). Schema.org property
* [Product.image](https://schema.org/image).
* @param images images or {@code null} for none
*/
public GoogleCloudRetailV2Product setImages(java.util.List<GoogleCloudRetailV2Image> images) {
this.images = images;
return this;
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* @return value or {@code null} for none
*/
public java.lang.String getLanguageCode() {
return languageCode;
}
/**
* Language of the title/description and other string attributes. Use language tags defined by
* [BCP 47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt). For product prediction, this field is
* ignored and the model automatically detects the text language. The Product can include text in
* different languages, but duplicating Products to provide text in multiple languages can result
* in degraded model performance. For product search this field is in use. It defaults to "en-US"
* if unset.
* @param languageCode languageCode or {@code null} for none
*/
public GoogleCloudRetailV2Product setLanguageCode(java.lang.String languageCode) {
this.languageCode = languageCode;
return this;
}
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getMaterials() {
return materials;
}
/**
* The material of the product. For example, "leather", "wooden". A maximum of 20 values are
* allowed. Each value must be a UTF-8 encoded string with a length limit of 200 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [material](https://support.google.com/merchants/answer/6324410). Schema.org
* property [Product.material](https://schema.org/material).
* @param materials materials or {@code null} for none
*/
public GoogleCloudRetailV2Product setMaterials(java.util.List<java.lang.String> materials) {
this.materials = materials;
return this;
}
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* @return value or {@code null} for none
*/
public java.lang.String getName() {
return name;
}
/**
* Immutable. Full resource name of the product, such as `projects/locations/global/catalogs/defau
* lt_catalog/branches/default_branch/products/product_id`.
* @param name name or {@code null} for none
*/
public GoogleCloudRetailV2Product setName(java.lang.String name) {
this.name = name;
return this;
}
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getPatterns() {
return patterns;
}
/**
* The pattern or graphic print of the product. For example, "striped", "polka dot", "paisley". A
* maximum of 20 values are allowed per Product. Each value must be a UTF-8 encoded string with a
* length limit of 128 characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding
* properties: Google Merchant Center property
* [pattern](https://support.google.com/merchants/answer/6324483). Schema.org property
* [Product.pattern](https://schema.org/pattern).
* @param patterns patterns or {@code null} for none
*/
public GoogleCloudRetailV2Product setPatterns(java.util.List<java.lang.String> patterns) {
this.patterns = patterns;
return this;
}
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2PriceInfo getPriceInfo() {
return priceInfo;
}
/**
* Product price and cost information. Corresponding properties: Google Merchant Center property
* [price](https://support.google.com/merchants/answer/6324371).
* @param priceInfo priceInfo or {@code null} for none
*/
public GoogleCloudRetailV2Product setPriceInfo(GoogleCloudRetailV2PriceInfo priceInfo) {
this.priceInfo = priceInfo;
return this;
}
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* @return value or {@code null} for none
*/
public java.lang.String getPrimaryProductId() {
return primaryProductId;
}
/**
* Variant group identifier. Must be an id, with the same parent branch with this product.
* Otherwise, an error is thrown. For Type.PRIMARY Products, this field can only be empty or set
* to the same value as id. For VARIANT Products, this field cannot be empty. A maximum of 2,000
* products are allowed to share the same Type.PRIMARY Product. Otherwise, an INVALID_ARGUMENT
* error is returned. Corresponding properties: Google Merchant Center property
* [item_group_id](https://support.google.com/merchants/answer/6324507). Schema.org property
* [Product.inProductGroupWithID](https://schema.org/inProductGroupWithID).
* @param primaryProductId primaryProductId or {@code null} for none
*/
public GoogleCloudRetailV2Product setPrimaryProductId(java.lang.String primaryProductId) {
this.primaryProductId = primaryProductId;
return this;
}
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Promotion> getPromotions() {
return promotions;
}
/**
* The promotions applied to the product. A maximum of 10 values are allowed per Product. Only
* Promotion.promotion_id will be used, other fields will be ignored if set.
* @param promotions promotions or {@code null} for none
*/
public GoogleCloudRetailV2Product setPromotions(java.util.List<GoogleCloudRetailV2Promotion> promotions) {
this.promotions = promotions;
return this;
}
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* @return value or {@code null} for none
*/
public String getPublishTime() {
return publishTime;
}
/**
* The timestamp when the product is published by the retailer for the first time, which indicates
* the freshness of the products. Note that this field is different from available_time, given it
* purely describes product freshness regardless of when it is available on search and
* recommendation.
* @param publishTime publishTime or {@code null} for none
*/
public GoogleCloudRetailV2Product setPublishTime(String publishTime) {
this.publishTime = publishTime;
return this;
}
/**
* The rating of this product.
* @return value or {@code null} for none
*/
public GoogleCloudRetailV2Rating getRating() {
return rating;
}
/**
* The rating of this product.
* @param rating rating or {@code null} for none
*/
public GoogleCloudRetailV2Product setRating(GoogleCloudRetailV2Rating rating) {
this.rating = rating;
return this;
}
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* @return value or {@code null} for none
*/
public String getRetrievableFields() {
return retrievableFields;
}
/**
* Indicates which fields in the Products are returned in SearchResponse. Supported fields for all
* types: * audience * availability * brands * color_info * conditions * gtin * materials * name *
* patterns * price_info * rating * sizes * title * uri Supported fields only for Type.PRIMARY and
* Type.COLLECTION: * categories * description * images Supported fields only for Type.VARIANT: *
* Only the first image in images To mark attributes as retrievable, include paths of the form
* "attributes.key" where "key" is the key of a custom attribute, as specified in attributes. For
* Type.PRIMARY and Type.COLLECTION, the following fields are always returned in SearchResponse by
* default: * name For Type.VARIANT, the following fields are always returned in by default: *
* name * color_info Maximum number of paths is 30. Otherwise, an INVALID_ARGUMENT error is
* returned. Note: Returning more fields in SearchResponse may increase response payload size and
* serving latency.
* @param retrievableFields retrievableFields or {@code null} for none
*/
public GoogleCloudRetailV2Product setRetrievableFields(String retrievableFields) {
this.retrievableFields = retrievableFields;
return this;
}
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getSizes() {
return sizes;
}
/**
* The size of the product. To represent different size systems or size types, consider using this
* format: [[[size_system:]size_type:]size_value]. For example, in "US:MENS:M", "US" represents
* size system; "MENS" represents size type; "M" represents size value. In "GIRLS:27", size system
* is empty; "GIRLS" represents size type; "27" represents size value. In "32 inches", both size
* system and size type are empty, while size value is "32 inches". A maximum of 20 values are
* allowed per Product. Each value must be a UTF-8 encoded string with a length limit of 128
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [size](https://support.google.com/merchants/answer/6324492),
* [size_type](https://support.google.com/merchants/answer/6324497), and
* [size_system](https://support.google.com/merchants/answer/6324502). Schema.org property
* [Product.size](https://schema.org/size).
* @param sizes sizes or {@code null} for none
*/
public GoogleCloudRetailV2Product setSizes(java.util.List<java.lang.String> sizes) {
this.sizes = sizes;
return this;
}
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getTags() {
return tags;
}
/**
* Custom tags associated with the product. At most 250 values are allowed per Product. This value
* must be a UTF-8 encoded string with a length limit of 1,000 characters. Otherwise, an
* INVALID_ARGUMENT error is returned. This tag can be used for filtering recommendation results
* by passing the tag as part of the PredictRequest.filter. Corresponding properties: Google
* Merchant Center property
* [custom_label_0–4](https://support.google.com/merchants/answer/6324473).
* @param tags tags or {@code null} for none
*/
public GoogleCloudRetailV2Product setTags(java.util.List<java.lang.String> tags) {
this.tags = tags;
return this;
}
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* @return value or {@code null} for none
*/
public java.lang.String getTitle() {
return title;
}
/**
* Required. Product title. This field must be a UTF-8 encoded string with a length limit of 1,000
* characters. Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google
* Merchant Center property [title](https://support.google.com/merchants/answer/6324415).
* Schema.org property [Product.name](https://schema.org/name).
* @param title title or {@code null} for none
*/
public GoogleCloudRetailV2Product setTitle(java.lang.String title) {
this.title = title;
return this;
}
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* @return value or {@code null} for none
*/
public String getTtl() {
return ttl;
}
/**
* Input only. The TTL (time to live) of the product. If it is set, it must be a non-negative
* value, and expire_time is set as current timestamp plus ttl. The derived expire_time is
* returned in the output and ttl is left blank when retrieving the Product. If it is set, the
* product is not available for SearchService.Search after current timestamp plus ttl. However,
* the product can still be retrieved by ProductService.GetProduct and
* ProductService.ListProducts.
* @param ttl ttl or {@code null} for none
*/
public GoogleCloudRetailV2Product setTtl(String ttl) {
this.ttl = ttl;
return this;
}
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* @return value or {@code null} for none
*/
public java.lang.String getType() {
return type;
}
/**
* Immutable. The type of the product. Default to
* Catalog.product_level_config.ingestion_product_type if unset.
* @param type type or {@code null} for none
*/
public GoogleCloudRetailV2Product setType(java.lang.String type) {
this.type = type;
return this;
}
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* @return value or {@code null} for none
*/
public java.lang.String getUri() {
return uri;
}
/**
* Canonical URL directly linking to the product detail page. It is strongly recommended to
* provide a valid uri for the product, otherwise the service performance could be significantly
* degraded. This field must be a UTF-8 encoded string with a length limit of 5,000 characters.
* Otherwise, an INVALID_ARGUMENT error is returned. Corresponding properties: Google Merchant
* Center property [link](https://support.google.com/merchants/answer/6324416). Schema.org
* property [Offer.url](https://schema.org/url).
* @param uri uri or {@code null} for none
*/
public GoogleCloudRetailV2Product setUri(java.lang.String uri) {
this.uri = uri;
return this;
}
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudRetailV2Product> getVariants() {
return variants;
}
/**
* Output only. Product variants grouped together on primary product which share similar product
* attributes. It's automatically grouped by primary_product_id for all the product variants. Only
* populated for Type.PRIMARY Products. Note: This field is OUTPUT_ONLY for
* ProductService.GetProduct. Do not set this field in API requests.
* @param variants variants or {@code null} for none
*/
public GoogleCloudRetailV2Product setVariants(java.util.List<GoogleCloudRetailV2Product> variants) {
this.variants = variants;
return this;
}
@Override
public GoogleCloudRetailV2Product set(String fieldName, Object value) {
return (GoogleCloudRetailV2Product) super.set(fieldName, value);
}
@Override
public GoogleCloudRetailV2Product clone() {
return (GoogleCloudRetailV2Product) super.clone();
}
}
|
googleapis/google-api-java-client-services
|
clients/google-api-services-retail/v2/1.31.0/com/google/api/services/retail/v2/model/GoogleCloudRetailV2Product.java
|
Java
|
apache-2.0
| 62,165 |
var httpManager = require("httpManager");
Alloy.Globals.isSearch = true;
if (OS_ANDROID) {
$.search.windowSoftInputMode = Ti.UI.Android.SOFT_INPUT_ADJUST_PAN;
}
var dataTitles = [
{
name : "Find Us",
view : "findUs"
},
{
name : "Deals",
view : "deals"
},
{
name : "Testimonials",
view : "testmonials"
},
{
name : "Loyalty",
view : "loyalty"
},
{
name : "Be Social",
view : "beSocial"
},
{
name : "Before & After",
view : "beforeAfter"
},
{
name : "About Us",
view : "aboutUs"
},
{
name : "Services for dermatology",
view : "services"
},
{
name : "Services for dental",
view : "services"
},
];
var data =[];
for (var i=0; i < dataTitles.length; i++) {
var row = Titanium.UI.createTableViewRow({
title:dataTitles[i].name,
color:'black',
height:50,
id : i,
});
data.push(row);
}
var search = Titanium.UI.createSearchBar({
barColor : '#DA308A',
showCancel : true,
height : 43,
top : 0,
});
search.addEventListener('cancel', function() {
search.blur();
});
var listView = Ti.UI.createListView({
searchView : search,
caseInsensitiveSearch : true,
backgroundColor:'white',
top :"60",
bottom :"60",
});
var listSection = Ti.UI.createListSection(
);
var data = [];
for (var i = 0; i < dataTitles.length; i++) {
data.push({
properties : {
title : dataTitles[i].name,
searchableText :dataTitles[i].name,
color :"black",
height : "40",
}
});
}
listSection.setItems(data);
listView.sections = [listSection];
listView.addEventListener('itemclick', function(e){
Alloy.createController(dataTitles[e.itemIndex].view).getView();
});
$.search.add(listView);
function logoutClicked (e)
{
httpManager.userLogout(function(response) {
if(response.success == 1)
{
Alloy.createController('login').getView();
$.search .close();
}
});
}
Ti.App.addEventListener('android:back', function() {
$.search.exitOnClose = true;
var myActivity = Ti.Android.currentActivity();
myActivity.finish();
});
Alloy.Globals.closeSearchWindow = function(){
$.search .close();
};
$.search.open();
|
SrinivasReddy987/Lookswoow
|
app/controllers/search.js
|
JavaScript
|
apache-2.0
| 2,071 |
package com.ssh.sys.core.validation;
import com.ssh.common.util.Constant;
import com.ssh.sys.api.dto.UserDTO;
import com.ssh.sys.api.dto.extension.PermissionExtDTO;
import com.ssh.sys.api.service.PermissionService;
import com.ssh.sys.api.service.UserService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.inject.Inject;
import java.util.List;
@ActiveProfiles(Constant.ENV_DEV)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({
"classpath:spring-validation.xml",
"classpath:spring-core-context.xml",
"classpath:sys-core-context.xml"
})
//@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional(transactionManager = "transactionManager")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ValidationTest {
private static final Logger LOGGER = LoggerFactory.getLogger(ValidationTest.class);
@Inject
private UserService userService;
@Inject
private PermissionService permissionService;
@Before
public void setUp() throws Exception {
Assert.assertNotNull(userService);
// 注意: 引进和不引进spring-validation.xml配置文件一下结果的区别
LOGGER.info("isAopProxy => {}", AopUtils.isAopProxy(userService));
LOGGER.info("isJdkDynamicProxy => {}", AopUtils.isJdkDynamicProxy(userService));
LOGGER.info("isCglibProxy => {}", AopUtils.isCglibProxy(userService));
}
@Test
@Rollback
public void test1Save() throws Exception {
UserDTO dto = new UserDTO();
dto.setCode("King");
dto.setName("King");
dto.setPass("King");
userService.add(dto);
}
@Test
public void test2GetList() throws Exception {
List<UserDTO> list = userService.getList(new UserDTO());
LOGGER.info("list => {}", list);
}
@Test
public void test3GetById() throws Exception {
PermissionExtDTO dto = permissionService.getById(11L);
LOGGER.info("=== {} ===", dto);
}
}
|
lugavin/ssh
|
ssh-sys-core/src/test/java/com/ssh/sys/core/validation/ValidationTest.java
|
Java
|
apache-2.0
| 2,560 |
package firestream.chat.chat;
import androidx.annotation.Nullable;
import org.pmw.tinylog.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import firestream.chat.events.ListData;
import firestream.chat.filter.Filter;
import firestream.chat.firebase.service.Path;
import firestream.chat.interfaces.IAbstractChat;
import firestream.chat.message.Sendable;
import firestream.chat.message.TypingState;
import firestream.chat.namespace.Fire;
import firestream.chat.types.SendableType;
import firestream.chat.types.TypingStateType;
import firestream.chat.util.TypingMap;
import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import sdk.guru.common.DisposableMap;
import sdk.guru.common.Event;
import sdk.guru.common.EventType;
import sdk.guru.common.Optional;
import sdk.guru.common.RX;
/**
* This class handles common elements of a conversation bit it 1-to-1 or group.
* Mainly sending and receiving messages.
*/
public abstract class AbstractChat implements IAbstractChat {
/**
* Store the disposables so we can dispose of all of them when the user logs out
*/
protected DisposableMap dm = new DisposableMap();
/**
* Event events
*/
protected Events events = new Events();
/**
* A list of all sendables received
*/
protected List<Sendable> sendables = new ArrayList<>();
protected TypingMap typingMap = new TypingMap();
/**
* Start listening to the current message reference and retrieve all messages
* @return a events of message results
*/
protected Observable<Event<Sendable>> messagesOn() {
return messagesOn(null);
}
/**
* Start listening to the current message reference and pass the messages to the events
* @param newerThan only listen for messages after this date
* @return a events of message results
*/
protected Observable<Event<Sendable>> messagesOn(Date newerThan) {
return Fire.internal().getFirebaseService().core.messagesOn(messagesPath(), newerThan).doOnNext(event -> {
Sendable sendable = event.get();
Sendable previous = getSendable(sendable.getId());
if (event.isAdded()) {
sendables.add(sendable);
}
if (previous != null) {
if (event.isModified()) {
sendable.copyTo(previous);
}
if (event.isRemoved()) {
sendables.remove(previous);
}
}
getSendableEvents().getSendables().accept(event);
}).doOnError(throwable -> {
events.publishThrowable().accept(throwable);
}).observeOn(RX.main());
}
/**
* Get a updateBatch of messages once
* @param fromDate get messages from this date
* @param toDate get messages until this date
* @param limit limit the maximum number of messages
* @return a events of message results
*/
protected Single<List<Sendable>> loadMoreMessages(@Nullable Date fromDate, @Nullable Date toDate, @Nullable Integer limit, boolean desc) {
return Fire.stream().getFirebaseService().core
.loadMoreMessages(messagesPath(), fromDate, toDate, limit)
.map(sendables -> {
Collections.sort(sendables, (s1, s2) -> {
if (desc) {
return s2.getDate().compareTo(s1.getDate());
} else {
return s1.getDate().compareTo(s2.getDate());
}
});
return sendables;
})
.observeOn(RX.main());
}
public Single<List<Sendable>> loadMoreMessages(Date fromDate, Date toDate, boolean desc) {
return loadMoreMessages(fromDate, toDate, null, desc);
}
public Single<List<Sendable>> loadMoreMessagesFrom(Date fromDate, Integer limit, boolean desc) {
return loadMoreMessages(fromDate, null, limit, desc);
}
public Single<List<Sendable>> loadMoreMessagesTo(Date toDate, Integer limit, boolean desc) {
return loadMoreMessages(null, toDate, limit, desc);
}
public Single<List<Sendable>> loadMoreMessagesBefore(final Date toDate, Integer limit, boolean desc) {
return Single.defer(() -> {
Date before = toDate == null ? null : new Date(toDate.getTime() - 1);
return loadMoreMessagesTo(before, limit, desc);
});
}
/**
* Listen for changes in the value of a list reference
* @param path to listen to
* @return events of list events
*/
protected Observable<Event<ListData>> listChangeOn(Path path) {
return Fire.stream().getFirebaseService().core
.listChangeOn(path)
.observeOn(RX.main());
}
public Completable send(Path messagesPath, Sendable sendable) {
return send(messagesPath, sendable, null);
}
/**
* Send a message to a messages ref
* @param messagesPath
* @param sendable item to be sent
* @param newId the ID of the new message
* @return single containing message id
*/
public Completable send(Path messagesPath, Sendable sendable, @Nullable Consumer<String> newId) {
return Fire.stream().getFirebaseService().core
.send(messagesPath, sendable, newId)
.observeOn(RX.main());
}
/**
* Delete a sendable from our queue
* @param messagesPath
* @return completion
*/
protected Completable deleteSendable (Path messagesPath) {
return Fire.stream().getFirebaseService().core
.deleteSendable(messagesPath)
.observeOn(RX.main());
}
/**
* Remove a user from a reference
* @param path for users
* @param user to remove
* @return completion
*/
protected Completable removeUser(Path path, User user) {
return removeUsers(path, user);
}
/**
* Remove users from a reference
* @param path for users
* @param users to remove
* @return completion
*/
protected Completable removeUsers(Path path, User... users) {
return removeUsers(path, Arrays.asList(users));
}
/**
* Remove users from a reference
* @param path for users
* @param users to remove
* @return completion
*/
protected Completable removeUsers(Path path, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.removeUsers(path, users)
.observeOn(RX.main());
}
/**
* Add a user to a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param user to add
* @return completion
*/
protected Completable addUser(Path path, User.DataProvider dataProvider, User user) {
return addUsers(path, dataProvider, user);
}
/**
* Add users to a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to add
* @return completion
*/
public Completable addUsers(Path path, User.DataProvider dataProvider, User... users) {
return addUsers(path, dataProvider, Arrays.asList(users));
}
/**
* Add users to a reference
* @param path
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to add
* @return completion
*/
public Completable addUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.addUsers(path, dataProvider, users)
.observeOn(RX.main());
}
/**
* Updates a user for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param user to update
* @return completion
*/
public Completable updateUser(Path path, User.DataProvider dataProvider, User user) {
return updateUsers(path, dataProvider, user);
}
/**
* Update users for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to update
* @return completion
*/
public Completable updateUsers(Path path, User.DataProvider dataProvider, User... users) {
return updateUsers(path, dataProvider, Arrays.asList(users));
}
/**
* Update users for a reference
* @param path for users
* @param dataProvider a callback to extract the data to add from the user
* this allows us to use one method to write to multiple different places
* @param users to update
* @return completion
*/
public Completable updateUsers(Path path, User.DataProvider dataProvider, List<? extends User> users) {
return Fire.stream().getFirebaseService().core
.updateUsers(path, dataProvider, users)
.observeOn(RX.main());
}
@Override
public void connect() throws Exception {
dm.add(Single.defer((Callable<SingleSource<Optional<Sendable>>>) () -> {
// If we are deleting the messages on receipt then we want to get all new messages
if (Fire.stream().getConfig().deleteMessagesOnReceipt) {
return Single.just(Optional.empty());
} else {
return Fire.stream().getFirebaseService().core.lastMessage(messagesPath());
}
}).flatMapObservable((Function<Optional<Sendable>, ObservableSource<Event<Sendable>>>) optional -> {
Date date = null;
if (!optional.isEmpty()) {
if (Fire.stream().getConfig().emitEventForLastMessage) {
passMessageResultToStream(new Event<>(optional.get(), EventType.Added));
}
date = optional.get().getDate();
}
return messagesOn(date);
}).subscribe(this::passMessageResultToStream, this));
}
@Override
public void disconnect () {
dm.dispose();
}
/**
* Convenience method to cast sendables and send them to the correct events
* @param event sendable event
*/
protected void passMessageResultToStream(Event<Sendable> event) {
Sendable sendable = event.get();
// if (Fire.stream().isBlocked(new User(sendable.getFrom()))) {
// return;
// }
debug("Sendable: " + sendable.getType() + " " + sendable.getId() + ", date: " + sendable.getDate().getTime());
// In general, we are mostly interested when messages are added
if (sendable.isType(SendableType.message())) {
events.getMessages().accept(event.to(sendable.toMessage()));
}
if (sendable.isType(SendableType.deliveryReceipt())) {
events.getDeliveryReceipts().accept(event.to(sendable.toDeliveryReceipt()));
}
if (sendable.isType(SendableType.typingState())) {
TypingState typingState = sendable.toTypingState();
if (event.isAdded()) {
typingState.setBodyType(TypingStateType.typing());
}
if (event.isRemoved()) {
typingState.setBodyType(TypingStateType.none());
}
events.getTypingStates().accept(new Event<>(typingState, EventType.Modified));
}
if (sendable.isType(SendableType.invitation())) {
events.getInvitations().accept(event.to(sendable.toInvitation()));
}
if (sendable.isType(SendableType.presence())) {
events.getPresences().accept(event.to(sendable.toPresence()));
}
}
@Override
public List<Sendable> getSendables() {
return sendables;
}
@Override
public List<Sendable> getSendables(SendableType type) {
List<Sendable> sendables = new ArrayList<>();
for (Sendable s: sendables) {
if (s.isType(type)) {
sendables.add(s);
}
}
return sendables;
}
// public DeliveryReceipt getDeliveryReceiptsForMessage(String messageId, DeliveryReceiptType type) {
// List<DeliveryReceipt> receipts = getSendables(DeliveryReceipt.class);
// for (DeliveryReceipt receipt: receipts) {
// try {
// if (receipt.getMessageId().equals(messageId) && receipt.getDeliveryReceiptType() == type) {
// return receipt;
// }
// } catch (Exception ignored) {}
// }
// return null;
// }
public <T extends Sendable> List<T> getSendables(Class<T> clazz) {
return new Sendable.Converter<T>(clazz).convert(getSendables());
}
@Override
public Sendable getSendable(String id) {
for (Sendable s: sendables) {
if (s.getId().equals(id)) {
return s;
}
}
return null;
}
/**
* returns the events object which exposes the different sendable streams
* @return events
*/
public Events getSendableEvents() {
return events;
}
/**
* Overridable messages reference
* @return Firestore messages reference
*/
protected abstract Path messagesPath();
@Override
public DisposableMap getDisposableMap() {
return dm;
}
@Override
public void manage(Disposable disposable) {
getDisposableMap().add(disposable);
}
public abstract Completable markRead(Sendable message);
public abstract Completable markReceived(Sendable message);
public void debug(String text) {
if (Fire.stream().getConfig().debugEnabled) {
Logger.debug(text);
}
}
protected Predicate<Event<? extends Sendable>> deliveryReceiptFilter() {
return Filter.and(new ArrayList<Predicate<Event<? extends Sendable>>>() {{
add(Fire.internal().getMarkReceivedFilter());
add(Filter.notFromMe());
add(Filter.byEventType(EventType.Added));
}});
}
@Override
public void onSubscribe(Disposable d) {
dm.add(d);
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
events.publishThrowable().accept(e);
}
/**
* Error handler method so we can redirect all errors to the error events
* @param throwable - the events error
*/
@Override
public void accept(Throwable throwable) {
onError(throwable);
}
}
|
chat-sdk/chat-sdk-android
|
firestream/src/main/java/firestream/chat/chat/AbstractChat.java
|
Java
|
apache-2.0
| 15,606 |
package org.xmlcml.norma.biblio;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.xmlcml.graphics.html.HtmlDiv;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
public class RISEntry {
public static final Logger LOG = Logger.getLogger(RISEntry.class);
static {
LOG.setLevel(Level.DEBUG);
}
private static final String AB = "AB";
private static final String ER = "ER";
public static final String TY = "TY";
public final static String START_DASH_SPACE = "^[A-Z][A-Z][A-Z ][A-Z ]\\- .*"; // PMID breaks the rules, this covers it
public final static String DASH_SPACE = "- "; // PMID breaks the rules, this covers it
public static final String PMID = "PMID";
private String type;
private StringBuilder currentValue;
private Multimap<String, StringBuilder> valuesByField = ArrayListMultimap.create();
private boolean canAdd;
private List<String> fieldList;
String abstractx;
public RISEntry() {
canAdd = true;
fieldList = new ArrayList<String>();
}
public String getType() {
return type;
}
public String addLine(String line) {
if (!canAdd) {
System.err.println("Cannot add line: "+line);
}
String field = null;
if (line.matches(START_DASH_SPACE)) {
String[] ss = line.split(DASH_SPACE);
field = ss[0].trim();
recordUnknownFields(field);
if (!fieldList.contains(field)) {
fieldList.add(field);
}
if (ss.length == 1) {
currentValue = null;
if (field.equals(ER)) {
canAdd = false;
}
} else {
currentValue = new StringBuilder(ss[1].trim());
valuesByField.put(field, currentValue);
}
} else {
String v = line.trim();
if (canAdd) {
if (currentValue != null) {
currentValue.append(" "+v);
} else {
System.err.println("Cannot add "+line);
}
} else {
System.err.println("Cannot add: "+line);
}
}
return field;
}
private void recordUnknownFields(String field) {
if (!RISParser.FIELD_MAP.containsKey(field)) {
if (!RISParser.UNKNOWN_KEYS.contains(field)) {
RISParser.addUnknownKey(field);
LOG.trace("Unknown Key: "+field);
}
}
}
public HtmlDiv createAbstractHtml() {
List<StringBuilder> abstracts = new ArrayList<StringBuilder>(valuesByField.get(AB));
HtmlDiv abstractDiv = null;
if (abstracts.size() == 1) {
abstractx = abstracts.get(0).toString();
BiblioAbstractAnalyzer abstractAnalyzer = new BiblioAbstractAnalyzer();
abstractDiv = abstractAnalyzer.createAndAnalyzeSections(abstractx);
}
return abstractDiv;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (String key : fieldList) {
sb.append(key+": ");
List<StringBuilder> values = new ArrayList<StringBuilder>(valuesByField.get(key));
if (values.size() == 1) {
sb.append(values.get(0).toString()+"\n");
} else {
sb.append("\n");
for (StringBuilder sb0 : values) {
sb.append(" "+sb0.toString()+"\n");
}
}
}
return sb.toString();
}
public String getAbstractString() {
if (abstractx == null) {
createAbstractHtml();
}
return abstractx;
}
}
|
petermr/norma
|
src/main/java/org/xmlcml/norma/biblio/RISEntry.java
|
Java
|
apache-2.0
| 3,184 |
/**
* <copyright>
*
* Copyright (c) 2010 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Reiner Hille-Doering (SAP AG) - initial API and implementation and/or initial documentation
*
* </copyright>
*/
package org.eclipse.bpmn2.impl;
import java.util.Collection;
import java.util.List;
import org.eclipse.bpmn2.Bpmn2Package;
import org.eclipse.bpmn2.DataState;
import org.eclipse.bpmn2.DataStore;
import org.eclipse.bpmn2.DataStoreReference;
import org.eclipse.bpmn2.ItemAwareElement;
import org.eclipse.bpmn2.ItemDefinition;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import org.eclipse.securebpmn2.ItemAwareElementAction;
import org.eclipse.securebpmn2.Securebpmn2Package;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Data Store Reference</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataState <em>Data State</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemSubjectRef <em>Item Subject Ref</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getItemAwareElementActions <em>Item Aware Element Actions</em>}</li>
* <li>{@link org.eclipse.bpmn2.impl.DataStoreReferenceImpl#getDataStoreRef <em>Data Store Ref</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class DataStoreReferenceImpl extends FlowElementImpl implements
DataStoreReference {
/**
* The cached value of the '{@link #getDataState() <em>Data State</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDataState()
* @generated
* @ordered
*/
protected DataState dataState;
/**
* The cached value of the '{@link #getItemSubjectRef() <em>Item Subject Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getItemSubjectRef()
* @generated
* @ordered
*/
protected ItemDefinition itemSubjectRef;
/**
* The cached value of the '{@link #getItemAwareElementActions() <em>Item Aware Element Actions</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getItemAwareElementActions()
* @generated
* @ordered
*/
protected EList<ItemAwareElementAction> itemAwareElementActions;
/**
* The cached value of the '{@link #getDataStoreRef() <em>Data Store Ref</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDataStoreRef()
* @generated
* @ordered
*/
protected DataStore dataStoreRef;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DataStoreReferenceImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Bpmn2Package.Literals.DATA_STORE_REFERENCE;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataState getDataState() {
return dataState;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDataState(DataState newDataState,
NotificationChain msgs) {
DataState oldDataState = dataState;
dataState = newDataState;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this,
Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
oldDataState, newDataState);
if (msgs == null)
msgs = notification;
else
msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDataState(DataState newDataState) {
if (newDataState != dataState) {
NotificationChain msgs = null;
if (dataState != null)
msgs = ((InternalEObject) dataState)
.eInverseRemove(
this,
EOPPOSITE_FEATURE_BASE
- Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
null, msgs);
if (newDataState != null)
msgs = ((InternalEObject) newDataState)
.eInverseAdd(
this,
EOPPOSITE_FEATURE_BASE
- Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
null, msgs);
msgs = basicSetDataState(newDataState, msgs);
if (msgs != null)
msgs.dispatch();
} else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE,
newDataState, newDataState));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ItemDefinition getItemSubjectRef() {
if (itemSubjectRef != null && itemSubjectRef.eIsProxy()) {
InternalEObject oldItemSubjectRef = (InternalEObject) itemSubjectRef;
itemSubjectRef = (ItemDefinition) eResolveProxy(oldItemSubjectRef);
if (itemSubjectRef != oldItemSubjectRef) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(
this,
Notification.RESOLVE,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF,
oldItemSubjectRef, itemSubjectRef));
}
}
return itemSubjectRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public ItemDefinition basicGetItemSubjectRef() {
return itemSubjectRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setItemSubjectRef(ItemDefinition newItemSubjectRef) {
ItemDefinition oldItemSubjectRef = itemSubjectRef;
itemSubjectRef = newItemSubjectRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF,
oldItemSubjectRef, itemSubjectRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public List<ItemAwareElementAction> getItemAwareElementActions() {
if (itemAwareElementActions == null) {
itemAwareElementActions = new EObjectContainmentWithInverseEList<ItemAwareElementAction>(
ItemAwareElementAction.class,
this,
Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS,
Securebpmn2Package.ITEM_AWARE_ELEMENT_ACTION__ITEM_AWARE_ELEMENT);
}
return itemAwareElementActions;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataStore getDataStoreRef() {
if (dataStoreRef != null && dataStoreRef.eIsProxy()) {
InternalEObject oldDataStoreRef = (InternalEObject) dataStoreRef;
dataStoreRef = (DataStore) eResolveProxy(oldDataStoreRef);
if (dataStoreRef != oldDataStoreRef) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF,
oldDataStoreRef, dataStoreRef));
}
}
return dataStoreRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DataStore basicGetDataStoreRef() {
return dataStoreRef;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setDataStoreRef(DataStore newDataStoreRef) {
DataStore oldDataStoreRef = dataStoreRef;
dataStoreRef = newDataStoreRef;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET,
Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF,
oldDataStoreRef, dataStoreRef));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return ((InternalEList<InternalEObject>) (InternalEList<?>) getItemAwareElementActions())
.basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd,
int featureID, NotificationChain msgs) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return basicSetDataState(null, msgs);
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return ((InternalEList<?>) getItemAwareElementActions())
.basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return getDataState();
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
if (resolve)
return getItemSubjectRef();
return basicGetItemSubjectRef();
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return getItemAwareElementActions();
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
if (resolve)
return getDataStoreRef();
return basicGetDataStoreRef();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
setDataState((DataState) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
setItemSubjectRef((ItemDefinition) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
getItemAwareElementActions().clear();
getItemAwareElementActions().addAll(
(Collection<? extends ItemAwareElementAction>) newValue);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
setDataStoreRef((DataStore) newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
setDataState((DataState) null);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
setItemSubjectRef((ItemDefinition) null);
return;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
getItemAwareElementActions().clear();
return;
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
setDataStoreRef((DataStore) null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return dataState != null;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
return itemSubjectRef != null;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return itemAwareElementActions != null
&& !itemAwareElementActions.isEmpty();
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STORE_REF:
return dataStoreRef != null;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eBaseStructuralFeatureID(int derivedFeatureID, Class<?> baseClass) {
if (baseClass == ItemAwareElement.class) {
switch (derivedFeatureID) {
case Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE:
return Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF:
return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF;
case Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS:
return Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS;
default:
return -1;
}
}
return super.eBaseStructuralFeatureID(derivedFeatureID, baseClass);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public int eDerivedStructuralFeatureID(int baseFeatureID, Class<?> baseClass) {
if (baseClass == ItemAwareElement.class) {
switch (baseFeatureID) {
case Bpmn2Package.ITEM_AWARE_ELEMENT__DATA_STATE:
return Bpmn2Package.DATA_STORE_REFERENCE__DATA_STATE;
case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_SUBJECT_REF:
return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_SUBJECT_REF;
case Bpmn2Package.ITEM_AWARE_ELEMENT__ITEM_AWARE_ELEMENT_ACTIONS:
return Bpmn2Package.DATA_STORE_REFERENCE__ITEM_AWARE_ELEMENT_ACTIONS;
default:
return -1;
}
}
return super.eDerivedStructuralFeatureID(baseFeatureID, baseClass);
}
} //DataStoreReferenceImpl
|
adbrucker/SecureBPMN
|
designer/src/org.activiti.designer.model/src/main/java/org/eclipse/bpmn2/impl/DataStoreReferenceImpl.java
|
Java
|
apache-2.0
| 13,233 |
/*
* Kendo UI v2014.3.1119 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["de-LI"] = {
name: "de-LI",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": "'",
".": ".",
groupSize: [3],
symbol: "CHF"
}
},
calendars: {
standard: {
days: {
names: ["Sonntag","Montag","Dienstag","Mittwoch","Donnerstag","Freitag","Samstag"],
namesAbbr: ["So","Mo","Di","Mi","Do","Fr","Sa"],
namesShort: ["So","Mo","Di","Mi","Do","Fr","Sa"]
},
months: {
names: ["Januar","Februar","März","April","Mai","Juni","Juli","August","September","Oktober","November","Dezember",""],
namesAbbr: ["Jan","Feb","Mrz","Apr","Mai","Jun","Jul","Aug","Sep","Okt","Nov","Dez",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "dddd, d. MMMM yyyy",
F: "dddd, d. MMMM yyyy HH:mm:ss",
g: "dd.MM.yyyy HH:mm",
G: "dd.MM.yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "HH:mm",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
y-todorov/Inventory
|
Inventory.MVC/Scripts/Kendo/cultures/kendo.culture.de-LI.js
|
JavaScript
|
apache-2.0
| 2,637 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.SourceBrowser.Common;
using Newtonsoft.Json;
namespace Microsoft.SourceBrowser.HtmlGenerator
{
public class TypeScriptSupport
{
private static readonly HashSet<string> alreadyProcessed = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, List<Reference>> references;
private List<string> declarations;
public Dictionary<string, List<Tuple<string, long>>> SymbolIDToListOfLocationsMap { get; private set; }
public void Generate(IEnumerable<string> typeScriptFiles, string solutionDestinationFolder)
{
if (typeScriptFiles == null || !typeScriptFiles.Any())
{
return;
}
var projectDestinationFolder = Path.Combine(solutionDestinationFolder, Constants.TypeScriptFiles).MustBeAbsolute();
declarations = new List<string>();
references = new Dictionary<string, List<Reference>>(StringComparer.OrdinalIgnoreCase);
SymbolIDToListOfLocationsMap = new Dictionary<string, List<Tuple<string, long>>>();
var list = new List<string>();
string libFile = null;
foreach (var file in typeScriptFiles)
{
if (!alreadyProcessed.Contains(file))
{
if (libFile == null && string.Equals(Path.GetFileName(file), "lib.d.ts", StringComparison.OrdinalIgnoreCase))
{
libFile = file;
}
else
{
list.Add(file);
}
}
}
if (libFile == null)
{
libFile = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptSupport", "lib.d.ts");
}
try
{
GenerateCore(list, libFile);
}
catch (Exception ex)
{
Log.Exception(ex, "Error when generating TypeScript files");
return;
}
ProjectGenerator.GenerateReferencesDataFilesToAssembly(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles,
references);
declarations.Sort();
Serialization.WriteDeclaredSymbols(
projectDestinationFolder,
declarations);
ProjectGenerator.GenerateSymbolIDToListOfDeclarationLocationsMap(
projectDestinationFolder,
SymbolIDToListOfLocationsMap);
}
private void GenerateCore(IEnumerable<string> fileNames, string libFile)
{
var output = Path.Combine(Common.Paths.BaseAppFolder, "output");
if (Directory.Exists(output))
{
Directory.Delete(output, recursive: true);
}
var json = JsonConvert.SerializeObject(new { fileNames, libFile, outputFolder = output });
var argumentsJson = Path.Combine(Common.Paths.BaseAppFolder, "TypeScriptAnalyzerArguments.json");
File.WriteAllText(argumentsJson, json);
var analyzerJs = Path.Combine(Common.Paths.BaseAppFolder, @"TypeScriptSupport\analyzer.js");
var arguments = string.Format("\"{0}\" {1}", analyzerJs, argumentsJson);
ProcessLaunchService.ProcessRunResult result;
try
{
using (Disposable.Timing("Calling Node.js to process TypeScript"))
{
result = new ProcessLaunchService().RunAndRedirectOutput("node", arguments);
}
}
catch (Win32Exception)
{
Log.Write("Warning: Node.js is required to generate TypeScript files. Skipping generation. Download Node.js from https://nodejs.org.", ConsoleColor.Yellow);
Log.Exception("Node.js is not installed.");
return;
}
using (Disposable.Timing("Generating TypeScript files"))
{
foreach (var file in Directory.GetFiles(output))
{
if (Path.GetFileNameWithoutExtension(file) == "ok")
{
continue;
}
if (Path.GetFileNameWithoutExtension(file) == "error")
{
var errorContent = File.ReadAllText(file);
Log.Exception(DateTime.Now.ToString() + " " + errorContent);
return;
}
var text = File.ReadAllText(file);
AnalyzedFile analysis = JsonConvert.DeserializeObject<AnalyzedFile>(text);
EnsureFileGeneratedAndGetUrl(analysis);
}
}
}
public void EnsureFileGeneratedAndGetUrl(AnalyzedFile analysis)
{
string localFileSystemPath = analysis.fileName;
localFileSystemPath = Path.GetFullPath(localFileSystemPath);
string destinationFilePath = GetDestinationFilePath(localFileSystemPath);
if (!File.Exists(destinationFilePath))
{
Generate(localFileSystemPath, destinationFilePath, analysis.syntacticClassifications, analysis.semanticClassifications);
}
}
public static string GetDestinationFilePath(string sourceFilePath)
{
var url = sourceFilePath + ".html";
url = url.Replace(":", "");
url = url.Replace(" ", "");
url = url.Replace(@"\bin\", @"\bin_\");
if (url.StartsWith(@"\\", StringComparison.Ordinal))
{
url = url.Substring(2);
}
url = Constants.TypeScriptFiles + @"\" + url;
url = Path.Combine(Paths.SolutionDestinationFolder, url);
return url;
}
private void Generate(
string sourceFilePath,
string destinationHtmlFilePath,
ClassifiedRange[] syntacticRanges,
ClassifiedRange[] semanticRanges)
{
Log.Write(destinationHtmlFilePath);
var sb = new StringBuilder();
var lines = File.ReadAllLines(sourceFilePath);
var text = File.ReadAllText(sourceFilePath);
var lineCount = lines.Length;
var lineLengths = TextUtilities.GetLineLengths(text);
var ranges = PrepareRanges(syntacticRanges, semanticRanges, text);
var relativePathToRoot = Paths.CalculateRelativePathToRoot(destinationHtmlFilePath, Paths.SolutionDestinationFolder);
var prefix = Markup.GetDocumentPrefix(Path.GetFileName(sourceFilePath), relativePathToRoot, lineCount, "ix");
sb.Append(prefix);
var displayName = GetDisplayName(destinationHtmlFilePath);
const string assemblyName = "TypeScriptFiles";
var url = "/#" + assemblyName + "/" + displayName.Replace('\\', '/');
displayName = @"\\" + displayName;
Markup.WriteLinkPanel(s => sb.AppendLine(s), fileLink: (displayName, url));
// pass a value larger than 0 to generate line numbers statically at HTML generation time
var table = Markup.GetTablePrefix();
sb.AppendLine(table);
var localSymbolIdMap = new Dictionary<string, int>();
foreach (var range in ranges)
{
range.lineNumber = TextUtilities.GetLineNumber(range.start, lineLengths);
var line = TextUtilities.GetLineFromPosition(range.start, text);
range.column = range.start - line.Item1;
range.lineText = text.Substring(line.Item1, line.Item2);
GenerateRange(sb, range, destinationHtmlFilePath, localSymbolIdMap);
}
var suffix = Markup.GetDocumentSuffix();
sb.AppendLine(suffix);
var folder = Path.GetDirectoryName(destinationHtmlFilePath);
Directory.CreateDirectory(folder);
File.WriteAllText(destinationHtmlFilePath, sb.ToString());
}
public static ClassifiedRange[] PrepareRanges(
ClassifiedRange[] syntacticRanges,
ClassifiedRange[] semanticRanges,
string text)
{
foreach (var range in semanticRanges)
{
range.IsSemantic = true;
}
var rangesSortedByStart = syntacticRanges
.Concat(semanticRanges)
.Where(r => r.length > 0)
.OrderBy(r => r.start)
.ToArray();
var midpoints = rangesSortedByStart
.Select(r => r.start)
.Concat(
rangesSortedByStart
.Select(r => r.end))
.Distinct()
.OrderBy(n => n)
.ToArray();
var ranges = RemoveIntersectingRanges(
text,
rangesSortedByStart,
midpoints);
ranges = RemoveOverlappingRanges(
text,
ranges);
ranges = RangeUtilities.FillGaps(
text,
ranges,
r => r.start,
r => r.length,
(s, l, t) => new ClassifiedRange(t, s, l));
foreach (var range in ranges)
{
if (range.text == null)
{
range.text = text.Substring(range.start, range.length);
}
}
return ranges;
}
public static ClassifiedRange[] RemoveOverlappingRanges(string text, ClassifiedRange[] ranges)
{
var output = new List<ClassifiedRange>(ranges.Length);
for (int i = 0; i < ranges.Length; i++)
{
ClassifiedRange best = ranges[i];
while (i < ranges.Length - 1 && ranges[i].start == ranges[i + 1].start)
{
best = ChooseBetterRange(best, ranges[i + 1]);
i++;
}
output.Add(best);
}
return output.ToArray();
}
private static ClassifiedRange ChooseBetterRange(ClassifiedRange left, ClassifiedRange right)
{
if (left == null)
{
return right;
}
if (right == null)
{
return left;
}
if (left.IsSemantic != right.IsSemantic)
{
if (left.IsSemantic)
{
right.classification = left.classification;
return right;
}
else
{
left.classification = right.classification;
return left;
}
}
ClassifiedRange victim = left;
ClassifiedRange winner = right;
if (left.classification == "comment")
{
victim = left;
winner = right;
}
if (right.classification == "comment")
{
victim = right;
winner = left;
}
if (winner.hyperlinks == null && victim.hyperlinks != null)
{
winner.hyperlinks = victim.hyperlinks;
}
if (winner.classification == "text")
{
winner.classification = victim.classification;
}
return winner;
}
public static ClassifiedRange[] RemoveIntersectingRanges(
string text,
ClassifiedRange[] rangesSortedByStart,
int[] midpoints)
{
var result = new List<ClassifiedRange>();
int currentEndpoint = 0;
int currentRangeIndex = 0;
for (; currentEndpoint < midpoints.Length && currentRangeIndex < rangesSortedByStart.Length;)
{
while (
currentRangeIndex < rangesSortedByStart.Length &&
rangesSortedByStart[currentRangeIndex].start == midpoints[currentEndpoint])
{
var currentRange = rangesSortedByStart[currentRangeIndex];
if (currentRange.end == midpoints[currentEndpoint + 1])
{
result.Add(currentRange);
}
else
{
int endpoint = currentEndpoint;
do
{
result.Add(
new ClassifiedRange(
text,
midpoints[endpoint],
midpoints[endpoint + 1] - midpoints[endpoint],
currentRange));
endpoint++;
}
while (endpoint < midpoints.Length && midpoints[endpoint] < currentRange.end);
}
currentRangeIndex++;
}
currentEndpoint++;
}
return result.ToArray();
}
private void GenerateRange(
StringBuilder sb,
ClassifiedRange range,
string destinationFilePath,
Dictionary<string, int> localSymbolIdMap)
{
var html = range.text;
html = Markup.HtmlEscape(html);
var localRelativePath = destinationFilePath.Substring(
Path.Combine(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles).Length + 1);
localRelativePath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length);
string classAttributeValue = GetSpanClass(range.classification);
HtmlElementInfo hyperlinkInfo = GenerateLinks(range, destinationFilePath, localSymbolIdMap);
if (hyperlinkInfo == null)
{
if (classAttributeValue == null)
{
sb.Append(html);
return;
}
if (classAttributeValue == "k")
{
sb.Append("<b>").Append(html).Append("</b>");
return;
}
}
var elementName = "span";
if (hyperlinkInfo != null)
{
elementName = hyperlinkInfo.Name;
}
sb.Append("<").Append(elementName);
bool overridingClassAttributeSpecified = false;
if (hyperlinkInfo != null)
{
foreach (var attribute in hyperlinkInfo.Attributes)
{
const string typeScriptFilesR = "/TypeScriptFiles/R/";
if (attribute.Key == "href" && attribute.Value.StartsWith(typeScriptFilesR, StringComparison.Ordinal))
{
var streamPosition = sb.Length + 7 + typeScriptFilesR.Length; // exact offset into <a href="HERE
ProjectGenerator.AddDeclaredSymbolToRedirectMap(
SymbolIDToListOfLocationsMap,
attribute.Value.Substring(typeScriptFilesR.Length, 16),
localRelativePath,
streamPosition);
}
AddAttribute(sb, attribute.Key, attribute.Value);
if (attribute.Key == "class")
{
overridingClassAttributeSpecified = true;
}
}
}
if (!overridingClassAttributeSpecified)
{
AddAttribute(sb, "class", classAttributeValue);
}
sb.Append('>');
sb.Append(html);
sb.Append("</").Append(elementName).Append(">");
}
private void AddAttribute(StringBuilder sb, string name, string value)
{
if (value != null)
{
sb.Append(" ").Append(name).Append("=\"").Append(value).Append("\"");
}
}
private int GetLocalId(string symbolId, Dictionary<string, int> localSymbolIdMap)
{
int localId = 0;
if (!localSymbolIdMap.TryGetValue(symbolId, out localId))
{
localId = localSymbolIdMap.Count;
localSymbolIdMap.Add(symbolId, localId);
}
return localId;
}
private HtmlElementInfo GenerateLinks(ClassifiedRange range, string destinationHtmlFilePath, Dictionary<string, int> localSymbolIdMap)
{
HtmlElementInfo result = null;
var localRelativePath = destinationHtmlFilePath.Substring(
Path.Combine(
Paths.SolutionDestinationFolder,
Constants.TypeScriptFiles).Length);
if (!string.IsNullOrEmpty(range.definitionSymbolId))
{
var definitionSymbolId = SymbolIdService.GetId(range.definitionSymbolId);
if (range.IsSymbolLocalOnly())
{
var localId = GetLocalId(definitionSymbolId, localSymbolIdMap);
result = new HtmlElementInfo
{
Name = "span",
Attributes =
{
{ "id", "r" + localId + " rd" },
{ "class", "r" + localId + " r" }
}
};
return result;
}
result = new HtmlElementInfo
{
Name = "a",
Attributes =
{
{ "id", definitionSymbolId },
{ "href", "/TypeScriptFiles/" + Constants.ReferencesFileName + "/" + definitionSymbolId + ".html" },
{ "target", "n" }
}
};
var searchString = range.searchString;
if (!string.IsNullOrEmpty(searchString) && searchString.Length > 2)
{
lock (declarations)
{
searchString = searchString.StripQuotes();
if (IsWellFormed(searchString))
{
var declaration = string.Join(";",
searchString, // symbol name
definitionSymbolId, // 8-byte symbol ID
range.definitionKind, // kind (e.g. "class")
Markup.EscapeSemicolons(range.fullName), // symbol full name and signature
GetGlyph(range.definitionKind) // glyph number
);
declarations.Add(declaration);
}
}
}
}
if (range.hyperlinks == null || range.hyperlinks.Length == 0)
{
return result;
}
var hyperlink = range.hyperlinks[0];
var symbolId = SymbolIdService.GetId(hyperlink.symbolId);
if (range.IsSymbolLocalOnly() || localSymbolIdMap.ContainsKey(symbolId))
{
var localId = GetLocalId(symbolId, localSymbolIdMap);
result = new HtmlElementInfo
{
Name = "span",
Attributes =
{
{ "class", "r" + localId + " r" }
}
};
return result;
}
var hyperlinkDestinationFile = Path.GetFullPath(hyperlink.sourceFile);
hyperlinkDestinationFile = GetDestinationFilePath(hyperlinkDestinationFile);
string href = "";
if (!string.Equals(hyperlinkDestinationFile, destinationHtmlFilePath, StringComparison.OrdinalIgnoreCase))
{
href = Paths.MakeRelativeToFile(hyperlinkDestinationFile, destinationHtmlFilePath);
href = href.Replace('\\', '/');
}
href = href + "#" + symbolId;
if (result == null)
{
result = new HtmlElementInfo
{
Name = "a",
Attributes =
{
{ "href", href },
{ "target", "s" },
}
};
}
else if (!result.Attributes.ContainsKey("href"))
{
result.Attributes.Add("href", href);
result.Attributes.Add("target", "s");
}
lock (this.references)
{
var lineNumber = range.lineNumber + 1;
var linkToReference = ".." + localRelativePath + "#" + lineNumber.ToString();
var start = range.column;
var end = range.column + range.text.Length;
var lineText = Markup.HtmlEscape(range.lineText, ref start, ref end);
var reference = new Reference
{
FromAssemblyId = Constants.TypeScriptFiles,
ToAssemblyId = Constants.TypeScriptFiles,
FromLocalPath = localRelativePath.Substring(0, localRelativePath.Length - ".html".Length).Replace('\\', '/'),
Kind = ReferenceKind.Reference,
ToSymbolId = symbolId,
ToSymbolName = range.text,
ReferenceLineNumber = lineNumber,
ReferenceLineText = lineText,
ReferenceColumnStart = start,
ReferenceColumnEnd = end,
Url = linkToReference.Replace('\\', '/')
};
if (!references.TryGetValue(symbolId, out List<Reference> bucket))
{
bucket = new List<Reference>();
references.Add(symbolId, bucket);
}
bucket.Add(reference);
}
return result;
}
private bool IsWellFormed(string searchString)
{
return searchString.Length > 2
&& !searchString.Contains(";")
&& !searchString.Contains("\n");
}
private string GetGlyph(string definitionKind)
{
switch (definitionKind)
{
case "variable":
return "42";
case "function":
return "72";
case "parameter":
return "42";
case "interface":
return "48";
case "property":
return "102";
case "method":
return "72";
case "type parameter":
return "114";
case "module":
return "150";
case "class":
return "0";
case "constructor":
return "72";
case "enum":
return "18";
case "enum member":
return "24";
case "import":
return "6";
case "get accessor":
return "72";
case "set accessor":
return "72";
default:
return "195";
}
}
private string GetSpanClass(string classification)
{
if (classification == "keyword")
{
return "k";
}
else if (classification == "comment")
{
return "c";
}
else if (classification == "string")
{
return "s";
}
else if (classification == "class name")
{
return "t";
}
else if (classification == "enum name")
{
return "t";
}
else if (classification == "interface name" || classification == "type alias name")
{
return "t";
}
else if (classification == "type parameter name")
{
return "t";
}
else if (classification == "module name")
{
return "t";
}
return null;
}
private string GetDisplayName(string destinationHtmlFilePath)
{
var result = Path.GetFileNameWithoutExtension(destinationHtmlFilePath);
var lengthOfPrefixToTrim = Paths.SolutionDestinationFolder.Length + Constants.TypeScriptFiles.Length + 2;
result = destinationHtmlFilePath.Substring(lengthOfPrefixToTrim, destinationHtmlFilePath.Length - lengthOfPrefixToTrim - 5); // strip ".html"
return result;
}
}
}
|
KirillOsenkov/SourceBrowser
|
src/HtmlGenerator/Pass1-Generation/TypeScriptSupport.cs
|
C#
|
apache-2.0
| 26,413 |
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package main
import (
"errors"
"fmt"
"strconv"
"encoding/json"
"time"
"strings"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}
var marbleIndexStr = "_marbleindex"
var driverIndexStr = "_driverindex" //name for the key/value that will store a list of all known marbles
var openTradesStr = "_opentrades" //name for the key/value that will store all open trades
type Marble struct{
Name string `json:"name"` //the fieldtags are needed to keep case from bouncing around
Color string `json:"color"`
Size int `json:"size"`
User string `json:"user"`
}
type Driver struct{
FirstName string `json:"firstname"` //the fieldtags are needed to keep case from bouncing around
LastName string `json:"lastname"`
Email string `json:"email"`
Mobile string `json:"mobile"`
Password string `json:"password"`
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
Status string `json:"status"`
}
type Description struct{
Color string `json:"color"`
Size int `json:"size"`
}
type AnOpenTrade struct{
User string `json:"user"` //user who created the open trade order
Timestamp int64 `json:"timestamp"` //utc timestamp of creation
Want Description `json:"want"` //description of desired marble
Willing []Description `json:"willing"` //array of marbles willing to trade away
}
type AllTrades struct{
OpenTrades []AnOpenTrade `json:"open_trades"`
}
type Adminlogin struct{
Userid string `json:"userid"` //User login for system Admin
Password string `json:"password"`
}
// ============================================================================================================================
// Main
// ============================================================================================================================
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
// ============================================================================================================================
// Init - reset all the things
// ============================================================================================================================
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
var Aval int
var err error
//Changes for the Hertz Blockchain
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
//Write the User Id "mail Id" arg[0] and password arg[1]
userid := args[0] //argument for UserID
password := args[1] //argument for password
str := `{"userid": "` + userid+ `", "password": "` + password + `"}`
err = stub.PutState(userid, []byte(str)) //Put the userid and password in blockchain
if err != nil {
return nil, err
}
//End of Changes for the Hertz Blockchain}
// Initialize the chaincode
Aval, err = strconv.Atoi(args[0])
if err != nil {
return nil, errors.New("Expecting integer value for asset holding")
}
// Write the state to the ledger
err = stub.PutState("abc", []byte(strconv.Itoa(Aval))) //making a test var "abc", I find it handy to read/write to it right away to test the network
if err != nil {
return nil, err
}
var empty []string
jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(marbleIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
//var empty []string
//jsonAsBytes, _ := json.Marshal(empty) //marshal an emtpy array of strings to clear the index
err = stub.PutState(driverIndexStr, jsonAsBytes)
if err != nil {
return nil, err
}
var trades AllTrades
jsonAsBytes, _ = json.Marshal(trades) //clear the open trade struct
err = stub.PutState(openTradesStr, jsonAsBytes)
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Run - Our entry point for Invocations - [LEGACY] obc-peer 4/25/2016
// ============================================================================================================================
func (t *SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("run is running " + function)
return t.Invoke(stub, function, args)
}
// ============================================================================================================================
// Invoke - Our entry point for Invocations
// ============================================================================================================================
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("invoke is running " + function)
// Handle different functions
if function == "init" { //initialize the chaincode state, used as reset
return t.Init(stub, "init", args)
} else if function == "delete" { //deletes an entity from its state
res, err := t.Delete(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "write" { //writes a value to the chaincode state
return t.Write(stub, args)
} else if function == "init_marble" { //create a new marble
return t.init_marble(stub, args)
} else if function == "signup_driver" { //create a new marble
return t.signup_driver(stub, args)
} else if function == "set_user" { //change owner of a marble
res, err := t.set_user(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
}else if function == "set_status" { //change owner of a marble
res, err := t.set_status(stub, args)
cleanTrades(stub) //lets make sure all open trades are still valid
return res, err
} else if function == "open_trade" { //create a new trade order
return t.open_trade(stub, args)
} else if function == "perform_trade" { //forfill an open trade order
res, err := t.perform_trade(stub, args)
cleanTrades(stub) //lets clean just in case
return res, err
} else if function == "remove_trade" { //cancel an open trade order
return t.remove_trade(stub, args)
}
fmt.Println("invoke did not find func: " + function) //error
return nil, errors.New("Received unknown function invocation")
}
// ============================================================================================================================
// Query - Our entry point for Queries
// ============================================================================================================================
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
fmt.Println("query is running " + function)
// Handle different functions
if function == "read" { //read a variable
return t.read(stub, args)
} else if function == "read_sysadmin" { //Read system admin User id and password
return t.read_sysadmin(stub, args)
}
fmt.Println("query did not find func: " + function) //error
return nil, errors.New("Received unknown function query")
}
// ============================================================================================================================
// Read - read a variable from chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) read(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, jsonResp string
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
}
name = args[0]
valAsbytes, err := stub.GetState(name) //get the var from chaincode state
if err != nil {
jsonResp = "{\"Error\":\"Failed to get state for " + name + "\"}"
return nil, errors.New(jsonResp)
}
return valAsbytes, nil //send it onward
}
//=============================================================
// Read - query function to read key/value pair (System Admin read User id and Password)
//===============================================================================================================================
func (t *SimpleChaincode) read_sysadmin(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query")
}
userid := args[0]
PassAsbytes, err := stub.GetState(userid)
if err != nil {
jsonResp := "{\"Error\":\"Failed to get state for " + userid + "\"}"
return nil, errors.New(jsonResp)
}
res := Adminlogin{}
json.Unmarshal(PassAsbytes,&res)
if res.Userid == userid{
fmt.Println("Userid Password Matched: " +res.Userid + res.Password)
}else {
fmt.Println("Wrong ID Password: " +res.Userid + res.Password)
}
return PassAsbytes, nil
}
// ============================================================================================================================
// Delete - remove a key/value pair from state
// ============================================================================================================================
func (t *SimpleChaincode) Delete(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
name := args[0]
err := stub.DelState(name) //remove the key from chaincode state
if err != nil {
return nil, errors.New("Failed to delete state")
}
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return nil, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
//remove marble from index
for i,val := range marbleIndex{
fmt.Println(strconv.Itoa(i) + " - looking at " + val + " for " + name)
if val == name{ //find the correct marble
fmt.Println("found marble")
marbleIndex = append(marbleIndex[:i], marbleIndex[i+1:]...) //remove it
for x:= range marbleIndex{ //debug prints...
fmt.Println(string(x) + " - " + marbleIndex[x])
}
break
}
}
jsonAsBytes, _ := json.Marshal(marbleIndex) //save new index
err = stub.PutState(marbleIndexStr, jsonAsBytes)
return nil, nil
}
// ============================================================================================================================
// Write - write variable into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) Write(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var name, value string // Entities
var err error
fmt.Println("running write()")
if len(args) != 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the variable and value to set")
}
name = args[0] //rename for funsies
value = args[1]
err = stub.PutState(name, []byte(value)) //write the variable into the chaincode state
if err != nil {
return nil, err
}
return nil, nil
}
// ============================================================================================================================
// Init Marble - create a new marble, store into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) init_marble(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3
// "asdf", "blue", "35", "bob"
if len(args) != 4 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
fmt.Println("-Amit C code-Init_marble driver")
//input sanitation
fmt.Println("- start init marble")
if len(args[0]) <= 0 {
return nil, errors.New("1st argument must be a non-empty string")
}
if len(args[1]) <= 0 {
return nil, errors.New("2nd argument must be a non-empty string")
}
if len(args[2]) <= 0 {
return nil, errors.New("3rd argument must be a non-empty string")
}
if len(args[3]) <= 0 {
return nil, errors.New("4th argument must be a non-empty string")
}
name := args[0]
color := strings.ToLower(args[1])
user := strings.ToLower(args[3])
size, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
//check if marble already exists
marbleAsBytes, err := stub.GetState(name)
if err != nil {
return nil, errors.New("Failed to get marble name")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res)
if res.Name == name{
fmt.Println("This marble arleady exists: " + name)
fmt.Println(res);
return nil, errors.New("This marble arleady exists") //all stop a marble by this name exists
}
//build the marble json string manually
str := `{"name": "` + name + `", "color": "` + color + `", "size": ` + strconv.Itoa(size) + `, "user": "` + user + `"}`
err = stub.PutState(name, []byte(str)) //store marble with id as key
if err != nil {
return nil, err
}
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return nil, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
//append
marbleIndex = append(marbleIndex, name) //add marble name to index list
fmt.Println("! marble index: ", marbleIndex)
jsonAsBytes, _ := json.Marshal(marbleIndex)
err = stub.PutState(marbleIndexStr, jsonAsBytes) //store name of marble
fmt.Println("- end init marble")
return nil, nil
}
// ============================================================================================================================
// Init Marble - create a new marble, store into chaincode state
// ============================================================================================================================
func (t *SimpleChaincode) signup_driver(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3
// "Mainak", "Mandal", "mainakmandal@hotmail.com", "password"
if len(args) != 9 {
return nil, errors.New("Incorrect number of arguments. Expecting 4")
}
//input sanitation
fmt.Println("- start signup driver")
fmt.Println("-Amit C code-signup driver")
if len(args[0]) <= 0 {
return nil, errors.New("1st argument must be a non-empty string")
}
if len(args[1]) <= 0 {
return nil, errors.New("2nd argument must be a non-empty string")
}
if len(args[2]) <= 0 {
return nil, errors.New("3rd argument must be a non-empty string")
}
if len(args[3]) <= 0 {
return nil, errors.New("4th argument must be a non-empty string")
}
if len(args[4]) <= 0 {
return nil, errors.New("5th argument must be a non-empty string")
}
if len(args[5]) <= 0 {
return nil, errors.New("6th argument must be a non-empty string")
}
if len(args[6]) <= 0 {
return nil, errors.New("7th argument must be a non-empty string")
}
if len(args[7]) <= 0 {
return nil, errors.New("8th argument must be a non-empty string")
}
if len(args[8]) <= 0 {
return nil, errors.New("9th argument must be a non-empty string")
}
firstname := args[0]
lastname := strings.ToLower(args[1])
email := strings.ToLower(args[2])
mobile := strings.ToLower(args[3])
password := strings.ToLower(args[4])
street := strings.ToLower(args[5])
city := strings.ToLower(args[6])
state := strings.ToLower(args[7])
zip := strings.ToLower(args[8])
status := "P"
//if err != nil {
//return nil, errors.New("3rd argument must be a numeric string")
//}
//check if marble already exists
driverAsBytes, err := stub.GetState(email)
if err != nil {
return nil, errors.New("Failed to get driver name")
}
res := Driver{}
json.Unmarshal(driverAsBytes, &res)
if res.Email == email{
fmt.Println("This marble arleady exists: " + email)
fmt.Println(res);
return nil, errors.New("This driver arleady exists") //all stop a marble by this name exists
}
//build the marble json string manually
str := `{"firstname": "` + firstname + `", "lastname": "` + lastname + `", "email": "` + email + `", "mobile": "` + mobile + `", "password": "` + password + `","street": "` + street + `","city": "` + city + `","state": "` + state + `","zip": "` + zip + `","status": "` + status + `"}`
err = stub.PutState(email, []byte(str)) //store marble with id as key
if err != nil {
return nil, err
}
//get the driver index
driversAsBytes, err := stub.GetState(driverIndexStr)
if err != nil {
return nil, errors.New("Failed to get driver index")
}
var driverIndex []string
json.Unmarshal(driversAsBytes, &driverIndex) //un stringify it aka JSON.parse()
//append
driverIndex = append(driverIndex, email) //add marble name to index list
fmt.Println("! driver index: ", driverIndex)
jsonAsBytes, _ := json.Marshal(driverIndex)
err = stub.PutState(driverIndexStr, jsonAsBytes) //store name of marble
fmt.Println("- end signup driver")
return nil, nil
}
// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_user(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1
// "name", "bob"
if len(args) < 2 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
fmt.Println("- start set user")
fmt.Println(args[0] + " - " + args[1])
marbleAsBytes, err := stub.GetState(args[0])
if err != nil {
return nil, errors.New("Failed to get thing")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
res.User = args[1] //change the user
jsonAsBytes, _ := json.Marshal(res)
err = stub.PutState(args[0], jsonAsBytes) //rewrite the marble with id as key
if err != nil {
return nil, err
}
fmt.Println("- end set user")
return nil, nil
}
// ============================================================================================================================
// Set User Permission on Marble
// ============================================================================================================================
func (t *SimpleChaincode) set_status(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1
// "email", "status"
if len(args) < 10 {
return nil, errors.New("Incorrect number of arguments. Expecting 2")
}
fmt.Println("- start set user")
fmt.Println(args[0] + " - " + args[1])
driverAsBytes, err := stub.GetState(args[0])
if err != nil {
return nil, errors.New("Failed to get driver name")
}
res := Driver{}
json.Unmarshal(driverAsBytes, &res)
res.FirstName = args[1] //change the user
res.LastName = args[2]
res.Mobile = args[3]
res.Password = args[4]
res.Street = args[5]
res.City = args[6]
res.State = args[7]
res.Zip = args[8]
res.Status = args[9]
jsonAsBytes, _ := json.Marshal(res)
err = stub.PutState(args[0], jsonAsBytes) //rewrite the user status with email-id as key
if err != nil {
return nil, err
}
fmt.Println("- end set user")
return nil, nil
}
// ============================================================================================================================
// Open Trade - create an open trade for a marble you want with marbles you have
// ============================================================================================================================
func (t *SimpleChaincode) open_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
var will_size int
var trade_away Description
// 0 1 2 3 4 5 6
//["bob", "blue", "16", "red", "16"] *"blue", "35*
if len(args) < 5 {
return nil, errors.New("Incorrect number of arguments. Expecting like 5?")
}
if len(args)%2 == 0{
return nil, errors.New("Incorrect number of arguments. Expecting an odd number")
}
size1, err := strconv.Atoi(args[2])
if err != nil {
return nil, errors.New("3rd argument must be a numeric string")
}
open := AnOpenTrade{}
open.User = args[0]
open.Timestamp = makeTimestamp() //use timestamp as an ID
open.Want.Color = args[1]
open.Want.Size = size1
fmt.Println("- start open trade")
jsonAsBytes, _ := json.Marshal(open)
err = stub.PutState("_debug1", jsonAsBytes)
for i:=3; i < len(args); i++ { //create and append each willing trade
will_size, err = strconv.Atoi(args[i + 1])
if err != nil {
msg := "is not a numeric string " + args[i + 1]
fmt.Println(msg)
return nil, errors.New(msg)
}
trade_away = Description{}
trade_away.Color = args[i]
trade_away.Size = will_size
fmt.Println("! created trade_away: " + args[i])
jsonAsBytes, _ = json.Marshal(trade_away)
err = stub.PutState("_debug2", jsonAsBytes)
open.Willing = append(open.Willing, trade_away)
fmt.Println("! appended willing to open")
i++;
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
trades.OpenTrades = append(trades.OpenTrades, open); //append to open trades
fmt.Println("! appended open to trades")
jsonAsBytes, _ = json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
fmt.Println("- end open trade")
return nil, nil
}
// ============================================================================================================================
// Perform Trade - close an open trade and move ownership
// ============================================================================================================================
func (t *SimpleChaincode) perform_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0 1 2 3 4 5
//[data.id, data.closer.user, data.closer.name, data.opener.user, data.opener.color, data.opener.size]
if len(args) < 6 {
return nil, errors.New("Incorrect number of arguments. Expecting 6")
}
fmt.Println("- start close trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
size, err := strconv.Atoi(args[5])
if err != nil {
return nil, errors.New("6th argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
marbleAsBytes, err := stub.GetState(args[2])
if err != nil {
return nil, errors.New("Failed to get thing")
}
closersMarble := Marble{}
json.Unmarshal(marbleAsBytes, &closersMarble) //un stringify it aka JSON.parse()
//verify if marble meets trade requirements
if closersMarble.Color != trades.OpenTrades[i].Want.Color || closersMarble.Size != trades.OpenTrades[i].Want.Size {
msg := "marble in input does not meet trade requriements"
fmt.Println(msg)
return nil, errors.New(msg)
}
marble, e := findMarble4Trade(stub, trades.OpenTrades[i].User, args[4], size) //find a marble that is suitable from opener
if(e == nil){
fmt.Println("! no errors, proceeding")
t.set_user(stub, []string{args[2], trades.OpenTrades[i].User}) //change owner of selected marble, closer -> opener
t.set_user(stub, []string{marble.Name, args[1]}) //change owner of selected marble, opener -> closer
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
}
}
}
fmt.Println("- end close trade")
return nil, nil
}
// ============================================================================================================================
// findMarble4Trade - look for a matching marble that this user owns and return it
// ============================================================================================================================
func findMarble4Trade(stub shim.ChaincodeStubInterface, user string, color string, size int )(m Marble, err error){
var fail Marble;
fmt.Println("- start find marble 4 trade")
fmt.Println("looking for " + user + ", " + color + ", " + strconv.Itoa(size));
//get the marble index
marblesAsBytes, err := stub.GetState(marbleIndexStr)
if err != nil {
return fail, errors.New("Failed to get marble index")
}
var marbleIndex []string
json.Unmarshal(marblesAsBytes, &marbleIndex) //un stringify it aka JSON.parse()
for i:= range marbleIndex{ //iter through all the marbles
//fmt.Println("looking @ marble name: " + marbleIndex[i]);
marbleAsBytes, err := stub.GetState(marbleIndex[i]) //grab this marble
if err != nil {
return fail, errors.New("Failed to get marble")
}
res := Marble{}
json.Unmarshal(marbleAsBytes, &res) //un stringify it aka JSON.parse()
//fmt.Println("looking @ " + res.User + ", " + res.Color + ", " + strconv.Itoa(res.Size));
//check for user && color && size
if strings.ToLower(res.User) == strings.ToLower(user) && strings.ToLower(res.Color) == strings.ToLower(color) && res.Size == size{
fmt.Println("found a marble: " + res.Name)
fmt.Println("! end find marble 4 trade")
return res, nil
}
}
fmt.Println("- end find marble 4 trade - error")
return fail, errors.New("Did not find marble to use in this trade")
}
// ============================================================================================================================
// Make Timestamp - create a timestamp in ms
// ============================================================================================================================
func makeTimestamp() int64 {
return time.Now().UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}
// ============================================================================================================================
// Remove Open Trade - close an open trade
// ============================================================================================================================
func (t *SimpleChaincode) remove_trade(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var err error
// 0
//[data.id]
if len(args) < 1 {
return nil, errors.New("Incorrect number of arguments. Expecting 1")
}
fmt.Println("- start remove trade")
timestamp, err := strconv.ParseInt(args[0], 10, 64)
if err != nil {
return nil, errors.New("1st argument must be a numeric string")
}
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return nil, errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
for i := range trades.OpenTrades{ //look for the trade
//fmt.Println("looking at " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10) + " for " + strconv.FormatInt(timestamp, 10))
if trades.OpenTrades[i].Timestamp == timestamp{
fmt.Println("found the trade");
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return nil, err
}
break
}
}
fmt.Println("- end remove trade")
return nil, nil
}
// ============================================================================================================================
// Clean Up Open Trades - make sure open trades are still possible, remove choices that are no longer possible, remove trades that have no valid choices
// ============================================================================================================================
func cleanTrades(stub shim.ChaincodeStubInterface)(err error){
var didWork = false
fmt.Println("- start clean trades")
//get the open trade struct
tradesAsBytes, err := stub.GetState(openTradesStr)
if err != nil {
return errors.New("Failed to get opentrades")
}
var trades AllTrades
json.Unmarshal(tradesAsBytes, &trades) //un stringify it aka JSON.parse()
fmt.Println("# trades " + strconv.Itoa(len(trades.OpenTrades)))
for i:=0; i<len(trades.OpenTrades); { //iter over all the known open trades
fmt.Println(strconv.Itoa(i) + ": looking at trade " + strconv.FormatInt(trades.OpenTrades[i].Timestamp, 10))
fmt.Println("# options " + strconv.Itoa(len(trades.OpenTrades[i].Willing)))
for x:=0; x<len(trades.OpenTrades[i].Willing); { //find a marble that is suitable
fmt.Println("! on next option " + strconv.Itoa(i) + ":" + strconv.Itoa(x))
_, e := findMarble4Trade(stub, trades.OpenTrades[i].User, trades.OpenTrades[i].Willing[x].Color, trades.OpenTrades[i].Willing[x].Size)
if(e != nil){
fmt.Println("! errors with this option, removing option")
didWork = true
trades.OpenTrades[i].Willing = append(trades.OpenTrades[i].Willing[:x], trades.OpenTrades[i].Willing[x+1:]...) //remove this option
x--;
}else{
fmt.Println("! this option is fine")
}
x++
fmt.Println("! x:" + strconv.Itoa(x))
if x >= len(trades.OpenTrades[i].Willing) { //things might have shifted, recalcuate
break
}
}
if len(trades.OpenTrades[i].Willing) == 0 {
fmt.Println("! no more options for this trade, removing trade")
didWork = true
trades.OpenTrades = append(trades.OpenTrades[:i], trades.OpenTrades[i+1:]...) //remove this trade
i--;
}
i++
fmt.Println("! i:" + strconv.Itoa(i))
if i >= len(trades.OpenTrades) { //things might have shifted, recalcuate
break
}
}
if(didWork){
fmt.Println("! saving open trade changes")
jsonAsBytes, _ := json.Marshal(trades)
err = stub.PutState(openTradesStr, jsonAsBytes) //rewrite open orders
if err != nil {
return err
}
}else{
fmt.Println("! all open trades are fine")
}
fmt.Println("- end clean trades")
return nil
}
|
mamandal/fleetchaincd
|
chaincode/marbles_chaincode.go
|
GO
|
apache-2.0
| 32,592 |
using XElement.DotNet.System.Environment.Startup;
namespace XElement.SDM.ManagementLogic
{
#region not unit-tested
internal abstract class AbstractProgramLogic : IProgramLogic
{
protected AbstractProgramLogic( IProgramInfo programInfo )
{
this._programInfo = programInfo;
}
public abstract void /*IProgramLogic.*/DelayStartup();
public void /*IProgramLogic.*/Do() { this.DelayStartup(); }
public abstract void /*IProgramLogic.*/PromoteStartup();
public void /*IProgramLogic.*/Undo() { this.PromoteStartup(); }
protected IProgramInfo _programInfo;
}
#endregion
}
|
XElementDev/SDM
|
code/Startup/ManagementLogic.Implementation/AbstractProgramLogic.cs
|
C#
|
apache-2.0
| 661 |
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<!-- NAME: 1 COLUMN -->
<!--[if gte mso 15]>
<xml>
<o:OfficeDocumentSettings>
<o:AllowPNG/>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
<![endif]-->
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Factuur</title>
<style type="text/css">
p{
margin:10px 0;
padding:0;
}
table{
border-collapse:collapse;
}
h1,h2,h3,h4,h5,h6{
display:block;
margin:0;
padding:0;
}
img,a img{
border:0;
height:auto;
outline:none;
text-decoration:none;
}
body,#bodyTable,#bodyCell{
height:100%;
margin:0;
padding:0;
width:100%;
}
#outlook a{
padding:0;
}
img{
-ms-interpolation-mode:bicubic;
}
table{
mso-table-lspace:0pt;
mso-table-rspace:0pt;
}
.ReadMsgBody{
width:100%;
}
.ExternalClass{
width:100%;
}
p,a,li,td,blockquote{
mso-line-height-rule:exactly;
}
a[href^=tel],a[href^=sms]{
color:inherit;
cursor:default;
text-decoration:none;
}
p,a,li,td,body,table,blockquote{
-ms-text-size-adjust:100%;
-webkit-text-size-adjust:100%;
}
.ExternalClass,.ExternalClass p,.ExternalClass td,.ExternalClass div,.ExternalClass span,.ExternalClass font{
line-height:100%;
}
a[x-apple-data-detectors]{
color:inherit !important;
text-decoration:none !important;
font-size:inherit !important;
font-family:inherit !important;
font-weight:inherit !important;
line-height:inherit !important;
}
#bodyCell{
padding:10px;
}
.templateContainer{
max-width:600px !important;
}
a.mcnButton{
display:block;
}
.mcnImage{
vertical-align:bottom;
}
.mcnTextContent{
word-break:break-word;
}
.mcnTextContent img{
height:auto !important;
}
.mcnDividerBlock{
table-layout:fixed !important;
}
body,#bodyTable{
background-color:#FAFAFA;
}
#bodyCell{
border-top:0;
}
.templateContainer{
border:0;
}
h1{
color:#202020;
font-family:Helvetica;
font-size:26px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h2{
color:#202020;
font-family:Helvetica;
font-size:22px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h3{
color:#202020;
font-family:Helvetica;
font-size:20px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
h4{
color:#202020;
font-family:Helvetica;
font-size:18px;
font-style:normal;
font-weight:bold;
line-height:125%;
letter-spacing:normal;
text-align:left;
}
#templatePreheader{
background-color:#FAFAFA;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:9px;
}
#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{
color:#656565;
font-family:Helvetica;
font-size:12px;
line-height:150%;
text-align:left;
}
#templatePreheader .mcnTextContent a,#templatePreheader .mcnTextContent p a{
color:#656565;
font-weight:normal;
text-decoration:underline;
}
#templateHeader{
background-color:#FFFFFF;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:0;
}
#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{
color:#202020;
font-family:Helvetica;
font-size:16px;
line-height:150%;
text-align:left;
}
#templateHeader .mcnTextContent a,#templateHeader .mcnTextContent p a{
color:#2BAADF;
font-weight:normal;
text-decoration:underline;
}
#templateBody{
background-color:#FFFFFF;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:2px solid #EAEAEA;
padding-top:0;
padding-bottom:9px;
}
#templateBody .mcnTextContent,#templateBody .mcnTextContent p{
color:#202020;
font-family:Helvetica;
font-size:16px;
line-height:150%;
text-align:left;
}
#templateBody .mcnTextContent a,#templateBody .mcnTextContent p a{
color:#2BAADF;
font-weight:normal;
text-decoration:underline;
}
#templateFooter{
background-color:#FAFAFA;
background-image:none;
background-repeat:no-repeat;
background-position:center;
background-size:cover;
border-top:0;
border-bottom:0;
padding-top:9px;
padding-bottom:9px;
}
#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{
color:#656565;
font-family:Helvetica;
font-size:12px;
line-height:150%;
text-align:center;
}
#templateFooter .mcnTextContent a,#templateFooter .mcnTextContent p a{
color:#656565;
font-weight:normal;
text-decoration:underline;
}
@media only screen and (min-width:768px){
.templateContainer{
width:600px !important;
}
} @media only screen and (max-width: 480px){
body,table,td,p,a,li,blockquote{
-webkit-text-size-adjust:none !important;
}
} @media only screen and (max-width: 480px){
body{
width:100% !important;
min-width:100% !important;
}
} @media only screen and (max-width: 480px){
#bodyCell{
padding-top:10px !important;
}
} @media only screen and (max-width: 480px){
.mcnImage{
width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnCartContainer,.mcnCaptionTopContent,.mcnRecContentContainer,.mcnCaptionBottomContent,.mcnTextContentContainer,.mcnBoxedTextContentContainer,.mcnImageGroupContentContainer,.mcnCaptionLeftTextContentContainer,.mcnCaptionRightTextContentContainer,.mcnCaptionLeftImageContentContainer,.mcnCaptionRightImageContentContainer,.mcnImageCardLeftTextContentContainer,.mcnImageCardRightTextContentContainer{
max-width:100% !important;
width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnBoxedTextContentContainer{
min-width:100% !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupContent{
padding:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnCaptionLeftContentOuter .mcnTextContent,.mcnCaptionRightContentOuter .mcnTextContent{
padding-top:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardTopImageContent,.mcnCaptionBlockInner .mcnCaptionTopContent:last-child .mcnTextContent{
padding-top:18px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardBottomImageContent{
padding-bottom:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupBlockInner{
padding-top:0 !important;
padding-bottom:0 !important;
}
} @media only screen and (max-width: 480px){
.mcnImageGroupBlockOuter{
padding-top:9px !important;
padding-bottom:9px !important;
}
} @media only screen and (max-width: 480px){
.mcnTextContent,.mcnBoxedTextContentColumn{
padding-right:18px !important;
padding-left:18px !important;
}
} @media only screen and (max-width: 480px){
.mcnImageCardLeftImageContent,.mcnImageCardRightImageContent{
padding-right:18px !important;
padding-bottom:0 !important;
padding-left:18px !important;
}
} @media only screen and (max-width: 480px){
.mcpreview-image-uploader{
display:none !important;
width:100% !important;
}
} @media only screen and (max-width: 480px){
h1{
font-size:22px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h2{
font-size:20px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h3{
font-size:18px !important;
line-height:125% !important;
}
} @media only screen and (max-width: 480px){
h4{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
.mcnBoxedTextContentContainer .mcnTextContent,.mcnBoxedTextContentContainer .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templatePreheader{
display:block !important;
}
} @media only screen and (max-width: 480px){
#templatePreheader .mcnTextContent,#templatePreheader .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateHeader .mcnTextContent,#templateHeader .mcnTextContent p{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateBody .mcnTextContent,#templateBody .mcnTextContent p{
font-size:16px !important;
line-height:150% !important;
}
} @media only screen and (max-width: 480px){
#templateFooter .mcnTextContent,#templateFooter .mcnTextContent p{
font-size:14px !important;
line-height:150% !important;
}
}</style></head>
<body style="height: 100%;margin: 0;padding: 0;width: 100%;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;">
<center>
<table align="center" border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" id="bodyTable" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 0;width: 100%;background-color: #FAFAFA;">
<tr>
<td align="center" valign="top" id="bodyCell" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;height: 100%;margin: 0;padding: 10px;width: 100%;border-top: 0;">
<!-- BEGIN TEMPLATE // -->
<!--[if gte mso 9]>
<table align="center" border="0" cellspacing="0" cellpadding="0" width="600" style="width:600px;">
<tr>
<td align="center" valign="top" width="600" style="width:600px;">
<![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="templateContainer" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;border: 0;max-width: 600px !important;">
<tr>
<td valign="top" id="templatePreheader" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="390" style="width:390px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 390px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;">
Factuur Hippiemarkt Aalsmeer
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
<td valign="top" width="210" style="width:210px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 210px;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-left: 18px;padding-bottom: 9px;padding-right: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: left;">
<a href="http://app.directevents.nl/mail/view/hippiemarkt-aalsmeer-factuur" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #656565;font-weight: normal;text-decoration: underline;">Mail niet leesbaar of graag in uw browser openen? Klik hier.</a>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateHeader" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 0;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnImageBlockOuter">
<tr>
<td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner">
<table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<img align="center" alt="" src="http://app.directevents.nl/assets/img/hippiemarkt-aalsmeer/mail-header.png" width="564" style="max-width: 799px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage">
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateBody" style="background:#FFFFFF none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FFFFFF;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 2px solid #EAEAEA;padding-top: 0;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="600" style="width:600px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;">
<h1 style="display: block;margin: 0;padding: 0;color: #202020;font-family: Helvetica;font-size: 26px;font-style: normal;font-weight: bold;line-height: 125%;letter-spacing: normal;text-align: left;">Factuur Hippiemarkt Aalsmeer</h1>
<p style="margin: 10px 0;padding: 0;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;color: #202020;font-family: Helvetica;font-size: 16px;line-height: 150%;text-align: left;">Beste Standhouder,<br>
<br>
Bedankt voor uw inschrijving voor De Hippiemarkt Aalsmeer op vrijdag 27 juli.<br>
<br>
Wij zijn enorm druk met alle voorbereidingen om de markt tot een succes te laten verlopen. In de bijlage sturen wij de algemene voorwaarden (met onder andere opbouw en afbouw tijden) en de factuur.<br>
<br>
Pas na ontvangst van uw betaling is uw inschrijving definitief.<br>
<br>
Tot vrijdag 27 juli op het surfeiland te Aalsmeer,<br>
<br>
Contact informatie:<br>
Info@directevents.nl<br>
</p>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
<tr>
<td valign="top" id="templateFooter" style="background:#FAFAFA none no-repeat center/cover;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;background-color: #FAFAFA;background-image: none;background-repeat: no-repeat;background-position: center;background-size: cover;border-top: 0;border-bottom: 0;padding-top: 9px;padding-bottom: 9px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnImageBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnImageBlockOuter">
<tr>
<td valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnImageBlockInner">
<table align="left" width="100%" border="0" cellpadding="0" cellspacing="0" class="mcnImageContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td class="mcnImageContent" valign="top" style="padding-right: 9px;padding-left: 9px;padding-top: 0;padding-bottom: 0;text-align: center;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<img align="center" alt="" src="https://gallery.mailchimp.com/042b4e4809d32ad5aa6147613/images/0bbee562-e766-4dda-83ca-4474a23a419b.png" width="564" style="max-width: 975px;padding-bottom: 0;display: inline !important;vertical-align: bottom;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" class="mcnImage">
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnFollowBlockOuter">
<tr>
<td align="center" valign="top" style="padding: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowBlockInner">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentContainer" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" style="padding-left: 9px;padding-right: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContent">
<tbody><tr>
<td align="center" valign="top" style="padding-top: 9px;padding-right: 9px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="top" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<![endif]-->
<!--[if mso]>
<td align="center" valign="top">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td valign="top" style="padding-right: 10px;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<a href="https://www.facebook.com/events/434974326975583/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-facebook-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
<td align="center" valign="top">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="display: inline;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td valign="top" style="padding-right: 0;padding-bottom: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" class="mcnFollowContentItemContainer">
<table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnFollowContentItem" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="left" valign="middle" style="padding-top: 5px;padding-right: 10px;padding-bottom: 5px;padding-left: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table align="left" border="0" cellpadding="0" cellspacing="0" width="" style="border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td align="center" valign="middle" width="24" class="mcnFollowIconContent" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<a href="http://www.hippiemarktaalsmeer.nl/" target="_blank" style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;"><img src="https://cdn-images.mailchimp.com/icons/social-block-v2/color-link-48.png" style="display: block;border: 0;height: auto;outline: none;text-decoration: none;-ms-interpolation-mode: bicubic;" height="24" width="24" class=""></a>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody></table>
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnDividerBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;table-layout: fixed !important;">
<tbody class="mcnDividerBlockOuter">
<tr>
<td class="mcnDividerBlockInner" style="min-width: 100%;padding: 10px 18px 25px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<table class="mcnDividerContent" border="0" cellpadding="0" cellspacing="0" width="100%" style="min-width: 100%;border-top-width: 2px;border-top-style: solid;border-top-color: #EEEEEE;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody><tr>
<td style="mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<span></span>
</td>
</tr>
</tbody></table>
<!--
<td class="mcnDividerBlockInner" style="padding: 18px;">
<hr class="mcnDividerContent" style="border-bottom-color:none; border-left-color:none; border-right-color:none; border-bottom-width:0; border-left-width:0; border-right-width:0; margin-top:0; margin-right:0; margin-bottom:0; margin-left:0;" />
-->
</td>
</tr>
</tbody>
</table><table border="0" cellpadding="0" cellspacing="0" width="100%" class="mcnTextBlock" style="min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<tbody class="mcnTextBlockOuter">
<tr>
<td valign="top" class="mcnTextBlockInner" style="padding-top: 9px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;">
<!--[if mso]>
<table align="left" border="0" cellspacing="0" cellpadding="0" width="100%" style="width:100%;">
<tr>
<![endif]-->
<!--[if mso]>
<td valign="top" width="600" style="width:600px;">
<![endif]-->
<table align="left" border="0" cellpadding="0" cellspacing="0" style="max-width: 100%;min-width: 100%;border-collapse: collapse;mso-table-lspace: 0pt;mso-table-rspace: 0pt;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;" width="100%" class="mcnTextContentContainer">
<tbody><tr>
<td valign="top" class="mcnTextContent" style="padding-top: 0;padding-right: 18px;padding-bottom: 9px;padding-left: 18px;mso-line-height-rule: exactly;-ms-text-size-adjust: 100%;-webkit-text-size-adjust: 100%;word-break: break-word;color: #656565;font-family: Helvetica;font-size: 12px;line-height: 150%;text-align: center;">
<em>Copyright © 2017 Direct Events, All rights reserved.</em><br>
<br>
info@directevents.nl<br></td>
</tr>
</tbody></table>
<!--[if mso]>
</td>
<![endif]-->
<!--[if mso]>
</tr>
</table>
<![endif]-->
</td>
</tr>
</tbody>
</table></td>
</tr>
</table>
<!--[if gte mso 9]>
</td>
</tr>
</table>
<![endif]-->
<!-- // END TEMPLATE -->
</td>
</tr>
</table>
</center>
<center>
<style type="text/css">
@media only screen and (max-width: 480px){
table#canspamBar td{font-size:14px !important;}
table#canspamBar td a{display:block !important; margin-top:10px !important;}
}
</style>
</center></body>
</html>
|
directonlijn/app
|
app/resources/views/emails/hippiemarkt-aalsmeer-factuur.blade.php
|
PHP
|
apache-2.0
| 34,222 |