code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*L
* Copyright Ekagra Software Technologies Ltd.
* Copyright SAIC
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacore-sdk-pre411/LICENSE.txt for details.
*/
package gov.nih.nci.codegen.core.transformer;
import gov.nih.nci.codegen.core.BaseArtifact;
import gov.nih.nci.codegen.core.ConfigurationException;
import gov.nih.nci.codegen.core.XMLConfigurable;
import gov.nih.nci.codegen.core.filter.UML13ClassifierFilter;
import gov.nih.nci.codegen.core.filter.UML13ModelElementFilter;
import gov.nih.nci.codegen.core.util.UML13Utils;
import gov.nih.nci.codegen.core.util.XMLUtils;
import gov.nih.nci.codegen.framework.FilteringException;
import gov.nih.nci.codegen.framework.TransformationException;
import gov.nih.nci.codegen.framework.Transformer;
import gov.nih.nci.common.util.Constant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.jmi.reflect.RefObject;
import org.apache.log4j.Logger;
import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.omg.uml.foundation.core.Classifier;
import org.omg.uml.foundation.core.UmlClass;
import org.omg.uml.modelmanagement.Model;
import org.omg.uml.modelmanagement.UmlPackage;
/**
* <!-- LICENSE_TEXT_START -->
* Copyright 2001-2004 SAIC. Copyright 2001-2003 SAIC. This software was developed in conjunction with the National Cancer Institute,
* and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions
* in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment:
* "This product includes software developed by the SAIC and the National Cancer Institute."
* If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself,
* wherever such third-party acknowledgments normally appear.
* 3. The names "The National Cancer Institute", "NCI" and "SAIC" must not be used to endorse or promote products derived from this software.
* 4. This license does not authorize the incorporation of this software into any third party proprietary programs. This license does not authorize
* the recipient to use any trademarks owned by either NCI or SAIC-Frederick.
* 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE,
* SAIC, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* <!-- LICENSE_TEXT_END -->
*/
/**
* Produces an XML file that contains object-relational mapping configuration
* information for use by the OJB tool ( <a href="http://db.apache.org/ojb/"
* target="_blank">http://db.apache.org/ojb/ </a>). In particular, it produces
* class-descriptor elements from a set classes defined in a UML 1.3 model.
* <p>
* In order to use this transformer, the supplied UML model must contain certain
* information, in the form of tagged values and stereotypes. This section
* describes the control file configuration and how it relates to the code. It
* does not describe how the UML model must be annotated (see the User's Guide
* for that).
* <p>
* The content model for this transformer's configuration element is as follows:
* <p>
* <code>
* <pre>
*
*
*
* <!ELEMENT transformer (param, filter)>
* <!ATTLIST transformer
* name CDATA #REQUIRED
* className CDATA #FIXED gov.nih.nci.codegen.core.transformer.OJBRepTransformer>
* <!ELEMENT param EMPTY>
* <!ATTLIST param
* name CDATA #FIXED packageName
* value CDATA #REQUIRED>
* <!ELEMENT filter ... see {@link gov.nih.nci.codegen.core.filter.UML13ClassifierFilter#configure(org.w3c.dom.Element)} ...
*
*
*
* </pre>
* </code>
* <p>
* As you can see, this transformer expects a nested filter element. The reason
* is that this transformer produces a single Artifact (an XML file) from a
* collection of model elements.
* <p>
* UML13OJBRepTransformer expects to be passed an instance of
* org.omg.uml.modelmanagement.Model. It uses UML13ModelElementFilter to obtain
* all model elements in the model. Then it use UML13Classifier to obtain the
* classifiers selected by the contents of the nested filter element. Then it
* iterates through these classifiers, building the class-descriptor elements.
* <p>
* A Collection containing a single Artifact is returned by this transformer's
* execute method. The name attribute of the Artifact is set to "ojb_repository"
* and its source attribute is set to the String that represents the XML
* document.
* <p>
*
* @author caBIO Team
* @version 1.0
*/
public class UML13HBCTransformer
implements Transformer, XMLConfigurable {
private static Logger log = Logger.getLogger(UML13HBCTransformer.class);
private UML13ClassifierFilter _classifierFilt;
private String _pkgName;
private String _fileSuffix;
/**
*
*/
public UML13HBCTransformer() {
super();
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.codegen.framework.Transformer#execute(javax.jmi.reflect.RefObject,
* java.util.Collection)
*/
public Collection execute(RefObject modelElement, Collection artifacts)
throws TransformationException {
if (modelElement == null) {
log.error("model element is null");
throw new TransformationException("model element is null");
}
if (!(modelElement instanceof Model)) {
log.error( "model element not instance of Model");
throw new TransformationException(
"model element not instance of Model");
}
ArrayList newArtifacts = new ArrayList();
UML13ModelElementFilter meFilt = new UML13ModelElementFilter();
ArrayList umlExtentCol = new ArrayList();
umlExtentCol.add(modelElement.refOutermostPackage());
Collection classifiers = null;
try {
classifiers = _classifierFilt.execute(meFilt.execute(umlExtentCol));
} catch (FilteringException ex) {
log.error("couldn't filter model elements " + ex.getMessage());
throw new TransformationException("couldn't filter model elements",
ex);
}
Document doc = generateConfig(classifiers);
XMLOutputter p = new XMLOutputter();
p.setFormat(Format.getPrettyFormat());
newArtifacts.add(new BaseArtifact("hibernate_config", modelElement, p
.outputString(doc)));
return newArtifacts;
}
/**
* @param classifiers
* @return
*/
private Document generateConfig(Collection classifiers) {
Element configEl = new Element("hibernate-configuration");
Element sessEl = new Element("session-factory");
configEl.addContent(sessEl);
for (Iterator i = classifiers.iterator(); i.hasNext();) {
Classifier klass = (Classifier) i.next();
UmlPackage pkg = null;
if (_pkgName != null) {
pkg = UML13Utils.getPackage(UML13Utils.getModel(klass),
_pkgName);
} else {
pkg = UML13Utils.getModel(klass);
}
String fileSuffix = _fileSuffix;
if (fileSuffix == null) {
fileSuffix = ".hbm.xml";
}
UmlClass superClass = UML13Utils.getSuperClass((UmlClass)klass);
if (superClass == null) {
String nn = UML13Utils.getNamespaceName(pkg, klass);
String resourceName = nn.replace('.', '/') + Constant.FORWARD_SLASH + klass.getName() + fileSuffix;
// String implResourceName = resourceName + "/impl";
Element mappingEl = new Element("mapping");
sessEl.addContent(mappingEl);
mappingEl.setAttribute("resource", resourceName);
String resourceName1 = nn.replace('.', '/') + "/impl/" + klass.getName() + "Impl" + fileSuffix;
Element mappingE2 = new Element("mapping");
sessEl.addContent(mappingE2);
mappingE2.setAttribute("resource", resourceName1);
}
}
DocType docType = new DocType("hibernate-configuration",
"-//Hibernate/Hibernate Configuration DTD 3.0//EN",
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd");
Document doc = new Document();
doc.setDocType(docType);
doc.setRootElement(configEl);
return doc;
}
/*
* (non-Javadoc)
*
* @see gov.nih.nci.codegen.core.JDOMConfigurable#configure(org.jdom.Element)
*/
public void configure(org.w3c.dom.Element config)
throws ConfigurationException {
org.w3c.dom.Element filterEl = XMLUtils.getChild(config, "filter");
if (filterEl == null) {
log.error("no child filter element found");
throw new ConfigurationException("no child filter element found");
}
String className = filterEl.getAttribute("className");
if (className == null) {
log.error("no filter class name specified");
throw new ConfigurationException("no filter class name specified");
}
_pkgName = getParameter(config, "basePackage");
log.debug("basePackage: " + _pkgName);
_fileSuffix = getParameter(config, "fileSuffix");
try {
_classifierFilt = (UML13ClassifierFilter) Class.forName(className)
.newInstance();
} catch (Exception ex) {
log.error("Couldn't instantiate "
+ className);
throw new ConfigurationException("Couldn't instantiate "
+ className);
}
_classifierFilt.configure(filterEl);
}
private String getParameter(org.w3c.dom.Element config, String paramName) {
String param = null;
List params = XMLUtils.getChildren(config, "param");
for (Iterator i = params.iterator(); i.hasNext();) {
org.w3c.dom.Element paramEl = (org.w3c.dom.Element) i.next();
if (paramName.equals(paramEl.getAttribute("name"))) {
param = paramEl.getAttribute("value");
break;
}
}
return param;
}
}
| NCIP/cacore-sdk-pre411 | src/gov/nih/nci/codegen/core/transformer/UML13HBCTransformer.java | Java | bsd-3-clause | 11,556 |
/*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/camod/LICENSE.txt for details.
*/
package gov.nih.nci.camod.biodbnet;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>
* Java class for dbWalkParams complex type.
*
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* <complexType name="dbWalkParams">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <all>
* <element name="dbPath" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="taxonId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="inputValues" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </all>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "dbWalkParams", propOrder = {
})
public class DbWalkParams {
@XmlElement(required = true)
protected String dbPath;
@XmlElement(required = true)
protected String taxonId;
@XmlElement(required = true)
protected String inputValues;
/**
* Gets the value of the dbPath property.
*
* @return possible object is {@link String }
*
*/
public String getDbPath() {
return dbPath;
}
/**
* Sets the value of the dbPath property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setDbPath(String value) {
this.dbPath = value;
}
/**
* Gets the value of the taxonId property.
*
* @return possible object is {@link String }
*
*/
public String getTaxonId() {
return taxonId;
}
/**
* Sets the value of the taxonId property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setTaxonId(String value) {
this.taxonId = value;
}
/**
* Gets the value of the inputValues property.
*
* @return possible object is {@link String }
*
*/
public String getInputValues() {
return inputValues;
}
/**
* Sets the value of the inputValues property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setInputValues(String value) {
this.inputValues = value;
}
}
| NCIP/camod | software/camod/src/gov/nih/nci/camod/biodbnet/DbWalkParams.java | Java | bsd-3-clause | 2,629 |
package com.rehivetech.beeeon.network.authentication;
import android.content.Intent;
import com.rehivetech.beeeon.gui.activity.LoginActivity;
import java.util.Map;
public interface IAuthProvider {
// Result codes
/**
* Provider has all data he needs and they are given via Intent object
*/
int RESULT_AUTH = 100;
/**
* User cancelled authorization process
*/
int RESULT_CANCEL = 101;
/**
* Error happened during authorization process
*/
int RESULT_ERROR = 102;
// Interface methods
boolean isDemo();
/**
* @return identifier for the provider as server knows it to correctly identify this login service.
*/
String getProviderName();
/**
* @return map of parameters required for authentication (e.g. email, password, ...).
*/
Map<String, String> getParameters();
/**
* This is used for remembering last logged in user and then automatic logging in.
*
* @return value of primary login field (e.g. e-mail or login).
*/
String getPrimaryParameter();
/**
* Set primary parameter (probably from last login attempt) so it could e.g. fill the email/login field automatically.
*
* @param parameter
*/
void setPrimaryParameter(String parameter);
/**
* Loads the data from the RESULT_AUTH activity result.
*
* @param data
* @return true when this provider has authorization parameters correctly loaded; false when given data aren't correct/expected.
*/
boolean loadAuthIntent(Intent data);
/**
* Do steps required for filling the parameters map (e.g. open login dialog to set login/password or load Google auth token).
* AuthProvider will provide the result via calling activity.onActivityResult(), read description in each AuthProvider to know what data receive/handle and how.
* AuthProvider must NOT throw any exceptions in this method. They won't be catch by caller.
* <p/>
* This will be called (probably) on UI thread so Provider must start the separate thread by itself.
*/
void prepareAuth(LoginActivity activity);
/**
* Interface for providers using WebAuthActivity.
*/
interface IWebAuthProvider {
/**
* This is called when in parent WebAuthActivity is called onStop method.
*/
void onActivityStop();
}
}
| BeeeOn/android | BeeeOn/app/src/main/java/com/rehivetech/beeeon/network/authentication/IAuthProvider.java | Java | bsd-3-clause | 2,218 |
/*
* Copyright (c) 2015, Felix "mezzodrinker" Fröhlich
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor
* the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package mezzo.mobtalkerscript.console.util.ui;
/**
* @author Felix "mezzodrinker" Fröhlich
*/
public class Area {
public int width;
public int height;
public Area(int width, int height) {
this.width = width;
this.height = height;
}
}
| mezzodrinker/interactive-console | src/mezzo/mobtalkerscript/console/util/ui/Area.java | Java | bsd-3-clause | 1,838 |
package org.thryft.waf.lib.protocols.jdbc;
import static org.thryft.Preconditions.checkNotEmpty;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import org.thryft.protocol.AbstractOutputProtocol;
import org.thryft.protocol.FieldBegin;
import org.thryft.protocol.OutputProtocolException;
import org.thryft.protocol.Type;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
public final class SqlUpdateStringOutputProtocol extends AbstractOutputProtocol {
public SqlUpdateStringOutputProtocol(final String tableName) {
this(tableName, ImmutableList.<String> of());
}
public SqlUpdateStringOutputProtocol(final String tableName, final Collection<String> extraColumnNames) {
columnNames.addAll(extraColumnNames);
this.tableName = checkNotEmpty(tableName);
}
public String getSqlUpdateString() {
if (columnNames.isEmpty()) {
return "";
}
final StringBuilder builder = new StringBuilder();
builder.append("UPDATE ");
builder.append(tableName);
builder.append(" SET ");
for (int columnI = 0; columnI < columnNames.size(); columnI++) {
if (columnI > 0) {
builder.append(", ");
}
builder.append(columnNames.get(columnI));
builder.append(" = ?");
}
return builder.toString();
}
@Override
public void writeBinary(final byte[] value) throws OutputProtocolException {
}
@Override
public void writeBool(final boolean value) throws OutputProtocolException {
}
@Override
public void writeByte(final byte value) throws OutputProtocolException {
}
@Override
public void writeDateTime(final Date value) throws OutputProtocolException {
}
@Override
public void writeDouble(final double value) throws OutputProtocolException {
}
@Override
public void writeFieldBegin(final String name, final Type type, final short id) throws OutputProtocolException {
if (depth == 1) {
switch (type) {
case LIST:
case MAP:
case SET:
case STRUCT:
break;
default:
if (id != FieldBegin.ABSENT_ID) {
columnNames.add(name + '_' + id);
} else {
columnNames.add(name);
}
}
}
}
@Override
public void writeFieldEnd() throws OutputProtocolException {
}
@Override
public void writeFieldStop() throws OutputProtocolException {
}
@Override
public void writeI16(final short value) throws OutputProtocolException {
}
@Override
public void writeI32(final int value) throws OutputProtocolException {
}
@Override
public void writeI64(final long value) throws OutputProtocolException {
}
@Override
public void writeListBegin(final Type elementType, final int size) throws OutputProtocolException {
depth++;
}
@Override
public void writeListEnd() throws OutputProtocolException {
depth--;
}
@Override
public void writeMapBegin(final Type keyType, final Type valueType, final int size) throws OutputProtocolException {
depth++;
}
@Override
public void writeMapEnd() throws OutputProtocolException {
depth--;
}
@Override
public void writeNull() throws OutputProtocolException {
}
@Override
public void writeString(final String value) throws OutputProtocolException {
}
@Override
public void writeStructBegin(final String name) throws OutputProtocolException {
depth++;
}
@Override
public void writeStructEnd() throws OutputProtocolException {
depth--;
}
private final List<String> columnNames = Lists.newArrayList();
int depth = 0;
private final String tableName;
}
| minorg/thryft-waf | java/lib/src/main/java/org/thryft/waf/lib/protocols/jdbc/SqlUpdateStringOutputProtocol.java | Java | bsd-3-clause | 3,986 |
package org.spin.mhive;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class ADSRView extends View {
Paint linePaint;
Paint bgPaint;
Paint circleStrokePaint;
Paint circleBGPaint;
Paint playHeadPaint;
Paint numericDisplayPaint;
Paint numericDisplayTextPaint;
Paint disablePaint;
RectF attackDecayCircle;
RectF decaySustainCircle;
RectF sustainReleaseCircle;
ADSREnvelope adsr;
private final int SELECTION_CIRCLE_RADIUS = 50;
private final int SELECTION_CIRCLE_STROKE_WIDTH = 4;
private final int NUMERIC_LINE_STROKE_WIDTH = 4;
private final float numericDisplayHeight = SELECTION_CIRCLE_RADIUS+SELECTION_CIRCLE_STROKE_WIDTH/2;
private final float LEFT_SIDE_BUFFER_SIZE = 125;
private final int MAX_MS = 1000;
private final int MIN_SUSTAIN_WIDTH_IN_MS = 400;
private final float MIN_DISPLAY_TEXT_WIDTH_IN_MS = 500;
private final float MS_IN_WIDTH = 3*MAX_MS + MIN_SUSTAIN_WIDTH_IN_MS;
private final float nDottedLinesForSustainPerPx = 0.15f;
//TODO: THIS SHOULD BE INTERFACE
MainActivity mainActivity;
private enum ADSRViewMode
{
DRAGGING_ATTACKDECAY_CIRCLE,
DRAGGING_DECAYSUSTAIN_CIRCLE,
DRAGGING_SUSTAINRELEASE_CIRCLE,
NOT_DRAGGING
}
ADSRViewMode mode;
Timer tmrPlayBar;
final int PLAYBAR_UPDATE_INTERVAL = 33;//ms
long playPosition = 0; //in MS
long startTime = 0; //in MS;
float playBarX = 0;
boolean isPlaying = false;
Handler uiHandler;
boolean enabled = true;
public ADSRView(Context context) {
super(context);
Init();
}
public ADSRView(Context context, AttributeSet attrs) {
super(context, attrs);
Init();
}
public ADSRView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
Init();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
Update();
}
public void SetMainActivity(MainActivity ma)
{
mainActivity = ma;
}
private void Init()
{
uiHandler = new Handler();
linePaint = new Paint();
linePaint.setColor(Color.BLACK);
linePaint.setStrokeWidth(5);
bgPaint = new Paint();
bgPaint.setColor(Color.WHITE);
circleStrokePaint = new Paint();
circleStrokePaint.setARGB(255, 0, 0, 255);
circleStrokePaint.setStrokeWidth(SELECTION_CIRCLE_STROKE_WIDTH);
circleStrokePaint.setStyle(Style.STROKE);
circleBGPaint = new Paint();
circleBGPaint.setARGB(127, 0, 0, 255);
circleBGPaint.setStyle(Style.FILL);
playHeadPaint = new Paint();
playHeadPaint.setARGB(127, 255, 0, 0);
playHeadPaint.setStrokeWidth(5);
numericDisplayPaint = new Paint();
numericDisplayPaint.setARGB(255, 0, 127, 255);
numericDisplayPaint.setStrokeWidth(NUMERIC_LINE_STROKE_WIDTH);
numericDisplayTextPaint = new Paint();
numericDisplayTextPaint.setARGB(255, 0, 127, 255);
numericDisplayTextPaint.setTextAlign(Align.CENTER);
numericDisplayTextPaint.setTextSize(36);
disablePaint = new Paint();
disablePaint.setARGB(170, 80, 80, 80);
disablePaint.setStyle(Style.FILL);
tmrPlayBar = new Timer();
tmrPlayBar.scheduleAtFixedRate(new PlayBarTask(), PLAYBAR_UPDATE_INTERVAL, PLAYBAR_UPDATE_INTERVAL);
adsr = new ADSREnvelope(100, 100, 0.5f, 100);
mode = ADSRViewMode.NOT_DRAGGING;
Update();
}
private float GetVisualizationHeight()
{
return GetVisualizationBottom() - numericDisplayHeight;
}
private float GetVisualizationTop()
{
return numericDisplayHeight;
}
private float GetVisualizationBottom()
{
return getHeight()-SELECTION_CIRCLE_RADIUS;
}
private float GetNumericTop()
{
return 0;
}
private float GetNumericBottom()
{
return GetVisualizationTop();
}
private float GetNumericHorizontalLineHeight()
{
return (GetNumericBottom() + GetNumericTop())*3/4;
}
private float GetNumericTextHeight()
{
return GetNumericHorizontalLineHeight() - 5;
}
private float GetVisualizationLeft()
{
return LEFT_SIDE_BUFFER_SIZE;
}
private float GetVisualizationRight()
{
return getWidth();
}
private float GetVisualizationWidth()
{
return getWidth() - LEFT_SIDE_BUFFER_SIZE;
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
float x = event.getX();
float y = event.getY()-GetVisualizationTop();
if(event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE)
{
if (mode == ADSRViewMode.NOT_DRAGGING)
{
if (decaySustainCircle.contains(x, y))
{
mode = ADSRViewMode.DRAGGING_DECAYSUSTAIN_CIRCLE;
} else if (attackDecayCircle.contains(x, y))
{
mode = ADSRViewMode.DRAGGING_ATTACKDECAY_CIRCLE;
} else if (sustainReleaseCircle.contains(x, y))
{
mode = ADSRViewMode.DRAGGING_SUSTAINRELEASE_CIRCLE;
}
}
if (mode == ADSRViewMode.DRAGGING_ATTACKDECAY_CIRCLE)
{
SetAttackXY(x, y);
} else if (mode == ADSRViewMode.DRAGGING_DECAYSUSTAIN_CIRCLE)
{
SetDecaySustainXY(x, y);
} else if (mode == ADSRViewMode.DRAGGING_SUSTAINRELEASE_CIRCLE)
{
SetSustainReleaseXY(x,y);
}
} else if (event.getAction() == MotionEvent.ACTION_UP)
{
mode = ADSRViewMode.NOT_DRAGGING;
}
return true;
}
//ATTACK MOVEMENT
private void SetAttackXY(float x, float y)
{
int ms = OffsetWidth2MS(x);
if (ms >= MAX_MS)
{
adsr = new ADSREnvelope(MAX_MS, adsr.getDecay(), adsr.getSustain(), adsr.getRelease());
} else if (ms <= 0)
{
adsr = new ADSREnvelope(0, adsr.getDecay(), adsr.getSustain(), adsr.getRelease());
} else {
adsr = new ADSREnvelope(ms, adsr.getDecay(), adsr.getSustain(), adsr.getRelease());
}
Update();
}
//DECAY_SUSTAIN MOVEMENT
private void SetDecaySustainXY(float x, float y)
{
int ms = OffsetWidth2MS(x)-adsr.getAttack();
float atten = Height2Sustain(y);
int newDecay = 0;
float newSustain = 1.0f;
if (ms >= MAX_MS)
{
newDecay = MAX_MS;
} else if (ms <= 0)
{
newDecay = 0;
} else {
newDecay = ms;
}
if (atten >= 1.0f)
{
newSustain = 1.0f;
} else if (atten <= 0)
{
newSustain = 0;
} else {
newSustain = atten;
}
adsr = new ADSREnvelope(adsr.getAttack(), newDecay, newSustain, adsr.getRelease());
Update();
}
//SUSTAIN_RELEASE MOVEMENT
//TODO: extract SUSTAIN stuff to separate function?
private void SetSustainReleaseXY(float x, float y)
{
int ms = Width2MS(GetVisualizationRight()-x);
float atten = Height2Sustain(y);
int newRelease = 0;
float newSustain = 1.0f;
if (ms >= MAX_MS)
{
newRelease = MAX_MS;
} else if (ms <= 0)
{
newRelease = 0;
} else {
newRelease = ms;
}
if (atten >= 1.0f)
{
newSustain = 1.0f;
} else if (atten <= 0)
{
newSustain = 0;
} else {
newSustain = atten;
}
adsr = new ADSREnvelope(adsr.getAttack(), adsr.getDecay(), newSustain, newRelease);
Update();
}
public void SetADSR(ADSREnvelope adsr)
{
if(adsr != this.adsr)
{
this.adsr = adsr;
Update();
}
}
public ADSREnvelope GetADSR()
{
return adsr;
}
public void NoteOn()
{
startTime = System.currentTimeMillis();
isPlaying = true;
}
public void NoteOff()
{
startTime = System.currentTimeMillis();
isPlaying = false;
}
private void Update()
{
attackDecayCircle = new RectF( OffsetMS2Width(adsr.getAttack())-SELECTION_CIRCLE_RADIUS, GetVisualizationTop()-SELECTION_CIRCLE_RADIUS,
OffsetMS2Width(adsr.getAttack())+SELECTION_CIRCLE_RADIUS, GetVisualizationTop()+SELECTION_CIRCLE_RADIUS);
decaySustainCircle = new RectF( SustainLeft()-SELECTION_CIRCLE_RADIUS, SustainHeight()-SELECTION_CIRCLE_RADIUS,
SustainLeft()+SELECTION_CIRCLE_RADIUS, SustainHeight()+SELECTION_CIRCLE_RADIUS);
sustainReleaseCircle = new RectF( SustainRight()-SELECTION_CIRCLE_RADIUS, SustainHeight()-SELECTION_CIRCLE_RADIUS,
SustainRight()+SELECTION_CIRCLE_RADIUS, SustainHeight()+SELECTION_CIRCLE_RADIUS);
if(mainActivity != null)
{
mainActivity.SetADSR(adsr);
}
this.invalidate();
}
private void UpdatePlayBar()
{
playPosition = System.currentTimeMillis() - startTime;
if(isPlaying)
{
playBarX = OffsetMS2Width(playPosition);
if (playBarX > SustainRight())
{
playBarX = SustainLeft() + ((int)(OffsetMS2Width(playPosition)-SustainLeft()))%((int)SustainWidth());
}
} else {
playBarX = MS2Width(playPosition)+SustainRight();
}
this.invalidate();
}
private float MS2Width(float ms)
{
return ms/MS_IN_WIDTH * GetVisualizationWidth();
}
private float OffsetMS2Width(float ms)
{
return GetVisualizationLeft() + MS2Width(ms);
}
private int Width2MS(float x)
{
return (int) (x/GetVisualizationWidth()*((float)MS_IN_WIDTH));
}
private int OffsetWidth2MS(float x)
{
return Width2MS(x-GetVisualizationLeft());
}
private float SustainHeight() { return SustainHeight(adsr.getSustain()); }
private float SustainHeight(float sus)
{
return (1.0f-sus)*GetVisualizationHeight()+GetVisualizationTop();
}
private float Height2Sustain(float y)
{
return 1.0f - (y/GetVisualizationHeight());
}
private float SustainWidth()
{
return MS2Width(MS_IN_WIDTH-(adsr.getAttack()+adsr.getDecay()+adsr.getRelease()));
}
private float SustainLeft()
{
return OffsetMS2Width(adsr.getAttack()+adsr.getDecay());
}
private float SustainRight()
{
return SustainLeft()+SustainWidth();
}
public void DisableADSR() { EnableADSR(false);}
public void EnableADSR() { EnableADSR(true);}
public void EnableADSR(boolean b)
{
enabled = b;
this.invalidate();
}
@Override
public void onDraw(Canvas c)
{
//DRAW MAIN VISUALIZATION
//bg
c.drawRect(GetVisualizationLeft(), GetVisualizationTop(), GetVisualizationRight(), getHeight(), bgPaint);
//bottom area
c.drawRect(GetVisualizationLeft(), GetVisualizationBottom(), GetVisualizationRight(), getHeight(), disablePaint);
//attack
c.drawLine(GetVisualizationLeft(), GetVisualizationBottom(), OffsetMS2Width(adsr.getAttack()), GetVisualizationTop(), linePaint);
//decay
c.drawLine(OffsetMS2Width(adsr.getAttack()), GetVisualizationTop(), SustainLeft(), SustainHeight(), linePaint);
//sustain
int nDottedLinesForSustain = (int) (nDottedLinesForSustainPerPx*SustainWidth());
float[] sustain_pts = new float[nDottedLinesForSustain*4];
float sustainLineWidth = SustainWidth()/((float)nDottedLinesForSustain*4);
for (int i = 0; i < nDottedLinesForSustain*4; i+=4)
{
sustain_pts[i] = SustainLeft() + i*sustainLineWidth; //x1
sustain_pts[i+1] = SustainHeight(); //y1
sustain_pts[i+2] = SustainLeft() + (i+2)*sustainLineWidth; // x2
sustain_pts[i+3] = SustainHeight(); // y2
}
c.drawLines(sustain_pts, linePaint);
//release
c.drawLine(SustainRight(), SustainHeight(), GetVisualizationRight(), GetVisualizationBottom(), linePaint);
//selection circles
c.drawOval(attackDecayCircle, circleBGPaint);
c.drawOval(attackDecayCircle, circleStrokePaint);
c.drawOval(decaySustainCircle, circleBGPaint);
c.drawOval(decaySustainCircle, circleStrokePaint);
c.drawOval(sustainReleaseCircle, circleBGPaint);
c.drawOval(sustainReleaseCircle, circleStrokePaint);
//draw playhead
if(enabled)
{
c.drawLine(playBarX, GetVisualizationTop(), playBarX, GetVisualizationBottom(), playHeadPaint);
}
//DRAW NUMERIC TOP
//lines
c.drawLine(GetVisualizationLeft()+NUMERIC_LINE_STROKE_WIDTH/2, GetNumericTop(), GetVisualizationLeft()+NUMERIC_LINE_STROKE_WIDTH/2, GetNumericBottom(), numericDisplayPaint);
c.drawLine(GetVisualizationLeft(), GetNumericHorizontalLineHeight(), OffsetMS2Width(adsr.getAttack()), GetNumericHorizontalLineHeight(), numericDisplayPaint);
c.drawLine(OffsetMS2Width(adsr.getAttack()), GetNumericTop(), OffsetMS2Width(adsr.getAttack()), GetNumericBottom(), numericDisplayPaint);
c.drawLine(OffsetMS2Width(adsr.getAttack()), GetNumericHorizontalLineHeight(), SustainLeft(), GetNumericHorizontalLineHeight(), numericDisplayPaint);
c.drawLine(SustainLeft(), GetNumericTop(), SustainLeft(), GetNumericBottom(), numericDisplayPaint);
c.drawLine(SustainRight(), GetNumericTop(), SustainRight(), GetNumericBottom(), numericDisplayPaint);
c.drawLine(SustainRight(), GetNumericHorizontalLineHeight(), GetVisualizationRight(), GetNumericHorizontalLineHeight(), numericDisplayPaint);
c.drawLine(GetVisualizationRight()-NUMERIC_LINE_STROKE_WIDTH/2, GetNumericTop(), GetVisualizationRight()-NUMERIC_LINE_STROKE_WIDTH/2, GetNumericBottom(), numericDisplayPaint);
//text
//attack
float textX = 0;
if(adsr.getAttack() < MIN_DISPLAY_TEXT_WIDTH_IN_MS)
{
textX = OffsetMS2Width(-MIN_DISPLAY_TEXT_WIDTH_IN_MS/2);
} else {
textX = OffsetMS2Width(adsr.getAttack()/2);
}
c.drawText(adsr.getAttackString(), textX, GetNumericTextHeight(), numericDisplayTextPaint);
//decay
if(adsr.getDecay() < MIN_DISPLAY_TEXT_WIDTH_IN_MS)
{
textX = OffsetMS2Width(adsr.getAttack() + adsr.getDecay() + MIN_DISPLAY_TEXT_WIDTH_IN_MS/2);
} else {
textX = OffsetMS2Width(adsr.getAttack()+adsr.getDecay()/2);
}
c.drawText(adsr.getDecayString(), textX, GetNumericTextHeight(), numericDisplayTextPaint);
//sustain
c.drawText(adsr.getSustainString(), SustainLeft() + SustainWidth()/2, GetNumericTextHeight(), numericDisplayTextPaint);
//release
if(adsr.getRelease() < MIN_DISPLAY_TEXT_WIDTH_IN_MS)
{
textX = SustainRight() - MS2Width(MIN_DISPLAY_TEXT_WIDTH_IN_MS/2);
} else {
textX = SustainRight() + MS2Width(adsr.getRelease())/2;
}
c.drawText(adsr.getReleaseString(), textX, GetNumericTextHeight(), numericDisplayTextPaint);
if(!enabled)
{
c.drawRect(GetVisualizationLeft(), 0, getWidth(), getHeight(), disablePaint);
}
}
class PlayBarTask extends TimerTask
{
@Override
public void run()
{
uiHandler.post(new Runnable() {
@Override
public void run() {
UpdatePlayBar();
}
});
}
}
}
| oschneid/mHIVE | mHIVE/src/org/spin/mhive/ADSRView.java | Java | bsd-3-clause | 14,321 |
package org.agmip.ui.quadui;
import org.apache.pivot.beans.BXMLSerializer;
import org.apache.pivot.collections.Map;
import org.apache.pivot.wtk.Application;
import org.apache.pivot.wtk.DesktopApplicationContext;
import org.apache.pivot.wtk.Display;
public class QuadUIApp extends Application.Adapter {
private QuadUIWindow window = null;
@Override
public void startup(Display display, Map<String, String> props) throws Exception {
BXMLSerializer bxml = new BXMLSerializer();
window = (QuadUIWindow) bxml.readObject(getClass().getResource("/quadui.bxml"));
window.open(display);
}
@Override
public boolean shutdown(boolean opt) {
if (window != null) {
window.close();
}
return false;
}
public static void main(String[] args) {
boolean cmdFlg = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("-cli")) {
cmdFlg = true;
break;
}
}
if (cmdFlg) {
QuadCmdLine cmd = new QuadCmdLine();
cmd.run(args);
} else {
DesktopApplicationContext.main(QuadUIApp.class, args);
}
}
}
| agmip/quadui | src/main/java/org/agmip/ui/quadui/QuadUIApp.java | Java | bsd-3-clause | 1,246 |
/*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
@author Steve Jin ([email protected])
*/
public class ApplyProfile extends DynamicData
{
public boolean enabled;
public ProfilePolicy[] policy;
public boolean isEnabled()
{
return this.enabled;
}
public ProfilePolicy[] getPolicy()
{
return this.policy;
}
public void setEnabled(boolean enabled)
{
this.enabled=enabled;
}
public void setPolicy(ProfilePolicy[] policy)
{
this.policy=policy;
}
} | mikem2005/vijava | src/com/vmware/vim25/ApplyProfile.java | Java | bsd-3-clause | 2,114 |
/**
* Copyright (c) 2012-2015, s3auth.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the s3auth.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.s3auth.hosts;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.urn.URN;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Collection of hosts, persisted in Amazon DynamoDB.
*
* <p>The class is mutable and thread-safe.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.0.1
* @checkstyle ClassDataAbstractionCoupling (500 lines)
*/
@SuppressWarnings({ "PMD.TooManyMethods", "PMD.UseConcurrentHashMap" })
@Immutable
@ToString
@EqualsAndHashCode(of = "dynamo")
@Loggable(Loggable.DEBUG)
public final class DynamoHosts implements Hosts {
/**
* Dynamo DB.
*/
private final transient Dynamo dynamo;
/**
* Default ctor.
*/
public DynamoHosts() {
this(new DefaultDynamo());
}
/**
* Default ctor.
* @param dnm The dynamo abstract
*/
public DynamoHosts(@NotNull final Dynamo dnm) {
this.dynamo = dnm;
}
@Override
@NotNull
@Loggable(value = Loggable.DEBUG, ignore = Hosts.NotFoundException.class)
public Host find(
@NotNull(message = "host name can't be NULL")
@Pattern(regexp = "[a-zA-Z0-9\\-\\.]+", message = "invalid host name")
final String name) throws IOException {
final Domain domain = this.byName(name);
if (domain == null) {
throw new Hosts.NotFoundException(
String.format(
// @checkstyle LineLength (1 line)
"host '%s' not found, register it at www.s3auth.com and wait for 10 minutes",
name
)
);
}
return new FastHost(
new SmartHost(
new DefaultHost(new DefaultBucket(domain))
)
);
}
@Override
@NotNull
public Set<Domain> domains(@NotNull @Valid final User user)
throws IOException {
final Map<URN, Domains> data = this.dynamo.load();
Domains domains;
try {
if (user.identity().equals(new URN("urn:github:526301"))) {
domains = new Domains();
for (final Domains dmns : data.values()) {
domains.addAll(dmns);
}
} else {
domains = data.get(user.identity());
}
if (domains == null) {
domains = new Domains();
}
} catch (final URISyntaxException ex) {
throw new IOException(ex);
}
return new DynamoHosts.Wrap(user, domains);
}
@Override
public void close() throws IOException {
this.dynamo.close();
}
/**
* Add new domain for the given user (this method is NOT thread-safe).
* @param user The user
* @param domain The domain
* @return Item was added (FALSE means that we already had it)
*/
private boolean add(final URN user, final Domain domain) {
boolean added = false;
try {
if (this.byName(domain.name()) == null) {
added = this.dynamo.add(user, new DefaultDomain(domain));
}
} catch (final IOException ex) {
throw new IllegalArgumentException(ex);
}
return added;
}
/**
* Remove this domain (this method is NOT thread-safe).
* @param user Who is removing it
* @param domain The domain
* @return Item was removed (FALSE means that we didn't have it)
*/
private boolean remove(final URN user, final Domain domain) {
boolean removed = false;
try {
final Map<URN, Domains> data = this.dynamo.load();
if (data.containsKey(user) && data.get(user).contains(domain)) {
removed = this.dynamo.remove(domain);
}
} catch (final IOException ex) {
throw new IllegalArgumentException(ex);
}
return removed;
}
/**
* Find domain by name or NULL if not found.
* @param name Name of domain to find
* @return Domain found or null
* @throws IOException If something goes wrong
*/
private Domain byName(final String name) throws IOException {
Domain domain = null;
for (final Set<Domain> domains : this.dynamo.load().values()) {
for (final Domain candidate : domains) {
if (candidate.name().equals(name)) {
domain = candidate;
break;
}
}
if (domain != null) {
break;
}
}
return domain;
}
/**
* Wrap of domains.
*/
@Loggable(Loggable.DEBUG)
private final class Wrap extends AbstractSet<Domain> {
/**
* User.
*/
private final transient User user;
/**
* Domains.
*/
private final transient Domains domains;
/**
* Public ctor.
* @param usr User
* @param dmns Domains
*/
Wrap(final User usr, final Domains dmns) {
super();
this.user = usr;
this.domains = dmns;
}
@Override
public int size() {
final Iterator<?> iterator = this.iterator();
int size = 0;
while (iterator.hasNext()) {
iterator.next();
++size;
}
return size;
}
@Override
public Iterator<Domain> iterator() {
return this.domains.iterator();
}
@Override
public boolean contains(final Object obj) {
return this.domains.contains(obj);
}
@Override
public boolean add(@NotNull @Valid final Domain domain) {
return DynamoHosts.this.add(this.user.identity(), domain);
}
@Override
public boolean remove(final Object obj) {
return DynamoHosts.this.remove(
this.user.identity(), Domain.class.cast(obj)
);
}
}
}
| jpetazzo/s3auth | s3auth-hosts/src/main/java/com/s3auth/hosts/DynamoHosts.java | Java | bsd-3-clause | 7,935 |
/*
Copyright (C) 2014 Parrot SA
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of Parrot nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
*/
/*
* GENERATED FILE
* Do not modify this file, it will be erased during the next configure run
*/
package com.parrot.arsdk.arsal;
import java.util.HashMap;
/**
* Java copy of the eARSAL_SOCKET_CLASS_SELECTOR enum
*/
public enum ARSAL_SOCKET_CLASS_SELECTOR_ENUM {
/** Dummy value for all unknown cases */
eARSAL_SOCKET_CLASS_SELECTOR_UNKNOWN_ENUM_VALUE (Integer.MIN_VALUE, "Dummy value for all unknown cases"),
ARSAL_SOCKET_CLASS_SELECTOR_CS0 (0),
ARSAL_SOCKET_CLASS_SELECTOR_UNSPECIFIED (0),
ARSAL_SOCKET_CLASS_SELECTOR_CS1 (32),
ARSAL_SOCKET_CLASS_SELECTOR_CS2 (64),
ARSAL_SOCKET_CLASS_SELECTOR_CS3 (96),
ARSAL_SOCKET_CLASS_SELECTOR_CS4 (128),
ARSAL_SOCKET_CLASS_SELECTOR_CS5 (160),
ARSAL_SOCKET_CLASS_SELECTOR_CS6 (192),
ARSAL_SOCKET_CLASS_SELECTOR_CS7 (224);
private final int value;
private final String comment;
static HashMap<Integer, ARSAL_SOCKET_CLASS_SELECTOR_ENUM> valuesList;
ARSAL_SOCKET_CLASS_SELECTOR_ENUM (int value) {
this.value = value;
this.comment = null;
}
ARSAL_SOCKET_CLASS_SELECTOR_ENUM (int value, String comment) {
this.value = value;
this.comment = comment;
}
/**
* Gets the int value of the enum
* @return int value of the enum
*/
public int getValue () {
return value;
}
/**
* Gets the ARSAL_SOCKET_CLASS_SELECTOR_ENUM instance from a C enum value
* @param value C value of the enum
* @return The ARSAL_SOCKET_CLASS_SELECTOR_ENUM instance, or null if the C enum value was not valid
*/
public static ARSAL_SOCKET_CLASS_SELECTOR_ENUM getFromValue (int value) {
if (null == valuesList) {
ARSAL_SOCKET_CLASS_SELECTOR_ENUM [] valuesArray = ARSAL_SOCKET_CLASS_SELECTOR_ENUM.values ();
valuesList = new HashMap<Integer, ARSAL_SOCKET_CLASS_SELECTOR_ENUM> (valuesArray.length);
for (ARSAL_SOCKET_CLASS_SELECTOR_ENUM entry : valuesArray) {
valuesList.put (entry.getValue (), entry);
}
}
ARSAL_SOCKET_CLASS_SELECTOR_ENUM retVal = valuesList.get (value);
if (retVal == null) {
retVal = eARSAL_SOCKET_CLASS_SELECTOR_UNKNOWN_ENUM_VALUE;
}
return retVal; }
/**
* Returns the enum comment as a description string
* @return The enum description
*/
public String toString () {
if (this.comment != null) {
return this.comment;
}
return super.toString ();
}
}
| Parrot-Developers/libARSAL | gen/JNI/java/com/parrot/arsdk/arsal/ARSAL_SOCKET_CLASS_SELECTOR_ENUM.java | Java | bsd-3-clause | 4,094 |
package org.burroloco.donkey.demo.csv2sql;
import au.net.netstorm.boost.spider.api.config.wire.Wire;
import org.burroloco.config.core.Config;
import org.burroloco.donkey.gargle.NoOpTupleGargler;
import org.burroloco.donkey.gargle.TupleGargler;
import org.burroloco.donkey.job.ConsumeTransformProduce;
import org.burroloco.donkey.job.ExceptionWrapper;
import org.burroloco.donkey.job.Job;
import org.burroloco.donkey.slurp.core.Slurper;
import org.burroloco.donkey.slurp.csv.CsvSlurper;
import org.burroloco.donkey.spit.core.Spitter;
import org.burroloco.donkey.spit.file.FileSpitter;
import org.burroloco.donkey.trebuchet.Wirer;
import org.burroloco.util.wire.Dna;
public class CsvToSqlWirer implements Wirer {
Wire wire;
Dna dna;
public void wire(Config config) {
dna.strand(Job.class, ExceptionWrapper.class, ConsumeTransformProduce.class);
wire.cls(CsvSlurper.class).to(Slurper.class);
wire.cls(NoOpTupleGargler.class).to(TupleGargler.class);
wire.cls(FileSpitter.class).to(Spitter.class);
}
}
| dbastin/donkey | src/java/test/org/burroloco/donkey/demo/csv2sql/CsvToSqlWirer.java | Java | bsd-3-clause | 1,048 |
package com.rehivetech.beeeon;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.graphics.Rect;
import android.os.RemoteException;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.core.UiWatcher;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class Base extends UiAutomatorTestCase {
/************************************************************************************
* Objects definition
***********************************************************************************/
// login google button
public UiObject ib_loginGoogle_ridi = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/login_btn_google")
.index(0));
// login mojeID button
UiObject ib_loginMojeid_ridi = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/login_btn_mojeid")
.index(1));
// demo button
UiObject ib_demo_ridi = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/login_btn_demo")
.index(2));
// Close
UiObject b_close_rid = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/showcase_button"));
// www
UiObject tw_www_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("http://rehivetech.com/"));
// browser title
UiObject tw_browser_t = new UiObject(new UiSelector()
.className(android.widget.EditText.class.getName())
.text("rehivetech.com")
//.text("www.fit.vutbr.cz")
.resourceId("com.android.chrome:id/url_bar"));
//.text("http://www.fit.vutbr.cz")
//.text("http://www.fit.vutbr.cz/ is not available"));
// email
UiObject tw_email_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("[email protected]"));
// Get the device properties
UiDevice myDevice = getUiDevice();
// All App Tray Button
UiObject AppTrayButton = new UiObject(new UiSelector().description("Apps"));
// Get AppTray container
UiScrollable appView = new UiScrollable(new UiSelector().className(
"android.view.View").scrollable(true));
// Apps Tab
UiObject AppsTab = new UiObject(new UiSelector().className(
"android.widget.TextView").description("Apps"));
// Verify the launched application by it's Package name
UiObject beeeonValidation = new UiObject(new UiSelector().packageName("com.rehivetech.beeeon.debug"));
UiObject tw_beeeOn_t = new UiObject(new UiSelector().className(
android.widget.TextView.class.getName())
.text("BeeeOn (debug)"));
UiObject currentPackage = new UiObject(
new UiSelector());
// menu - nav drawer
UiObject ib_navDrawer_i = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(0));
// gamification
UiObject iw_gamification_rid = new UiObject(new UiSelector().className(
android.widget.ImageView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/level"));
// first adapter in menu
UiObject firstAdapterInMenu = new UiObject(new UiSelector()
.className(android.widget.LinearLayout.class.getName())
.index(0));
// second adapter in menu
UiObject secondAdapterInMenu = new UiObject(new UiSelector()
.className(android.widget.LinearLayout.class.getName())
.index(1));
// overview
UiObject overview = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Overview"));
// graphs
UiObject graphs = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Graphs"));
// watchdog
UiObject tw_watchdog_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Watchdog"));
// settings
UiObject tw_settings_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Settings"));
// about
UiObject tw_about_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("About"));
// wastebin - remove device
UiObject tw_bin_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sensor_menu_del"));
// pencil - edit gateway
UiObject tw_pencil_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/ada_menu_edit"));
// users - userd of gateway
UiObject tw_adausers_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/ada_menu_users"));
// wastebin - delete gateway
UiObject tw_adabin_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/ada_menu_del"));
// device name text (TextView)
UiObject senzorNameText = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Karma"));
// device name text (TextView)
UiObject actorNameText = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Televizor"));
// device name text (TextView)
UiObject actorNameText2 = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Lampa u tv"));
// actor switch
UiObject sc_actor_i = new UiObject(new UiSelector()
.index(1));
UiObject sc_actor_rid = new UiObject(new UiSelector()
.resourceId("com.rehivetech.beeeon.debug:id/sen_detail_value_switch"));
// On
UiObject tw_on_i = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("On"));
// Off
UiObject tw_off_i = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Off"));
UiObject tw_onOff_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sen_detail_value"));
// logout (TextView)
UiObject logoutText = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Logout"));
// NEXT
UiObject nextButton = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("NEXT"));
// SKIP
UiObject skipButton = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("SKIP"));
// Cancel
UiObject cancelButton = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("Cancel"));
// START
UiObject startIntroButton = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("START"));
// ADD
UiObject addButton = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("ADD"));
UiObject add = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/add_adapter_next"));
UiObject add2 = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.index(1));
UiObject add3 = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/add_adapter_next")
.index(1)
.text("ADD"));
// ADD user
UiObject b_addUser_rid = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/add_user_adapter_save"));
// SAVE
UiObject b_save_t = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("Save"));
UiObject b_save_rid = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/add_adapter_next"));
// OK
UiObject b_ok_t = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("OK"));
// Rate
UiObject b_rate_t = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.text("Rate"));
// fab button - menu
UiObject ib_fabMenu_rid = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/fab"));
// fab add device
// fab add adapter
UiObject fabAddAdapterButton = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(5));
UiObject im_fabAddAdapter_i = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(3));
// fab add device
UiObject fabAddDeviceButton = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(6));
// fab add user
UiObject b_fabAddUser_rid = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/fab_add_user"));
// adapter name
UiObject nameAdapterEditText = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(1));
// adapter id
UiObject idAdapterEditText = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(2));
// user email
UiObject et_userEmail_rid = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(1));
//.resourceId("rehivetech.beeeon.debug:id/add_user_email"));
//
UiObject toastGatewayActivated = new UiObject(new UiSelector()
.description("Gateway has been activated"));
//
UiObject toastGatewayRemoved = new UiObject(new UiSelector()
.className(android.widget.Toast.class.getName())
//.text("Gateway has been removed")
//.description("Gateway has been removed"));
.resourceId("com.rehivetech.beeeon.debug:id/toast_adapter_removed"));
// device title box - for swiping
UiObject ll_deviceTitleBox_i = new UiObject(new UiSelector()
.className(android.widget.LinearLayout.class.getName())
.index(0));
// new devices layout
UiObject ll_newDevices_i = new UiObject(new UiSelector()
.className(android.widget.LinearLayout.class.getName())
.index(1));
// new device name
UiObject et_deviceName_rid = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/setup_sensor_item_name"));
UiObject et_deviceName_i = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(1));
// new device location
UiObject spi_newDevicelocation_rid = new UiObject(new UiSelector().className(
android.widget.Spinner.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/addsensor_spinner_choose_location"));
UiObject spi_newDevicelocation_i = new UiObject(new UiSelector().className(
android.widget.Spinner.class.getName())
.index(3));
// user role
UiObject spi_userRole_rid = new UiObject(new UiSelector().className(
android.widget.Spinner.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/add_user_gate_save"));
// device added
UiObject t_DeviceAdded_d = new UiObject(new UiSelector()
.description("New device was added"));
// Menu button - guide
UiObject ibBackGuide = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(0));
// edit device
// com.rehivetech.beeeon.debug:id/sen_detail_edit_fab
UiObject ib_editDevice_i = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.index(1));
UiObject ib_editDevice_rid = new UiObject(new UiSelector().className(
android.widget.ImageButton.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sen_detail_edit_fab"));
// renameDevice
// com.rehivetech.beeeon.debug:id/sen_edit_name
UiObject et_renameDevice_rid = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sen_edit_name"));
UiObject et_renameDevice_i = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(1));
// change location spinner
// android.widget.Spinner
// com.rehivetech.beeeon.debug:id/sen_edit_location
UiObject spi_changeDevicelocation_rid = new UiObject(new UiSelector().className(
android.widget.Spinner.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sen_edit_location"));
UiObject spi_changeDevicelocation_i = new UiObject(new UiSelector().className(
android.widget.Spinner.class.getName())
.index(1));
// android.widget.CheckedTextView
// com.rehivetech.beeeon.debug:id/custom_spinner_dropdown_label
/*NOT SPEFICIF
* UiObject chtw_changeDevicelocation_rid = new UiObject(new UiSelector().className(
android.widget.CheckedTextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/custom_spinner_dropdown_label"));*/
UiObject chtw_gardenDevicelocation_t = new UiObject(new UiSelector().className(
android.widget.CheckedTextView.class.getName())
.text("Garden"));
UiObject chtw_bedroomDevicelocation_t = new UiObject(new UiSelector().className(
android.widget.CheckedTextView.class.getName())
.text("Bedroom"));
// device refresh time
// android.widget.SeekBar
// com.rehivetech.beeeon.debug:id/sen_edit_refreshtime
UiObject sb_changeDevicelocation_rid = new UiObject(new UiSelector().className(
android.widget.SeekBar.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/sen_edit_refreshtime"));
UiObject sb_changeDevicelocation_i = new UiObject(new UiSelector().className(
android.widget.SeekBar.class.getName())
.index(1));
// Save
UiObject tw_save_rid = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.resourceId("com.rehivetech.beeeon.debug:id/action_save"));
UiObject tw_save_t = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.text("Save"));
UiObject tw_save_i = new UiObject(new UiSelector()
.className(android.widget.TextView.class.getName())
.index(0));
// logout button
UiObject logout = new UiObject(new UiSelector().description("Logout"));
// Owner
UiObject chtw_owner_t = new UiObject(new UiSelector()
.className(android.widget.CheckedTextView.class.getName())
.text("Owner"));
// Admin
UiObject chtw_admin_t = new UiObject(new UiSelector()
.className(android.widget.CheckedTextView.class.getName())
.text("Admin"));
// User
UiObject chtw_user_t = new UiObject(new UiSelector()
.className(android.widget.CheckedTextView.class.getName())
.text("User"));
// Guest
UiObject chtw_guest_t = new UiObject(new UiSelector()
.className(android.widget.CheckedTextView.class.getName())
.text("Guest"));
/**
* UiWatcher 'anrWatcher' for applications ANR.
* Checks whether a dialog box with "Application not responding" message appears.
*/
UiWatcher anrWatcher = new UiWatcher() {
/**
* Override method checkForCondition() that terminates the executions of tests
* when 'application not responding' text appears in application being tested
* and informs user about it.
* @Override
*/
public boolean checkForCondition() {
UiObject tw_anr_t = new UiObject(new UiSelector().className(
android.widget.TextView.class.getName())
.text("Unfortunately, BeeeOn (debug) has stopped."));
if(tw_anr_t.exists()) {
trace("Application not responding. Test will be terminated");
Runtime.getRuntime().exit(0);
}
// TODO co to tu vracim ? true / false
return false;
}
};
/************************************************************************************
* Methods definition
***********************************************************************************/
public void trace(String message){
System.out.println("### " + message + " ###");
}
public void trace_start(String message){
System.out.println("\n### " + message + " start ###");
}
public void trace_end(String message){
System.out.println("### " + message + " end ###");
}
public void check_intro(){
}
public void check_google_allow() throws UiObjectNotFoundException{
// allow - ok
b_ok_t.waitForExists(5000);
if(b_ok_t.exists()) b_ok_t.clickAndWaitForNewWindow();
}
public void check_no_account() throws UiObjectNotFoundException{
// create beeeon accout - OK
b_ok_t.waitForExists(5000);
if(b_ok_t.exists()) b_ok_t.clickAndWaitForNewWindow();
}
public void choose_an_account(){
}
public void confirm_google(){
}
public void click_through_add_gateway_guide() throws UiObjectNotFoundException{
// b: next
UiObject b_next_u = new UiObject(new UiSelector()
.className(android.widget.Button.class.getName())
.index(2)
.resourceId("com.rehivetech.beeeon.debug:id/add_adapter_next")
.text("NEXT")
.text("Next")
.text("next"));
// clicking on NEXT button
assertTrue("'NEXT' button not found.", b_next_u.exists());
b_next_u.clickAndWaitForNewWindow();
assertTrue("'NEXT' button not found.", b_next_u.exists());
b_next_u.clickAndWaitForNewWindow();
assertTrue("'NEXT' button not found.", b_next_u.exists());
b_next_u.clickAndWaitForNewWindow();
}
/**
*
* @throws UiObjectNotFoundException
*/
public void swipe_through_add_gateway_guide() throws UiObjectNotFoundException{
// b: next
UiObject iw_guide_i = new UiObject(new UiSelector()
.className(android.widget.ImageView.class.getName())
.index(1));
iw_guide_i.swipeLeft(70);
iw_guide_i.swipeLeft(70);
iw_guide_i.swipeLeft(70);
}
public void swipe_through_add_device_guide() throws UiObjectNotFoundException{
// b: next
UiObject iw_guide_i = new UiObject(new UiSelector()
.className(android.widget.ImageView.class.getName())
.index(1));
iw_guide_i.swipeLeft(70);
iw_guide_i.swipeLeft(70);
}
/**
* Method for taking screenshot with timestamp
* @param fileName
* @throws IOException
* @throws InterruptedException
*/
public void takeScreenShot(String fileName) throws IOException, InterruptedException{
long xx = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
Date resultdate = new Date(xx);
String tstamp = sdf.format(resultdate);
Process ptakeScreenShot = Runtime.getRuntime().exec("screencap -p " + "/data/local/tmp/screenshots/" + fileName + "." + tstamp + ".png");
ptakeScreenShot.waitFor();
}
public void add_accounts() throws UiObjectNotFoundException{
// email .address
UiObject et_email_i = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(0));
et_email_i.waitForExists(3000);
if(et_email_i.exists()) {
et_email_i.clearTextField();
et_email_i.setText("[email protected]");
}
// next
UiObject b_next_t = new UiObject(new UiSelector().className(
android.widget.Button.class.getName())
.text("Next"));
UiObject b_i = new UiObject(new UiSelector().className(
android.widget.Button.class.getName())
.index(0));
if(b_i.exists()) b_i.clickAndWaitForNewWindow();
// passwd
UiObject et_passwd_i = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.index(0));
et_passwd_i.waitForExists(3000);
/*if(et_passwd_i.exists()) */
getUiDevice().getInstance().click(540, 924);
et_passwd_i.clearTextField();
et_passwd_i.setText("atr1atr1");
// next
if(b_i.exists()) b_i.clickAndWaitForNewWindow();
// accept Terms of service and Privacy Policy
UiObject b_accept_d = new UiObject(new UiSelector()
.description("ACCEPT"));
b_i.waitForExists(3000);
if(b_i.exists()) {
b_i.clickAndWaitForNewWindow();
sleep(10000);
}
// more
UiObject b_more_t = new UiObject(new UiSelector().className(
android.widget.EditText.class.getName())
.text("More"));
b_i.waitForExists(3000);
if(b_i.exists()) {
b_i.clickAndWaitForNewWindow();
}
// next
if(b_i.exists()) b_next_t.clickAndWaitForNewWindow();
sleep(1000);
}
public void maximize() throws UiObjectNotFoundException, IOException, RemoteException {
// maximize
//myDevice.getInstance().pressMenu();
//myDevice.getInstance().pressKeyCode(0x139);
myDevice.getInstance().pressRecentApps();
if(!tw_beeeOn_t.exists()){
sleep(5000);
}
if(!tw_beeeOn_t.exists()){
// myDevice.getInstance().pressHome();
// myDevice.getInstance().pressMenu();
sleep(5000);
}
tw_beeeOn_t.clickAndWaitForNewWindow();
if(!beeeonValidation.exists()){
sleep(5000);
}
// verify
assertTrue("Unable to detect BeeeOn", beeeonValidation.exists());
}
}
| BeeeOn/android | tests/regress/src/com/rehivetech/beeeon/Base.java | Java | bsd-3-clause | 23,408 |
/*
* Copyright 2014, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.grpc.transport;
import static java.lang.Math.min;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import io.grpc.DeferredInputStream;
import io.grpc.KnownLength;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;
/**
* Encodes gRPC messages to be delivered via the transport layer which implements {@link
* MessageFramer.Sink}.
*/
public class MessageFramer {
/**
* Sink implemented by the transport layer to receive frames and forward them to their
* destination.
*/
public interface Sink {
/**
* Delivers a frame via the transport.
*
* @param frame a non-empty buffer to deliver or {@code null} if the framer is being
* closed and there is no data to deliver.
* @param endOfStream whether the frame is the last one for the GRPC stream
* @param flush {@code true} if more data may not be arriving soon
*/
void deliverFrame(WritableBuffer frame, boolean endOfStream, boolean flush);
}
private static final int HEADER_LENGTH = 5;
private static final byte UNCOMPRESSED = 0;
private static final byte COMPRESSED = 1;
public enum Compression {
NONE, GZIP;
}
private final Sink sink;
private WritableBuffer buffer;
private final Compression compression;
private final OutputStreamAdapter outputStreamAdapter = new OutputStreamAdapter();
private final byte[] headerScratch = new byte[HEADER_LENGTH];
private final WritableBufferAllocator bufferAllocator;
private boolean closed;
/**
* Creates a {@code MessageFramer} without compression.
*
* @param sink the sink used to deliver frames to the transport
* @param bufferAllocator allocates buffers that the transport can commit to the wire.
*/
public MessageFramer(Sink sink, WritableBufferAllocator bufferAllocator) {
this(sink, bufferAllocator, Compression.NONE);
}
/**
* Creates a {@code MessageFramer}.
*
* @param sink the sink used to deliver frames to the transport
* @param bufferAllocator allocates buffers that the transport can commit to the wire.
* @param compression the compression type
*/
public MessageFramer(Sink sink, WritableBufferAllocator bufferAllocator,
Compression compression) {
this.sink = Preconditions.checkNotNull(sink, "sink");
this.bufferAllocator = bufferAllocator;
this.compression = Preconditions.checkNotNull(compression, "compression");
}
/**
* Writes out a payload message.
*
* @param message contains the message to be written out. It will be completely consumed.
*/
public void writePayload(InputStream message) {
verifyNotClosed();
try {
switch (compression) {
case NONE:
int messageLength = getKnownLength(message);
if (messageLength != -1) {
writeKnownLength(message, messageLength, false);
} else {
BufferChainOutputStream bufferChain = new BufferChainOutputStream();
writeToOutputStream(message, bufferChain);
writeBufferChain(bufferChain, false);
}
break;
case GZIP:
BufferChainOutputStream bufferChain = new BufferChainOutputStream();
gzipCompressTo(message, bufferChain);
writeBufferChain(bufferChain, true);
break;
default:
throw new AssertionError("Unknown compression type");
}
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
private int getKnownLength(InputStream inputStream) throws IOException {
if (inputStream instanceof KnownLength || inputStream instanceof ByteArrayInputStream) {
return inputStream.available();
}
return -1;
}
private static void gzipCompressTo(InputStream in, OutputStream out)
throws IOException {
int messageLength = -1;
if (in instanceof KnownLength) {
messageLength = in.available();
}
GZIPOutputStream compressingStream = new GZIPOutputStream(out);
try {
long written = writeToOutputStream(in, compressingStream);
if (messageLength != -1 && messageLength != written) {
throw new RuntimeException("Message length was inaccurate");
}
} finally {
compressingStream.close();
}
}
/**
* Write an unserialized message with a known length.
*/
private void writeKnownLength(InputStream message, int messageLength, boolean compressed)
throws IOException {
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(compressed ? COMPRESSED : UNCOMPRESSED);
header.putInt(messageLength);
// Allocate the initial buffer chunk based on frame header + payload length.
// Note that the allocator may allocate a buffer larger or smaller than this length
if (buffer == null) {
buffer = bufferAllocator.allocate(header.position() + messageLength);
}
writeRaw(headerScratch, 0, header.position());
long written = writeToOutputStream(message, outputStreamAdapter);
if (messageLength != written) {
throw new RuntimeException("Message length was inaccurate");
}
}
/**
* Write a message that has been serialized to a sequence of buffers.
*/
private void writeBufferChain(BufferChainOutputStream bufferChain, boolean compressed)
throws IOException {
ByteBuffer header = ByteBuffer.wrap(headerScratch);
header.put(compressed ? COMPRESSED : UNCOMPRESSED);
int messageLength = bufferChain.readableBytes();
header.putInt(messageLength);
WritableBuffer writeableHeader = bufferAllocator.allocate(HEADER_LENGTH);
writeableHeader.write(headerScratch, 0, header.position());
if (messageLength == 0) {
// the payload had 0 length so make the header the current buffer.
buffer = writeableHeader;
return;
}
// Note that we are always delivering a small message to the transport here which
// may incur transport framing overhead as it may be sent separately to the contents
// of the GRPC frame.
sink.deliverFrame(writeableHeader, false, false);
// Commit all except the last buffer to the sink
List<WritableBuffer> bufferList = bufferChain.bufferList;
for (int i = 0; i < bufferList.size() - 1; i++) {
sink.deliverFrame(bufferList.get(i), false, false);
}
// Assign the current buffer to the last in the chain so it can be used
// for future writes or written with end-of-stream=true on close.
buffer = bufferList.get(bufferList.size() - 1);
}
@SuppressWarnings("rawtypes")
private static long writeToOutputStream(InputStream message, OutputStream outputStream)
throws IOException {
if (message instanceof DeferredInputStream) {
return ((DeferredInputStream) message).flushTo(outputStream);
} else {
// This makes an unnecessary copy of the bytes when bytebuf supports array(). However, we
// expect performance-critical code to support flushTo().
return ByteStreams.copy(message, outputStream);
}
}
private void writeRaw(byte[] b, int off, int len) {
while (len > 0) {
if (buffer != null && buffer.writableBytes() == 0) {
commitToSink(false, false);
}
if (buffer == null) {
// Request a buffer allocation using the message length as a hint.
buffer = bufferAllocator.allocate(len);
}
int toWrite = min(len, buffer.writableBytes());
buffer.write(b, off, toWrite);
off += toWrite;
len -= toWrite;
}
}
/**
* Flushes any buffered data in the framer to the sink.
*/
public void flush() {
if (buffer != null && buffer.readableBytes() > 0) {
commitToSink(false, true);
}
}
/**
* Indicates whether or not this framer has been closed via a call to either
* {@link #close()} or {@link #dispose()}.
*/
public boolean isClosed() {
return closed;
}
/**
* Flushes and closes the framer and releases any buffers. After the framer is closed or
* disposed, additional calls to this method will have no affect.
*/
public void close() {
if (!isClosed()) {
closed = true;
// With the current code we don't expect readableBytes > 0 to be possible here, added
// defensively to prevent buffer leak issues if the framer code changes later.
if (buffer != null && buffer.readableBytes() == 0) {
buffer.release();
buffer = null;
}
commitToSink(true, true);
}
}
/**
* Closes the framer and releases any buffers, but does not flush. After the framer is
* closed or disposed, additional calls to this method will have no affect.
*/
public void dispose() {
closed = true;
if (buffer != null) {
buffer.release();
buffer = null;
}
}
private void commitToSink(boolean endOfStream, boolean flush) {
sink.deliverFrame(buffer, endOfStream, flush);
buffer = null;
}
private void verifyNotClosed() {
if (isClosed()) {
throw new IllegalStateException("Framer already closed");
}
}
/** OutputStream whose write()s are passed to the framer. */
private class OutputStreamAdapter extends OutputStream {
private final byte[] singleByte = new byte[1];
@Override
public void write(int b) {
singleByte[0] = (byte) b;
write(singleByte, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) {
writeRaw(b, off, len);
}
}
/**
* Produce a collection of {@link WritableBuffer} instances from the data written to an
* {@link OutputStream}.
*/
private class BufferChainOutputStream extends OutputStream {
private final byte[] singleByte = new byte[1];
private List<WritableBuffer> bufferList;
private WritableBuffer current;
private BufferChainOutputStream() {
bufferList = new ArrayList<WritableBuffer>();
}
@Override
public void write(int b) throws IOException {
singleByte[0] = (byte) b;
write(singleByte, 0, 1);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
if (current == null) {
// Request len bytes initially from the allocator, it may give us more.
current = bufferAllocator.allocate(len);
bufferList.add(current);
}
while (len > 0) {
int canWrite = Math.min(len, current.writableBytes());
if (canWrite == 0) {
// Assume message is twice as large as previous assumption if were still not done,
// the allocator may allocate more or less than this amount.
current = bufferAllocator.allocate(current.readableBytes() * 2);
bufferList.add(current);
} else {
current.write(b, off, canWrite);
off += canWrite;
len -= canWrite;
}
}
}
private int readableBytes() {
int readable = 0;
for (WritableBuffer writableBuffer : bufferList) {
readable += writableBuffer.readableBytes();
}
return readable;
}
}
}
| jcanizales/grpc-java | core/src/main/java/io/grpc/transport/MessageFramer.java | Java | bsd-3-clause | 12,771 |
package org.jetbrains.protocolReader;
import org.jetbrains.protocolReader.TextOutput;
abstract class ClassNameScheme {
private final String suffix;
private final String rootPackage;
private ClassNameScheme(String suffix, String rootPackage) {
this.suffix = suffix;
this.rootPackage = rootPackage;
}
NamePath getFullName(String domainName, String baseName) {
return new NamePath(getShortName(baseName), new NamePath(getPackageNameVirtual(domainName)));
}
String getShortName(String baseName) {
return Generator.capitalizeFirstChar(baseName) + suffix;
}
TextOutput appendShortName(TextOutput out, String baseName) {
if (!baseName.isEmpty() && Character.isLowerCase(baseName.charAt(0))) {
out.append(Character.toUpperCase(baseName.charAt(0))).append(baseName, 1);
}
out.append(suffix);
return out;
}
protected String getPackageNameVirtual(String domainName) {
return getPackageName(rootPackage, domainName);
}
public static String getPackageName(String rootPackage, String domain) {
if (domain.isEmpty()) {
return rootPackage;
}
return rootPackage + '.' + domain.toLowerCase();
}
static class Input extends ClassNameScheme {
Input(String suffix, String rootPackage) {
super(suffix, rootPackage);
}
String getParseMethodName(String domain, String name) {
return "read" + Generator.capitalizeFirstChar(domain) + getShortName(name);
}
}
static class Output extends ClassNameScheme {
Output(String suffix, String rootPackage) {
super(suffix, rootPackage);
}
}
static class Common extends ClassNameScheme {
Common(String suffix, String rootPackage) {
super(suffix, rootPackage);
}
}
} | develar/chromedevtools | protocol/protocol-model-generator/src/org/jetbrains/protocolReader/ClassNameScheme.java | Java | bsd-3-clause | 1,744 |
/*
Copyright (c) 2008, Jared Crapo All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of jactiveresource.org nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.jactiveresource;
/**
* exception for http status 401 - Unauthorized
*
* @version $LastChangedRevision$ <br>
* $LastChangedDate$
* @author $LastChangedBy$
*/
public class UnauthorizedAccess extends ClientError {
private static final long serialVersionUID = 1L;
public UnauthorizedAccess() {
super();
}
public UnauthorizedAccess( String s ) {
super( s );
}
public UnauthorizedAccess( String message, Throwable cause ) {
super( message, cause );
}
}
| jactiveresource/jactiveresource | src/main/java/org/jactiveresource/UnauthorizedAccess.java | Java | bsd-3-clause | 2,034 |
package de.plushnikov.intellij.plugin.action.delombok;
import com.intellij.openapi.actionSystem.AnAction;
import de.plushnikov.intellij.plugin.action.LombokLightActionTest;
public class DelombokSetterActionTest extends LombokLightActionTest {
protected AnAction getAction() {
return new DelombokSetterAction();
}
@Override
protected String getBasePath() {
return super.getBasePath() + "/action/delombok/setter";
}
public void testSetterFields() throws Exception {
doTest();
}
public void testSetterClass() throws Exception {
doTest();
}
}
| mg6maciej/hrisey-intellij-plugin | lombok-plugin/src/test/java/de/plushnikov/intellij/plugin/action/delombok/DelombokSetterActionTest.java | Java | bsd-3-clause | 581 |
package io.burt.jmespath;
/**
* This enum represents the six value types defined in the JMESPath specification.
*/
public enum JmesPathType {
NUMBER,
STRING,
BOOLEAN,
ARRAY,
OBJECT,
NULL;
@Override
public String toString() {
return name().toLowerCase();
}
}
| burtcorp/jmespath-java | jmespath-core/src/main/java/io/burt/jmespath/JmesPathType.java | Java | bsd-3-clause | 284 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class GlobalMessageChangedEvent extends SessionEvent {
public String message;
public String getMessage() {
return this.message;
}
public void setMessage(String message) {
this.message=message;
}
} | xebialabs/vijava | src/com/vmware/vim25/GlobalMessageChangedEvent.java | Java | bsd-3-clause | 1,989 |
// ex: se sts=4 sw=4 expandtab:
/**
* Yeti core library - Selector function.
*
* Copyright (c) 2008 Madis Janson
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package yeti.lang;
public final class Selector extends Fun {
private final String name;
public Selector(String aName) {
name = aName;
}
public final Object apply(Object value) {
return ((Struct) value).get(name);
}
public String toString() {
return "(." + name + ')';
}
}
| chrisichris/yetiscript | srclib/yeti/lang/Selector.java | Java | bsd-3-clause | 1,873 |
/*
******************************************************************
Copyright (c) 2001-2011, Jeff Martin, Tim Bacon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the xmlunit.sourceforge.net nor the names
of its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
******************************************************************
*/
package org.custommonkey.xmlunit;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.StringReader;
import java.util.HashMap;
import junit.framework.AssertionFailedError;
import junit.framework.TestSuite;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Test case used to test the XMLTestCase
*/
public class test_XMLTestCase extends XMLTestCase {
private static final String PREFIX = "foo";
private static final String TEST_NS = "urn:org.example";
private static final NamespaceContext NS_CONTEXT;
static {
HashMap m = new HashMap();
m.put(PREFIX, TEST_NS);
NS_CONTEXT = new SimpleNamespaceContext(m);
}
private final String[] control = new String[]{
"<root/>",
"<root></root>",
"<root>test</root>",
"<root attr=\"test\">test</root>",
"<test/>",
"<root>test</root>",
"<root attr=\"test\"/>",
"<root><outer><inner></inner></outer></root>",
"<root attr=\"test\"><outer>test<inner>test</inner></outer></root>",
"<root attr=\"test\"><outer>test<inner>test</inner></outer></root>"
};
private final String[] test = new String[]{
"<fail/>",
"<fail/>",
"<fail>test</fail>",
"<root>test</root>",
"<fail/>",
"<root>fail</root>",
"<root attr=\"fail\"/>",
"<root><outer><inner>test</inner></outer></root>",
"<root attr=\"test\"><outer>fail<inner>test</inner></outer></root>",
"<root attr=\"fail\"><outer>test<inner>test</inner></outer></root>"
};
/**
* Test for the compareXML method.
*/
public void testCompareXMLStrings() throws Exception {
for(int i=0;i<control.length;i++){
assertEquals("compareXML case " + i + " failed", true,
compareXML(control[i], control[i]).similar());
assertEquals("!compareXML case " + i + " failed", false,
compareXML(control[i], test[i]).similar());
}
}
/**
* Test the comparision of two files
*/
public void testXMLEqualsFiles() throws Exception {
assertXMLEqual(new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"),
new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"));
assertXMLNotEqual(new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"),
new FileReader(
test_Constants.BASEDIR + "/tests/etc/test2.xml"));
// Bug 956372
assertXMLEqual("equal message", new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"),
new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"));
assertXMLNotEqual("notEqual message", new FileReader(
test_Constants.BASEDIR + "/tests/etc/test1.xml"),
new FileReader(
test_Constants.BASEDIR + "/tests/etc/test2.xml"));
try{
assertXMLNotEqual(new FileReader("nosuchfile.xml"),
new FileReader("nosuchfile.xml"));
fail("Expecting FileNotFoundException");
}catch(FileNotFoundException e){}
}
/**
* Test for the assertXMLEquals method.
*/
public void testXMLEqualsStrings() throws Exception {
for(int i=0;i<control.length;i++){
assertXMLEqual("assertXMLEquals test case " + i + " failed",
control[i], control[i]);
assertXMLNotEqual("assertXMLNotEquals test case" + i + " failed",
control[i], test[i]);
}
}
/**
* Test for the assertXMLEquals method.
*/
public void testXMLEqualsDocuments() throws Exception {
Document controlDocument, testDocument;
for(int i=0;i<control.length;i++){
controlDocument = XMLUnit.buildControlDocument(control[i]);
assertXMLEqual("assertXMLEquals test case " + i + " failed",
controlDocument, controlDocument);
testDocument = XMLUnit.buildTestDocument(test[i]);
assertXMLNotEqual("assertXMLNotEquals test case" + i + " failed",
controlDocument, testDocument);
}
}
private static final String xpathValuesControlXML =
"<root><outer attr=\"urk\"><inner attr=\"urk\">"
+ "controlDocument</inner></outer></root>";
private static final String xpathValuesTestXML =
"<root><outer attr=\"urk\"><inner attr=\"ugh\">"
+ "testDocument</inner></outer></root>";
private static final String xpathValuesControlXMLNS =
addNamespaceToDocument(xpathValuesControlXML);
private static final String xpathValuesTestXMLNS =
addNamespaceToDocument(xpathValuesTestXML);
public void testXpathValuesEqualUsingDocument() throws Exception {
Document controlDocument = XMLUnit.buildControlDocument(xpathValuesControlXML);
Document testDocument = XMLUnit.buildTestDocument(xpathValuesTestXML);
assertXpathValuesEqual("//text()", "//inner/text()", controlDocument);
assertXpathValuesEqual("//inner/@attr", controlDocument,
"//outer/@attr", testDocument);
assertXpathValuesNotEqual("//inner/text()", "//outer/@attr", controlDocument);
assertXpathValuesNotEqual("//inner/text()", controlDocument,
"//text()", testDocument);
}
public void testXpathValuesEqualUsingDocumentNS() throws Exception {
Document controlDocument = XMLUnit.buildControlDocument(xpathValuesControlXMLNS);
Document testDocument = XMLUnit.buildTestDocument(xpathValuesTestXMLNS);
assertXpathValuesNotEqual("//text()",
"//inner/text()", controlDocument);
XMLUnit.setXpathNamespaceContext(NS_CONTEXT);
assertXpathValuesEqual("//text()",
"//" + PREFIX + ":inner/text()",
controlDocument);
assertXpathValuesEqual("//" + PREFIX + ":inner/@attr", controlDocument,
"//" + PREFIX + ":outer/@attr", testDocument);
assertXpathValuesNotEqual("//" + PREFIX + ":inner/text()",
"//" + PREFIX + ":outer/@attr",
controlDocument);
assertXpathValuesNotEqual("//" + PREFIX + ":inner/text()",
controlDocument,
"//text()",
testDocument);
}
public void testXpathValuesEqualUsingString() throws Exception {
assertXpathValuesEqual("//text()", "//inner/text()", xpathValuesControlXML);
assertXpathValuesEqual("//inner/@attr", xpathValuesControlXML,
"//outer/@attr", xpathValuesTestXML);
assertXpathValuesNotEqual("//inner/text()", "//outer/@attr", xpathValuesControlXML);
assertXpathValuesNotEqual("//inner/text()", xpathValuesControlXML,
"//text()", xpathValuesTestXML);
}
public void testXpathValuesEqualUsingStringNS() throws Exception {
assertXpathValuesNotEqual("//text()", "//inner/text()",
xpathValuesControlXMLNS);
XMLUnit.setXpathNamespaceContext(NS_CONTEXT);
assertXpathValuesEqual("//text()",
"//" + PREFIX + ":inner/text()",
xpathValuesControlXMLNS);
assertXpathValuesEqual("//" + PREFIX + ":inner/@attr",
xpathValuesControlXMLNS,
"//" + PREFIX + ":outer/@attr",
xpathValuesTestXMLNS);
assertXpathValuesNotEqual("//" + PREFIX + ":inner/text()",
"//" + PREFIX + ":outer/@attr",
xpathValuesControlXMLNS);
assertXpathValuesNotEqual("//" + PREFIX + ":inner/text()",
xpathValuesControlXMLNS,
"//text()", xpathValuesTestXMLNS);
}
public void testXpathEvaluatesTo() throws Exception {
assertXpathEvaluatesTo("urk", "//outer/@attr", xpathValuesControlXML);
try {
assertXpathEvaluatesTo("yum", "//inner/@attr", xpathValuesControlXML);
fail("Expected assertion to fail #1");
} catch (AssertionFailedError e) {
}
assertXpathEvaluatesTo("2", "count(//@attr)", xpathValuesControlXML);
Document testDocument = XMLUnit.buildTestDocument(xpathValuesTestXML);
assertXpathEvaluatesTo("ugh", "//inner/@attr", testDocument);
try {
assertXpathEvaluatesTo("yeah", "//outer/@attr", testDocument);
fail("Expected assertion to fail #2");
} catch (AssertionFailedError e) {
}
}
public void testXpathEvaluatesToNS() throws Exception {
try {
assertXpathEvaluatesTo("urk", "//outer/@attr",
xpathValuesControlXMLNS);
fail("Expected assertion to fail #1");
} catch (AssertionFailedError e) {
}
XMLUnit.setXpathNamespaceContext(NS_CONTEXT);
assertXpathEvaluatesTo("urk", "//" + PREFIX + ":outer/@attr",
xpathValuesControlXMLNS);
try {
assertXpathEvaluatesTo("yum", "//" + PREFIX + ":inner/@attr",
xpathValuesControlXMLNS);
fail("Expected assertion to fail #2");
} catch (AssertionFailedError e) {
}
assertXpathEvaluatesTo("2", "count(//@attr)", xpathValuesControlXMLNS);
Document testDocument = XMLUnit.buildTestDocument(xpathValuesTestXMLNS);
assertXpathEvaluatesTo("ugh", "//" + PREFIX + ":inner/@attr",
testDocument);
try {
assertXpathEvaluatesTo("yeah", "//" + PREFIX + ":outer/@attr",
testDocument);
fail("Expected assertion to fail #3");
} catch (AssertionFailedError e) {
}
}
public void testNodeTest() throws Exception {
NodeTester tester = new CountingNodeTester(1);
assertNodeTestPasses(xpathValuesControlXML, tester, Node.TEXT_NODE);
try {
assertNodeTestPasses(xpathValuesControlXML, tester, Node.ELEMENT_NODE);
fail("Expected node test failure #1!");
} catch (AssertionFailedError e) {
}
NodeTest test = new NodeTest(new StringReader(xpathValuesTestXML));
tester = new CountingNodeTester(4);
assertNodeTestPasses(test, tester,
new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}, true);
assertNodeTestPasses(test, tester,
new short[] {Node.TEXT_NODE, Node.COMMENT_NODE}, false);
try {
assertNodeTestPasses(test, tester,
new short[] {Node.TEXT_NODE, Node.ELEMENT_NODE}, false);
fail("Expected node test failure #2!");
assertNodeTestPasses(test, tester,
new short[] {Node.TEXT_NODE, Node.COMMENT_NODE}, true);
fail("Expected node test failure #3!");
} catch (AssertionFailedError e) {
}
}
public void testXMLValid() {
// see test_Validator class
}
private static final String TREES_OPEN = "<trees>";
private static final String TREES_CLOSE = "</trees>";
private static final String xpathNodesControlXML = TREES_OPEN
+ "<tree evergreen=\"false\">oak</tree>"
+ "<tree evergreen=\"false\">ash</tree>"
+ "<tree evergreen=\"true\">scots pine</tree>"
+ "<tree evergreen=\"true\">spruce</tree>"
+ "<favourite><!-- is this a tree or a bush?! -->"
+ "<tree evergreen=\"false\">magnolia</tree>"
+ "</favourite>"
+ "<fruit>"
+ "<apples><crunchy/><yum/><tree evergreen=\"false\">apple</tree></apples>"
+ "</fruit>"
+ TREES_CLOSE;
private static final String xpathNodesTestXML = TREES_OPEN
+ "<tree evergreen=\"false\">oak</tree>"
+ "<tree evergreen=\"false\">ash</tree>"
+ "<tree evergreen=\"true\">scots pine</tree>"
+ "<tree evergreen=\"true\">spruce</tree>"
+ "<tree flowering=\"true\">cherry</tree>"
+ "<tree flowering=\"true\">apple</tree>"
+ "<favourite><!-- is this a tree or a bush?! -->"
+ "<tree evergreen=\"false\">magnolia</tree>"
+ "</favourite>"
+ "<apples><crunchy/><yum/><tree evergreen=\"false\">apple</tree></apples>"
+ TREES_CLOSE;
public void testXpathsEqual() throws Exception {
Document controlDoc = XMLUnit.buildControlDocument(xpathNodesControlXML);
Document testDoc = XMLUnit.buildTestDocument(xpathNodesTestXML);
String[] controlXpath = new String[]{"/trees/tree[@evergreen]",
"//tree[@evergreen='false']",
"/trees/favourite",
"//fruit/apples"};
String[] testXpath = {controlXpath[0],
controlXpath[1],
"//favourite",
"//apples"};
// test positive passes
for (int i=0; i < controlXpath.length; ++i) {
assertXpathsEqual(controlXpath[i], controlDoc,
testXpath[i], testDoc);
assertXpathsEqual(controlXpath[i], xpathNodesControlXML,
testXpath[i], xpathNodesTestXML);
assertXpathsEqual(controlXpath[i], testXpath[i], controlDoc);
assertXpathsEqual(controlXpath[i], testXpath[i], xpathNodesControlXML);
}
// test negative fails
for (int i=0; i < controlXpath.length; ++i) {
try {
assertXpathsNotEqual(controlXpath[i], controlDoc,
testXpath[i], testDoc);
fail("should not be notEqual!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsNotEqual(controlXpath[i], xpathNodesControlXML,
testXpath[i], xpathNodesTestXML);
fail("should not be notEqual!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsNotEqual(controlXpath[i], testXpath[i], controlDoc);
fail("should not be notEqual!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsNotEqual(controlXpath[i], testXpath[i], xpathNodesControlXML);
fail("should not be notEqual!");
} catch (AssertionFailedError e) {
}
}
}
public void testXpathsNotEqual() throws Exception {
Document controlDoc = XMLUnit.buildControlDocument(xpathNodesControlXML);
Document testDoc = XMLUnit.buildTestDocument(xpathNodesTestXML);
String[] controlXpath = new String[]{"/trees/tree[@evergreen]",
"//tree[@evergreen='false']",
"/trees/favourite",
"//fruit/apples"};
String[] testXpath = {"//tree",
"//tree[@evergreen='true']",
"//favourite/apples",
"//apples/tree"};
// test positive passes
for (int i=0; i < controlXpath.length; ++i) {
assertXpathsNotEqual(controlXpath[i], controlDoc,
testXpath[i], testDoc);
assertXpathsNotEqual(controlXpath[i], xpathNodesControlXML,
testXpath[i], xpathNodesTestXML);
assertXpathsNotEqual(controlXpath[i], testXpath[i], controlDoc);
assertXpathsNotEqual(controlXpath[i], testXpath[i], xpathNodesControlXML);
}
// test negative fails
for (int i=0; i < controlXpath.length; ++i) {
try {
assertXpathsEqual(controlXpath[i], controlDoc,
testXpath[i], testDoc);
fail("should not be Equal!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsEqual(controlXpath[i], xpathNodesControlXML,
testXpath[i], xpathNodesTestXML);
fail("should not be Equal!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsEqual(controlXpath[i], testXpath[i], controlDoc);
fail("should not be Equal!");
} catch (AssertionFailedError e) {
}
try {
assertXpathsEqual(controlXpath[i], testXpath[i], xpathNodesControlXML);
fail("should not be Equal!");
} catch (AssertionFailedError e) {
}
}
}
public void testDocumentAssertXpathExists() throws Exception {
Document controlDoc = XMLUnit.buildControlDocument(xpathNodesControlXML);
assertXpathExists("/trees/fruit/apples/yum", controlDoc);
assertXpathExists("//tree[@evergreen='false']", controlDoc);
try {
assertXpathExists("//tree[@evergreen='idunno']", controlDoc);
fail("Xpath does not exist");
} catch (AssertionFailedError e) {
// expected
}
}
public void testStringAssertXpathExists() throws Exception {
assertXpathExists("/trees/fruit/apples/yum", xpathNodesControlXML);
assertXpathExists("//tree[@evergreen='false']", xpathNodesControlXML);
try {
assertXpathExists("//tree[@evergreen='idunno']", xpathNodesControlXML);
fail("Xpath does not exist");
} catch (AssertionFailedError e) {
// expected
}
}
public void testDocumentAssertNotXpathExists() throws Exception {
Document controlDoc = XMLUnit.buildControlDocument(xpathNodesControlXML);
assertXpathNotExists("//tree[@evergreen='idunno']", controlDoc);
try {
assertXpathNotExists("/trees/fruit/apples/yum", controlDoc);
fail("Xpath does exist, once");
} catch (AssertionFailedError e) {
// expected
}
try {
assertXpathNotExists("//tree[@evergreen='false']", controlDoc);
fail("Xpath does exist many times");
} catch (AssertionFailedError e) {
// expected
}
}
public void testStringAssertNotXpathExists() throws Exception {
assertXpathNotExists("//tree[@evergreen='idunno']", xpathNodesControlXML);
try {
assertXpathNotExists("/trees/fruit/apples/yum", xpathNodesControlXML);
fail("Xpath does exist, once");
} catch (AssertionFailedError e) {
// expected
}
try {
assertXpathNotExists("//tree[@evergreen='false']", xpathNodesControlXML);
fail("Xpath does exist many times");
} catch (AssertionFailedError e) {
// expected
}
}
// Bug 585555
public void testUnusedNamespacesDontMatter() throws Exception
{
boolean startValueIgnoreWhitespace = XMLUnit.getIgnoreWhitespace();
try {
XMLUnit.setIgnoreWhitespace(true);
String a = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<outer xmlns:NS2=\"http://namespace2/foo\">\n" +
" <inner xmlns:NS2=\"http://namespace2/\">5</inner>\n" +
"</outer>\n";
String b = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<outer xmlns:NS2=\"http://namespace2\">\n" +
" <inner xmlns:NS2=\"http://namespace2/\">5</inner>\n" +
"</outer>\n";
assertXMLEqual(a, b);
} finally {
XMLUnit.setIgnoreWhitespace(startValueIgnoreWhitespace);
}
}
// Bug 585555
public void testNamespaceMatters() throws Exception
{
boolean startValueIgnoreWhitespace = XMLUnit.getIgnoreWhitespace();
try {
XMLUnit.setIgnoreWhitespace(true);
String a = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<outer xmlns=\"http://namespace2/\">\n" +
"</outer>";
String b = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<outer xmlns=\"http://namespace2\">\n" +
"</outer>\n";
assertXMLNotEqual(a, b);
} finally {
XMLUnit.setIgnoreWhitespace(startValueIgnoreWhitespace);
}
}
// Bug 741636
public void testXpathCount() throws Exception {
assertXpathEvaluatesTo("25", "count(//td)",
"<div><p>" +
"</p><table><tr><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td></tr><tr><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td></tr><tr><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td></tr><tr><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td></tr><tr><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td><td><p>" +
"</p></td></tr></table></div>");
}
// bug 1418497
public void testAssertXpathExistsFails() throws Exception {
String xmlDocument = "<axrtable> <schema name=\"emptySchema\"><relation name=\"\"></relation></schema></axrtable>";
assertXpathExists("/axrtable/schema", xmlDocument);
}
// bug 3290264
public void testAssertXpathEqualsAndAttributes() throws Exception {
assertXpathsNotEqual("/foo/Bar/@a", "/foo/Bar",
"<foo><Bar a=\"1\" /></foo>");
assertXpathsNotEqual("/foo/Bar/@a", "/foo/Bar/@b",
"<foo><Bar a=\"1\" b=\"1\"/></foo>");
assertXpathsEqual("/foo/Bar/@a", "/foo/Bar/@a",
"<foo><Bar a=\"1\" b=\"2\"/></foo>");
}
public test_XMLTestCase(String name) {
super(name);
}
private static String addNamespaceToDocument(String original) {
int pos = original.indexOf(">");
return original.substring(0, pos) + " xmlns='" + TEST_NS + "'"
+ original.substring(pos);
}
public void tearDown() {
XMLUnit.setXpathNamespaceContext(null);
}
/**
* returns the TestSuite containing this test
*/
public static TestSuite suite(){
return new TestSuite(test_XMLTestCase.class);
}
}
| wallymathieu/XmlUnit | tests/java/org/custommonkey/xmlunit/test_XMLTestCase.java | Java | bsd-3-clause | 25,928 |
package org.lielas.dataloggerstudio.lib.Logger.MeasurementType;
/**
* Created by Andi on 16.09.2015.
*/
public abstract class MeasurementType {
public abstract double toMetric(double value);
public abstract double toImperial(double value);
}
| anre/LielasDataloggerstudio | src/dataloggerstudio/lib/Logger/MeasurementType/MeasurementType.java | Java | bsd-3-clause | 256 |
/*
* Copyright (c) 2009, Jan Stender, Bjoern Kolbeck, Mikael Hoegqvist,
* Felix Hupfeld, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.babudb.sandbox;
import java.util.Iterator;
import java.util.Random;
import java.util.Map.Entry;
import org.xtreemfs.babudb.api.BabuDB;
import org.xtreemfs.babudb.api.database.UserDefinedLookup;
import org.xtreemfs.babudb.api.exception.BabuDBException;
import org.xtreemfs.babudb.lsmdb.LSMLookupInterface;
/**
*
* @author bjko
*/
public class BenchmarkWorkerThread extends Thread {
public static enum BenchmarkOperation {
INSERT,
ITERATE,
LOOKUP,
UDL,
DIRECT_LOOKUP
};
private final int numKeys;
private final int id;
private final int minKeyLength;
private final int maxKeyLength;
private final byte[] payload;
private final BabuDB database;
private final BenchmarkOperation operation;
private volatile boolean done;
private volatile Exception error;
private volatile double throughput;
private final String dbName;
private final Random random;
public BenchmarkWorkerThread(int id, int numKeys, int minKeyLength,
int maxKeyLength, byte[] payload, BabuDB database, BenchmarkOperation operation) {
this(id,numKeys,minKeyLength,maxKeyLength,payload,database,operation,"",0L);
}
public BenchmarkWorkerThread(int id, int numKeys, int minKeyLength,
int maxKeyLength, byte[] payload, BabuDB database, BenchmarkOperation operation, String dbPrefix, long seed) {
this.id = id;
this.numKeys = numKeys;
this.minKeyLength = minKeyLength;
this.maxKeyLength = maxKeyLength;
this.payload = payload;
this.database = database;
this.operation = operation;
this.dbName = dbPrefix+Integer.toString(id);
this.random = new Random(seed);
error = null;
done = false;
}
public void run() {
try {
switch (operation) {
case INSERT : performInserts(); break;
case LOOKUP : performLookups(); break;
case DIRECT_LOOKUP : performDirectLookups(); break;
case ITERATE : countKeys(); break;
case UDL : performUserDefinedLookups(); break;
}
} catch (Exception ex) {
error = ex;
}
synchronized (this) {
done = true;
this.notifyAll();
}
}
public double waitForResult() throws Exception {
synchronized (this) {
if (!done) {
this.wait();
}
if (error != null) {
throw error;
}
return throughput;
}
}
public void performInserts() throws BabuDBException, InterruptedException {
long tStart = System.currentTimeMillis();
byte[] key = null;
for (int i = 0; i < numKeys; i++) {
key = createRandomKey();
database.getDatabaseManager().getDatabase(dbName).singleInsert(0, key, payload, null).get();
}
long tEnd = System.currentTimeMillis();
double dur = (tEnd-tStart);
String output = String.format(" thread #%3d: insert of %d keys took %.4f seconds\n", id ,numKeys,dur/1000.0);
output += String.format(" thread #%3d: = %10.4f s/key\n",id,(dur/1000.0)/((double)numKeys));
output += String.format(" thread #%3d: = %10.4f keys/s\n\n",id,((double)numKeys)/(dur/1000.0));
throughput = ((double)numKeys)/(dur/1000.0);
System.out.print(output);
}
public void countKeys() throws BabuDBException, InterruptedException {
long tStart = System.currentTimeMillis();
Iterator<Entry<byte[],byte[]>> iter = database.getDatabaseManager().getDatabase(dbName).prefixLookup(0, new byte[]{}, null).get();
int count = 0;
while (iter.hasNext()) {
Entry<byte[],byte[]> e = iter.next();
count++;
}
long tEnd = System.currentTimeMillis();
double dur = (tEnd-tStart);
String output = String.format(" thread #%3d: iterating over %d keys took %.4f seconds\n\n",id,count,dur/1000.0);
throughput = ((double)count)/(dur/1000.0);
System.out.print(output);
}
public void performLookups() throws BabuDBException, InterruptedException {
long tStart = System.currentTimeMillis();
byte[] key = null;
int hits = 0;
for (int i = 0; i < numKeys; i++) {
key = createRandomKey();
byte[] value = database.getDatabaseManager().getDatabase(dbName).lookup(0, key, null).get();
if (value != null)
hits++;
}
long tEnd = System.currentTimeMillis();
double dur = (tEnd-tStart);
String output = String.format(" thread #%3d: lookup of %d keys took %.4f seconds\n",id,numKeys,dur/1000.0);
output += String.format(" thread #%3d: = %10.4f s/key\n",id,(dur/1000.0)/((double)numKeys));
output += String.format(" thread #%3d: = %10.4f keys/s\n",id,((double)numKeys)/(dur/1000.0));
output += String.format(" thread #%3d: hit-rate %6.2f%%\n\n",id,(hits*100.0)/(double)numKeys);
throughput = ((double)numKeys)/(dur/1000.0);
System.out.print(output);
}
public void performDirectLookups() throws BabuDBException, InterruptedException {
long tStart = System.currentTimeMillis();
byte[] key = null;
int hits = 0;
for (int i = 0; i < numKeys; i++) {
key = createRandomKey();
byte[] value = database.getDatabaseManager().getDatabase(dbName).lookup(0, key, null).get();
if (value != null)
hits++;
}
long tEnd = System.currentTimeMillis();
double dur = (tEnd-tStart);
String output = String.format(" thread #%3d: direct lookup of %d keys took %.4f seconds\n",id,numKeys,dur/1000.0);
output += String.format(" thread #%3d: = %10.4f s/key\n",id,(dur/1000.0)/((double)numKeys));
output += String.format(" thread #%3d: = %10.4f keys/s\n",id,((double)numKeys)/(dur/1000.0));
output += String.format(" thread #%3d: hit-rate %6.2f%%\n\n",id,(hits*100.0)/(double)numKeys);
throughput = ((double)numKeys)/(dur/1000.0);
System.out.print(output);
}
public void performUserDefinedLookups() throws BabuDBException, InterruptedException {
long tStart = System.currentTimeMillis();
int hits = 0;
for (int i = 0; i < numKeys; i++) {
final byte[] key = createRandomKey();
byte[] value = (byte[]) database.getDatabaseManager().getDatabase(dbName).userDefinedLookup(new UserDefinedLookup() {
public Object execute(LSMLookupInterface database) throws BabuDBException {
byte[] result = null;
for (int i = 0; i < 20; i++)
result = database.lookup(0, key);
return result;
}
},null).get();
if (value != null)
hits++;
}
long tEnd = System.currentTimeMillis();
double dur = (tEnd-tStart);
String output = String.format(" thread #%3d: exec of %d UDLs took %.4f seconds\n",id,numKeys,dur/1000.0);
output += String.format(" thread #%3d: = %10.4f s/UDL\n",id,(dur/1000.0)/((double)numKeys));
output += String.format(" thread #%3d: = %10.4f UDLs/s\n",id,((double)numKeys)/(dur/1000.0));
output += String.format(" thread #%3d: hit-rate %6.2f%%\n\n",id,(hits*100.0)/(double)numKeys);
throughput = ((double)numKeys)/(dur/1000.0);
System.out.print(output);
}
byte[] createRandomKey() {
return createRandomKey(random.nextDouble(),random.nextDouble());
}
private byte[] createRandomKey(double randLength,double randVal) {
final int length = (int) (randLength * ((double)(maxKeyLength - minKeyLength)) + minKeyLength);
assert(length >= minKeyLength);
assert(length <= maxKeyLength);
byte[] key = new byte[length];
for (int i = 0; i < length; i++)
key[i] = BabuDBBenchmark.CHARS[(int)(randVal*(BabuDBBenchmark.CHARS.length-1))];
return key;
}
}
| caraboides/babuDB | src/org/xtreemfs/babudb/sandbox/BenchmarkWorkerThread.java | Java | bsd-3-clause | 8,541 |
package org.basex.http.auth;
import static org.basex.query.func.Function.*;
import static org.junit.Assert.*;
import java.io.*;
import org.basex.core.*;
import org.basex.http.*;
import org.basex.query.*;
import org.basex.util.*;
import org.junit.*;
/**
* HTTP authentication tests.
*
* @author BaseX Team 2005-20, BSD License
* @author Christian Gruen
*/
public abstract class AuthTest extends HTTPTest {
/** Local database context. */
private static Context ctx;
/** Authentication method. */
protected static String method;
/**
* Initializes the test.
* @param meth method
* @throws Exception exception
*/
protected static void init(final String meth) throws Exception {
Prop.put(StaticOptions.AUTHMETHOD, meth);
method = meth;
init(REST_ROOT, true, true);
ctx = new Context();
}
/**
* Stops the test.
*/
@AfterClass public static void close() {
Prop.clear();
ctx.close();
}
/**
* Successful request.
* @throws Exception Exception
*/
@Test public void sendRequestOk() throws Exception {
assertEquals("200", sendRequest("admin", "admin"));
}
/**
* Failed request.
* @throws Exception Exception
*/
@Test public void sendRequestFail() throws Exception {
assertEquals("401", sendRequest("unknown", "wrong"));
}
/**
* Calls the specified URL and checks the error message.
* @param url URL
* @param error expected error, or {@code null} if no error is expected
*/
protected static void test(final String url, final String error) {
try {
final String request = request(url, "", "GET");
if(error != null) fail("Error expected:\n" + request);
} catch(final IOException ex) {
if(error == null) fail("No error expected:\n" + ex);
assertEquals(error, ex.getMessage());
}
}
/**
* Tests authentication.
* @param user user
* @param pass password
* @return code
* @throws Exception Exception
*/
private static String sendRequest(final String user, final String pass) throws Exception {
try(QueryProcessor qp = new QueryProcessor(_HTTP_SEND_REQUEST.args(
" <http:request xmlns:http='http://expath.org/ns/http-client' method='GET' " +
"auth-method='" + method + "' username='" + user + "' password='" + pass + "' " +
"send-authorization='true' href='" + REST_ROOT + "'/>") +
"[. instance of node()]/@status/string()", ctx)) {
return qp.value().serialize().toString();
}
}
}
| dimitarp/basex | basex-api/src/test/java/org/basex/http/auth/AuthTest.java | Java | bsd-3-clause | 2,497 |
package gov.nih.nci.security.acegi;
import org.acegisecurity.AccessDeniedException;
import org.acegisecurity.AfterInvocationManager;
import org.acegisecurity.Authentication;
import org.acegisecurity.ConfigAttribute;
import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.afterinvocation.AfterInvocationProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
*
* Custom AfterInvocationProviderManager for CSM.
*
* Additional property 'securityMap' has been added to hold the SecurityMap obtained from SecurityHelperImpl by SDK.
*
* Provider-based implementation of {@link AfterInvocationManager}.<p>Handles configuration of a bean context
* defined list of {@link AfterInvocationProvider}s.</p>
* <p>Every <code>AfterInvocationProvider</code> will be polled when the {@link #decide(Authentication, Object,
* ConfigAttributeDefinition, Object)} method is called. The <code>Object</code> returned from each provider will be
* presented to the successive provider for processing. This means each provider <b>must</b> ensure they return the
* <code>Object</code>, even if they are not interested in the "after invocation" decision (perhaps as the secure
* object invocation did not include a configuration attribute a given provider is configured to respond to).</p>
*
* @author parmarv
*/
public class CSMAfterInvocationProviderManager implements AfterInvocationManager, InitializingBean {
//~ Static fields/initializers =====================================================================================
protected static final Log logger = LogFactory.getLog(CSMAfterInvocationProviderManager.class);
//~ Instance fields ================================================================================================
/**
* Note: added SecurityMap attribute.
*/
private Map<String,Collection<String>> securityMap;
private List providers;
//~ Methods ========================================================================================================
public void afterPropertiesSet() throws Exception {
checkIfValidList(this.providers);
}
private void checkIfValidList(List listToCheck) {
if ((listToCheck == null) || (listToCheck.size() == 0)) {
throw new IllegalArgumentException("A list of AfterInvocationProviders is required");
}
}
public Object decide(Authentication authentication, Object object, ConfigAttributeDefinition config,
Object returnedObject) throws AccessDeniedException {
Iterator iter = this.providers.iterator();
Object result = returnedObject;
while (iter.hasNext()) {
AfterInvocationProvider provider = (AfterInvocationProvider) iter.next();
result = provider.decide(authentication, object, config, result);
}
return result;
}
public List getProviders() {
return this.providers;
}
public void setProviders(List newList) {
checkIfValidList(newList);
Iterator iter = newList.iterator();
while (iter.hasNext()) {
Object currentObject = null;
try {
currentObject = iter.next();
AfterInvocationProvider attemptToCast = (AfterInvocationProvider) currentObject;
} catch (ClassCastException cce) {
throw new IllegalArgumentException("AfterInvocationProvider " + currentObject.getClass().getName()
+ " must implement AfterInvocationProvider");
}
}
this.providers = newList;
}
public boolean supports(ConfigAttribute attribute) {
Iterator iter = this.providers.iterator();
while (iter.hasNext()) {
AfterInvocationProvider provider = (AfterInvocationProvider) iter.next();
if (logger.isDebugEnabled()) {
logger.debug("Evaluating " + attribute + " against " + provider);
}
if (provider.supports(attribute)) {
return true;
}
}
return false;
}
/**
* Iterates through all <code>AfterInvocationProvider</code>s and ensures each can support the presented
* class.<p>If one or more providers cannot support the presented class, <code>false</code> is returned.</p>
*
* @param clazz the secure object class being queries
*
* @return if the <code>AfterInvocationProviderManager</code> can support the secure object class, which requires
* every one of its <code>AfterInvocationProvider</code>s to support the secure object class
*/
public boolean supports(Class clazz) {
Iterator iter = this.providers.iterator();
while (iter.hasNext()) {
AfterInvocationProvider provider = (AfterInvocationProvider) iter.next();
if (!provider.supports(clazz)) {
return false;
}
}
return true;
}
public Map<String, Collection<String>> getSecurityMap() {
return securityMap;
}
public void setSecurityMap(Map<String, Collection<String>> securityMap) {
this.securityMap = securityMap;
}
}
| NCIP/cagrid | cagrid/Software/general/external/csmapi-42/api/src/gov/nih/nci/security/acegi/CSMAfterInvocationProviderManager.java | Java | bsd-3-clause | 5,393 |
/*
* $Id:
*/
/*
Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.medknow;
import java.io.*;
import org.lockss.daemon.PluginException;
import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.util.urlconn.CacheException;
public class TestMedknowLoginPageChecker extends LockssTestCase {
public void testNotLoginPage() throws IOException {
MedknowLoginPageChecker checker = new MedknowLoginPageChecker();
try {
assertFalse(checker.isLoginPage(new CIProperties(),
new MyStringReader("blah")));
} catch (PluginException e) {
}
}
public static String downloadPageText =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" +
"<html><head>" +
"<!-- TAG START-->" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">" +
"<title>Article Title of One Sort : Download PDF</title>" +
"<meta name=\"DC.Title\" content=\"Indian J Crit Care Med\">" +
"<meta name=\"DC.Publisher.CorporateName\" content=\"Medknow Publications\">" +
"<meta name=\"DC.Publisher.CorporateName.Address\" content=\"Mumbai, India\"> " +
"<meta name=\"DC.Date\" content=\"1990\">" +
"<meta name=\"DC.Format\" content=\"text/html\">" +
"<meta name=\"DC.Type\" content=\"text.serial.Journal\">" +
"<meta name=\"DC.Language\" content=\"(SCHEME=ISO639) en\"><!-- TAG START-->" +
"" +
"" +
"</head>" +
"<body class=\"dbody\">" +
"There is stuff here" +
"</body>" +
"</html>";
public static String altDownloadPageText =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" +
"<html><head>" +
"<!-- TAG START-->" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">" +
"<title>Article Title of One Sort : Download PDFs</title>" +
"<meta name=\"DC.Title\" content=\"Indian J Crit Care Med\">" +
"<meta name=\"DC.Publisher.CorporateName\" content=\"Medknow Publications\">" +
"<meta name=\"DC.Publisher.CorporateName.Address\" content=\"Mumbai, India\"> " +
"<meta name=\"DC.Date\" content=\"1990\">" +
"<meta name=\"DC.Format\" content=\"text/html\">" +
"<meta name=\"DC.Type\" content=\"text.serial.Journal\">" +
"<meta name=\"DC.Language\" content=\"(SCHEME=ISO639) en\"><!-- TAG START-->" +
"" +
"" +
"</head>" +
"<body class=\"dbody\">" +
"There is stuff here" +
"</body>" +
"</html>";
public static String notDownloadPageText =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">" +
"<html><head>" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">" +
"<title>And article title - goes" +
"here but isn't a : download button page" +
" </title>" +
"</head>" +
"" +
"<body class=\"dbody\">" +
"not a download page" +
"</body>" +
"</html>";
public void testIsLoginPage() throws IOException {
MedknowLoginPageChecker checker = new MedknowLoginPageChecker();
CIProperties props = new CIProperties();
props.put("Content-Type", "text/html; charset=windows-1252");
MyStringReader reader = new MyStringReader(downloadPageText);
try {
// old return value would be true, which would result in fatal error
assertTrue(checker.isLoginPage(props, reader));
} catch (CacheException e) {
assertClass(CacheException.UnexpectedNoRetryFailException.class, e);
} catch (PluginException e) {
}
}
public void testAltIsLoginPage() throws IOException {
MedknowLoginPageChecker checker = new MedknowLoginPageChecker();
CIProperties props = new CIProperties();
props.put("Content-Type", "text/html; charset=windows-1252");
MyStringReader reader = new MyStringReader(altDownloadPageText);
try {
assertTrue(checker.isLoginPage(props, reader));
} catch (CacheException e) {
assertClass(CacheException.UnexpectedNoRetryFailException.class, e);
} catch (PluginException e) {
}
}
public void testIsNotLoginPage() throws IOException {
MedknowLoginPageChecker checker = new MedknowLoginPageChecker();
CIProperties props = new CIProperties();
props.put("Content-Type", "text/html; charset=windows-1252");
MyStringReader reader = new MyStringReader(notDownloadPageText);
try {
assertFalse(checker.isLoginPage(props, reader));
} catch (PluginException e) {
}
}
private static class MyStringReader extends StringReader {
boolean readCalled = false;
public MyStringReader(String str) {
super(str);
}
public int read(char[] cbuf, int off, int len) throws IOException {
readCalled = true;
return super.read(cbuf, off, len);
}
}
}
| lockss/lockss-daemon | plugins/test/src/org/lockss/plugin/medknow/TestMedknowLoginPageChecker.java | Java | bsd-3-clause | 6,754 |
/**
* Package with input/output related classes.
* @author Alex
*/
package com.alexrnl.commons.io; | AlexRNL/Commons | src/main/java/com/alexrnl/commons/io/package-info.java | Java | bsd-3-clause | 101 |
/**
*
*
* @author WILEDION
*/
package kani.state;
import java.io.IOException;
import kani.data.AnimManager;
import kani.data.ImgManager;
import kani.data.MapManager;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.loading.DeferredResource;
import org.newdawn.slick.loading.LoadingList;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class LoadState extends BasicGameState {
int stateID = -1;
ImgManager imgmanager;
MapManager mapmanager;
AnimManager animmanager;
DeferredResource nextResource;
boolean started;
public LoadState( int stateID ) {
this.stateID = stateID;
imgmanager = ImgManager.get();
mapmanager = MapManager.get();
animmanager = AnimManager.get();
}
public int getID() {
return stateID;
}
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
LoadingList.setDeferredLoading(true);
imgmanager.load();
mapmanager.load();
animmanager.load();
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics gr) throws SlickException {
if (nextResource != null) {
gr.drawString("Loading: "+nextResource.getDescription(), 100, 100);
}
int total = LoadingList.get().getTotalResources();
int loaded = LoadingList.get().getTotalResources() - LoadingList.get().getRemainingResources();
float bar = loaded / (float) total;
gr.fillRect(100,550,loaded*40,20);
gr.drawRect(100,550,total*40,20);
if (started) {
gr.drawString("LOADING COMPLETE",100,550);
sbg.enterState(1);
}
}
public void update(GameContainer gc, StateBasedGame sbg, int delta) throws SlickException {
if (nextResource != null) {
try {
nextResource.load();
// slow down loading for example purposes
try { Thread.sleep(50); } catch (Exception e) {}
} catch (IOException e) {
throw new SlickException("Failed to load: "+nextResource.getDescription(), e);
}
nextResource = null;
}
if (LoadingList.get().getRemainingResources() > 0) {
nextResource = LoadingList.get().getNext();
} else {
if (!started) {
started = true;
}
}
}
}
| wiledion/Kani | src/kani/state/LoadState.java | Java | bsd-3-clause | 2,509 |
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.team3182.main;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class MainRobot extends IterativeRobot {
// create attributes for joysticks
private Joystick _leftDriveJoystick;
private Joystick _rightDriveJoystick;
private Joystick _buttonsJoystick;
// create attribute for drivetrain
private RobotDrive _driveTrain;
// create attributes for auxiliary motors
private Jaguar _upperShooterMotor;
private Jaguar _lowerShooterMotor;
private Jaguar _loaderMotor;
private Jaguar _collectorMotor;
private Jaguar _turretMotor;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
_leftDriveJoystick = new Joystick(1); // Joystick 1
_rightDriveJoystick = new Joystick(2); // Joystick 2
_buttonsJoystick = new Joystick(3); // Joystick 3
_driveTrain = new RobotDrive(1, 2); // PWM 1, 2
_driveTrain.setSafetyEnabled(false);
_upperShooterMotor = new Jaguar(5); // PWM 5
_lowerShooterMotor = new Jaguar(6); // PWM 6
_loaderMotor = new Jaguar(9); // PWM 9
_collectorMotor = new Jaguar(7); // PWM 7
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
// drive the robot directly from the joysticks
_driveTrain.tankDrive(_leftDriveJoystick, _rightDriveJoystick);
// pull useful information from the buttons joystick
double shooterSpeed = _buttonsJoystick.getThrottle();
boolean shootBall = _buttonsJoystick.getTrigger();
boolean loadBall = _buttonsJoystick.getRawButton(2);
// if the driver requests a ball to fire and is not also trying to
// load a ball
if (shootBall && !loadBall) {
// set the speed of the shooter to the same as the throttle
//_upperShooterMotor.set(shooterSpeed);
//_lowerShooterMotor.set(shooterSpeed);
// set the speed of the shooter to a reasonable value that a little
// kid can catch... :)
_upperShooterMotor.set(-.52);
_lowerShooterMotor.set(-.52);
// run the collector belts
_collectorMotor.set(-1);
} else {
// all stop
_upperShooterMotor.set(0);
_lowerShooterMotor.set(0);
}
// if the driver requests loading a ball and is not also trying to
// fire
if (loadBall && !shootBall) {
// run the collector belts and the loadfer motor so the ball
// doesn't enter the shoot wheels
_collectorMotor.set(-1);
_loaderMotor.set(1);
} else {
// stop the loader motor
_loaderMotor.set(0);
}
// stop the collector motor only if not shooting
if (!shootBall) {
_collectorMotor.set(0);
}
}
}
| FRCTeam3182/FRC2012 | src/edu/team3182/main/MainRobot.java | Java | bsd-3-clause | 4,456 |
// SPDX-License-Identifier: BSD-3-Clause
// -*- Java -*-
//
// Copyright (c) 2005, Matthew J. Rutherford <[email protected]>
// Copyright (c) 2005, University of Colorado at Boulder
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// * Neither the name of the University of Colorado at Boulder nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
package org.xbill.DNS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;
class MFRecordTest {
@Test
void ctor_0arg() {
MFRecord d = new MFRecord();
assertNull(d.getName());
assertNull(d.getAdditionalName());
assertNull(d.getMailAgent());
}
@Test
void ctor_4arg() throws TextParseException {
Name n = Name.fromString("my.name.");
Name a = Name.fromString("my.alias.");
MFRecord d = new MFRecord(n, DClass.IN, 0xABCDEL, a);
assertEquals(n, d.getName());
assertEquals(Type.MF, d.getType());
assertEquals(DClass.IN, d.getDClass());
assertEquals(0xABCDEL, d.getTTL());
assertEquals(a, d.getAdditionalName());
assertEquals(a, d.getMailAgent());
}
}
| dnsjava/dnsjava | src/test/java/org/xbill/DNS/MFRecordTest.java | Java | bsd-3-clause | 2,566 |
package net.machinemuse.powersuits.powermodule.energy;
import net.machinemuse.api.IModularItem;
import net.machinemuse.api.electricity.ElectricConversions;
import net.machinemuse.powersuits.item.ItemComponent;
import net.machinemuse.powersuits.powermodule.PowerModuleBase;
import net.machinemuse.utils.ElectricItemUtils;
import net.machinemuse.utils.MuseCommonStrings;
import net.machinemuse.utils.MuseItemUtils;
import net.minecraft.util.StatCollector;
import java.util.List;
public class EliteBatteryModule extends PowerModuleBase {
public static final String MODULE_BATTERY_ELITE = "Elite Battery";
public EliteBatteryModule(List<IModularItem> validItems) {
super(validItems);
addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.hvcapacitor, 1));
addBaseProperty(ElectricItemUtils.MAXIMUM_ENERGY(), 750000, "J");
addBaseProperty(MuseCommonStrings.WEIGHT, 2000, "g");
addTradeoffProperty("Battery Size", ElectricItemUtils.MAXIMUM_ENERGY(), 4250000);
addTradeoffProperty("Battery Size", MuseCommonStrings.WEIGHT, 8000);
addBaseProperty(ElectricConversions.IC2_TIER(), 1);
addTradeoffProperty("IC2 Tier", ElectricConversions.IC2_TIER(), 2);
}
@Override
public String getTextureFile() {
return "crystalcapacitor";
}
@Override
public String getCategory() {
return MuseCommonStrings.CATEGORY_ENERGY;
}
@Override
public String getDataName() {
return MODULE_BATTERY_ELITE;
}
@Override
public String getLocalizedName() {
return StatCollector.translateToLocal("module.eliteBattery.name");
}
@Override
public String getDescription() {
return StatCollector.translateToLocal("module.eliteBattery.desc");
}
}
| QMXTech/MachineMusePowersuits | src/main/scala/net/machinemuse/powersuits/powermodule/energy/EliteBatteryModule.java | Java | bsd-3-clause | 1,788 |
package com.sjl.dsl4xml.sax;
import org.xml.sax.*;
public class DocHandler<R> implements Handler<R> {
private TagHandler<R> root;
public DocHandler(TagHandler<R> aRoot) {
root = aRoot;
}
@Override
public Handler<?> startTag(String aQName, Attributes anAttributes, Context aCtx) {
if (root.handlesTag(aQName)) {
return root.moveDown(aQName, anAttributes, aCtx);
} else {
throw new InvalidStateException("unexpected root element: " + aQName);
}
}
@Override
public Handler<?> moveUp(String aQName, Context aCtx) {
return root;
}
@Override
public Handler<?> characters(char[] aChars, int aStart, int aLength, Context aContext) {
return root.characters(aChars, aStart, aLength, aContext);
}
}
| steveliles/dsl4xml | xml/sax/src/main/java/com/sjl/dsl4xml/sax/DocHandler.java | Java | bsd-3-clause | 731 |
package edu.ucdenver.ccp.datasource.fileparsers.ncbi.gene;
/*
* #%L
* Colorado Computational Pharmacology's common module
* %%
* Copyright (C) 2012 - 2015 Regents of the University of Colorado
* %%
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the Regents of the University of Colorado nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import org.apache.log4j.Logger;
import edu.ucdenver.ccp.common.file.reader.Line;
import edu.ucdenver.ccp.datasource.fileparsers.CcpExtensionOntology;
import edu.ucdenver.ccp.datasource.fileparsers.License;
import edu.ucdenver.ccp.datasource.fileparsers.Record;
import edu.ucdenver.ccp.datasource.fileparsers.RecordField;
import edu.ucdenver.ccp.datasource.fileparsers.SingleLineFileRecord;
import edu.ucdenver.ccp.datasource.identifiers.DataSource;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.RefSeqID;
import edu.ucdenver.ccp.datasource.identifiers.impl.bio.UniProtID;
/**
* Representation of data from the EntrezGene gene2pubmed file.
*
* @author Bill Baumgartner
*
*/
@Record(ontClass = CcpExtensionOntology.NCBI_GENE_REFSEQ_UNIPROTKB_COLLABORATION_RECORD, dataSource = DataSource.NCBI_GENE,
comment="",
license=License.NCBI,
citation="The NCBI handbook [Internet]. Bethesda (MD): National Library of Medicine (US), National Center for Biotechnology Information; 2002 Oct. Chapter 19 Gene: A Directory of Genes. Available from http://www.ncbi.nlm.nih.gov/books/NBK21091",
label="refseq/uniprot mapping record")
public class NcbiGeneRefSeqUniprotKbCollabFileData extends SingleLineFileRecord {
public static final String RECORD_NAME_PREFIX = "REFSEQ_UNI_COLLAB_";
private static final Logger logger = Logger.getLogger(NcbiGeneRefSeqUniprotKbCollabFileData.class);
@RecordField(ontClass = CcpExtensionOntology.NCBI_GENE_REFSEQ_UNIPROTKB_COLLABORATION_RECORD___REFSEQ_PROTEIN_IDENTIFIER_FIELD_VALUE)
private final RefSeqID refSeqProteinId;
@RecordField(ontClass = CcpExtensionOntology.NCBI_GENE_REFSEQ_UNIPROTKB_COLLABORATION_RECORD___UNIPROT_IDENTIFIER_FIELD_VALUE)
private final UniProtID uniprotId;
public NcbiGeneRefSeqUniprotKbCollabFileData(RefSeqID refseqProteinId, UniProtID uniprotId, long byteOffset,
long lineNumber) {
super(byteOffset, lineNumber);
this.refSeqProteinId = refseqProteinId;
this.uniprotId = uniprotId;
}
/**
* @return the refSeqProteinId
*/
public RefSeqID getRefSeqProteinId() {
return refSeqProteinId;
}
/**
* @return the uniprotId
*/
public UniProtID getUniprotId() {
return uniprotId;
}
public static NcbiGeneRefSeqUniprotKbCollabFileData parseGeneRefseqUniprotKbCollabLine(Line line) {
String[] toks = line.getText().split("\\t");
if (toks.length == 2) {
RefSeqID refseqId = new RefSeqID(toks[0]);
UniProtID uniprotId = new UniProtID(toks[1]);
return new NcbiGeneRefSeqUniprotKbCollabFileData(refseqId, uniprotId, line.getByteOffset(),
line.getLineNumber());
}
logger.error("Unexpected number of tokens (" + toks.length + ") on line: " + line.toString());
return null;
}
}
| UCDenver-ccp/datasource | datasource-fileparsers/src/main/java/edu/ucdenver/ccp/datasource/fileparsers/ncbi/gene/NcbiGeneRefSeqUniprotKbCollabFileData.java | Java | bsd-3-clause | 4,450 |
package com.crunchbase.app.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Image {
protected static class Fields {
public static final String AVAILABLE_SIZES = "available_sizes";
public static final String ATTRIBUTION = "attribution";
}
@SerializedName(Fields.AVAILABLE_SIZES)
private List<ImageSize> mAvailableSizes;
@SerializedName(Fields.ATTRIBUTION)
private String mAttribution;
public String getLastImageUrl() {
if (mAvailableSizes != null && mAvailableSizes.size() > 0) {
return mAvailableSizes.get(mAvailableSizes.size() - 1).getUrl();
} else {
return null;
}
}
}
| cfmobile/arca-android-samples | CrunchBase/app/src/main/java/com/crunchbase/app/models/Image.java | Java | bsd-3-clause | 710 |
package gen.model.test.converters;
import java.io.*;
import java.util.*;
import java.util.stream.*;
import org.revenj.postgres.*;
import org.revenj.postgres.converters.*;
public class Detail2Converter implements ObjectConverter<gen.model.test.Detail2> {
@SuppressWarnings("unchecked")
public Detail2Converter(List<ObjectConverter.ColumnInfo> allColumns) throws java.io.IOException {
Optional<ObjectConverter.ColumnInfo> column;
final java.util.List<ObjectConverter.ColumnInfo> columns =
allColumns.stream().filter(it -> "test".equals(it.typeSchema) && "Detail2_entity".equals(it.typeName))
.collect(Collectors.toList());
columnCount = columns.size();
readers = new ObjectConverter.Reader[columnCount];
for (int i = 0; i < readers.length; i++) {
readers[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
}
final java.util.List<ObjectConverter.ColumnInfo> columnsExtended =
allColumns.stream().filter(it -> "test".equals(it.typeSchema) && "-ngs_Detail2_type-".equals(it.typeName))
.collect(Collectors.toList());
columnCountExtended = columnsExtended.size();
readersExtended = new ObjectConverter.Reader[columnCountExtended];
for (int i = 0; i < readersExtended.length; i++) {
readersExtended[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
}
column = columns.stream().filter(it -> "u".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'u' column in test Detail2_entity. Check if DB is in sync");
__index___u = (int)column.get().order - 1;
column = columnsExtended.stream().filter(it -> "u".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'u' column in test Detail2. Check if DB is in sync");
__index__extended_u = (int)column.get().order - 1;
column = columns.stream().filter(it -> "dd".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'dd' column in test Detail2_entity. Check if DB is in sync");
__index___dd = (int)column.get().order - 1;
column = columnsExtended.stream().filter(it -> "dd".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'dd' column in test Detail2. Check if DB is in sync");
__index__extended_dd = (int)column.get().order - 1;
column = columns.stream().filter(it -> "EntityCompositeid".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'EntityCompositeid' column in test Detail2_entity. Check if DB is in sync");
__index___EntityCompositeid = (int)column.get().order - 1;
column = columnsExtended.stream().filter(it -> "EntityCompositeid".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'EntityCompositeid' column in test Detail2. Check if DB is in sync");
__index__extended_EntityCompositeid = (int)column.get().order - 1;
column = columns.stream().filter(it -> "EntityIndex".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'EntityIndex' column in test Detail2_entity. Check if DB is in sync");
__index___EntityIndex = (int)column.get().order - 1;
column = columnsExtended.stream().filter(it -> "EntityIndex".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'EntityIndex' column in test Detail2. Check if DB is in sync");
__index__extended_EntityIndex = (int)column.get().order - 1;
column = columns.stream().filter(it -> "Index".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Index' column in test Detail2_entity. Check if DB is in sync");
__index___Index = (int)column.get().order - 1;
column = columnsExtended.stream().filter(it -> "Index".equals(it.columnName)).findAny();
if (!column.isPresent()) throw new java.io.IOException("Unable to find 'Index' column in test Detail2. Check if DB is in sync");
__index__extended_Index = (int)column.get().order - 1;
}
public void configure(org.revenj.patterns.ServiceLocator locator) {
gen.model.test.Detail2.__configureConverter(readers, __index___u, __index___dd, __index___EntityCompositeid, __index___EntityIndex, __index___Index);
gen.model.test.Detail2.__configureConverterExtended(readersExtended, __index__extended_u, __index__extended_dd, __index__extended_EntityCompositeid, __index__extended_EntityIndex, __index__extended_Index);
}
@Override
public String getDbName() {
return "\"test\".\"Detail2_entity\"";
}
@Override
public gen.model.test.Detail2 from(PostgresReader reader) throws java.io.IOException {
return from(reader, 0);
}
private gen.model.test.Detail2 from(PostgresReader reader, int outerContext, int context, ObjectConverter.Reader<gen.model.test.Detail2>[] readers) throws java.io.IOException {
reader.read(outerContext);
gen.model.test.Detail2 instance = new gen.model.test.Detail2(reader, context, readers);
reader.read(outerContext);
return instance;
}
@Override
public PostgresTuple to(gen.model.test.Detail2 instance) {
if (instance == null) return null;
PostgresTuple[] items = new PostgresTuple[columnCount];
items[__index___u] = org.revenj.postgres.converters.UrlConverter.toTuple(instance.getU());
items[__index___dd] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDd(), org.revenj.postgres.converters.DoubleConverter::toTuple);
items[__index___EntityCompositeid] = org.revenj.postgres.converters.UuidConverter.toTuple(instance.getEntityCompositeid());
items[__index___EntityIndex] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getEntityIndex());
items[__index___Index] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getIndex());
return RecordTuple.from(items);
}
private final int columnCount;
private final ObjectConverter.Reader<gen.model.test.Detail2>[] readers;
public gen.model.test.Detail2 from(PostgresReader reader, int context) throws java.io.IOException {
int cur = reader.read();
if (cur == ',' || cur == ')') return null;
gen.model.test.Detail2 instance = from(reader, context, context == 0 ? 1 : context << 1, readers);
reader.read();
return instance;
}
public gen.model.test.Detail2 from(PostgresReader reader, int outerContext, int context) throws java.io.IOException {
return from(reader, outerContext, context, readers);
}
public PostgresTuple toExtended(gen.model.test.Detail2 instance) {
if (instance == null) return null;
PostgresTuple[] items = new PostgresTuple[columnCountExtended];
items[__index__extended_u] = org.revenj.postgres.converters.UrlConverter.toTuple(instance.getU());
items[__index__extended_dd] = org.revenj.postgres.converters.ArrayTuple.create(instance.getDd(), org.revenj.postgres.converters.DoubleConverter::toTuple);
items[__index__extended_EntityCompositeid] = org.revenj.postgres.converters.UuidConverter.toTuple(instance.getEntityCompositeid());
items[__index__extended_EntityIndex] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getEntityIndex());
items[__index__extended_Index] = org.revenj.postgres.converters.IntConverter.toTuple(instance.getIndex());
return RecordTuple.from(items);
}
private final int columnCountExtended;
private final ObjectConverter.Reader<gen.model.test.Detail2>[] readersExtended;
public gen.model.test.Detail2 fromExtended(PostgresReader reader, int context) throws java.io.IOException {
int cur = reader.read();
if (cur == ',' || cur == ')') return null;
gen.model.test.Detail2 instance = from(reader, context, context == 0 ? 1 : context << 1, readersExtended);
reader.read();
return instance;
}
public gen.model.test.Detail2 fromExtended(PostgresReader reader, int outerContext, int context) throws java.io.IOException {
return from(reader, outerContext, context, readersExtended);
}
private final int __index___u;
private final int __index__extended_u;
private final int __index___dd;
private final int __index__extended_dd;
private final int __index___EntityCompositeid;
private final int __index__extended_EntityCompositeid;
private final int __index___EntityIndex;
private final int __index__extended_EntityIndex;
private final int __index___Index;
private final int __index__extended_Index;
public static String buildURI(org.revenj.postgres.PostgresBuffer _sw, gen.model.test.Detail2 instance) throws java.io.IOException {
_sw.initBuffer();
String _tmp;
org.revenj.postgres.converters.UuidConverter.serializeURI(_sw, instance.getEntityCompositeid());
_sw.addToBuffer('/');org.revenj.postgres.converters.IntConverter.serializeURI(_sw, instance.getEntityIndex());
_sw.addToBuffer('/');org.revenj.postgres.converters.IntConverter.serializeURI(_sw, instance.getIndex());
return _sw.bufferToString();
}
}
| tferega/revenj | java/revenj-test/src/test/java/gen/model/test/converters/Detail2Converter.java | Java | bsd-3-clause | 9,185 |
package org.hisp.dhis.dataelement;
/*
* Copyright (c) 2004-2018, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hisp.dhis.category.Category;
import org.hisp.dhis.category.CategoryCombo;
import org.hisp.dhis.category.CategoryComboStore;
import org.hisp.dhis.category.CategoryOption;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.category.CategoryOptionComboStore;
import org.hisp.dhis.category.CategoryOptionGroup;
import org.hisp.dhis.category.CategoryOptionGroupSet;
import org.hisp.dhis.category.CategoryOptionGroupSetStore;
import org.hisp.dhis.category.CategoryOptionGroupStore;
import org.hisp.dhis.category.CategoryOptionStore;
import org.hisp.dhis.category.CategoryService;
import org.hisp.dhis.category.CategoryStore;
import org.hisp.dhis.common.DataDimensionType;
import org.hisp.dhis.common.IdentifiableObjectManager;
import org.hisp.dhis.common.IdentifiableProperty;
import org.hisp.dhis.dataset.DataSet;
import org.hisp.dhis.dataset.DataSetElement;
import org.hisp.dhis.security.acl.AccessStringHelper;
import org.hisp.dhis.security.acl.AclService;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserCredentials;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Abyot Asalefew
*/
@Transactional
public class DefaultCategoryService
implements CategoryService
{
private static final Log log = LogFactory.getLog( DefaultCategoryService.class );
// -------------------------------------------------------------------------
// Dependencies
// -------------------------------------------------------------------------
private CategoryStore categoryStore;
public void setCategoryStore( CategoryStore categoryStore )
{
this.categoryStore = categoryStore;
}
private CategoryOptionStore categoryOptionStore;
public void setCategoryOptionStore( CategoryOptionStore categoryOptionStore )
{
this.categoryOptionStore = categoryOptionStore;
}
private CategoryComboStore categoryComboStore;
public void setCategoryComboStore( CategoryComboStore categoryComboStore )
{
this.categoryComboStore = categoryComboStore;
}
private CategoryOptionComboStore categoryOptionComboStore;
public void setCategoryOptionComboStore( CategoryOptionComboStore categoryOptionComboStore )
{
this.categoryOptionComboStore = categoryOptionComboStore;
}
private CategoryOptionGroupStore categoryOptionGroupStore;
public void setCategoryOptionGroupStore( CategoryOptionGroupStore categoryOptionGroupStore )
{
this.categoryOptionGroupStore = categoryOptionGroupStore;
}
private CategoryOptionGroupSetStore categoryOptionGroupSetStore;
public void setCategoryOptionGroupSetStore( CategoryOptionGroupSetStore categoryOptionGroupSetStore )
{
this.categoryOptionGroupSetStore = categoryOptionGroupSetStore;
}
private IdentifiableObjectManager idObjectManager;
public void setIdObjectManager( IdentifiableObjectManager idObjectManager )
{
this.idObjectManager = idObjectManager;
}
private CurrentUserService currentUserService;
public void setCurrentUserService( CurrentUserService currentUserService )
{
this.currentUserService = currentUserService;
}
private AclService aclService;
public void setAclService( AclService aclService )
{
this.aclService = aclService;
}
// -------------------------------------------------------------------------
// Category
// -------------------------------------------------------------------------
@Override
public int addCategory( Category dataElementCategory )
{
categoryStore.save( dataElementCategory );
return dataElementCategory.getId();
}
@Override
public void updateCategory( Category dataElementCategory )
{
categoryStore.update( dataElementCategory );
}
@Override
public void deleteCategory( Category dataElementCategory )
{
categoryStore.delete( dataElementCategory );
}
@Override
public List<Category> getAllDataElementCategories()
{
return categoryStore.getAll();
}
@Override
public Category getCategory( int id )
{
return categoryStore.get( id );
}
@Override
public Category getCategory( String uid )
{
return categoryStore.getByUid( uid );
}
@Override
public Category getCategoryByName( String name )
{
List<Category> dataElementCategories = new ArrayList<>(
categoryStore.getAllEqName( name ) );
if ( dataElementCategories.isEmpty() )
{
return null;
}
return dataElementCategories.get( 0 );
}
@Override
public Category getDefaultCategory()
{
return getCategoryByName( Category.DEFAULT_NAME );
}
@Override
public List<Category> getDisaggregationCategories()
{
return categoryStore.getCategoriesByDimensionType( DataDimensionType.DISAGGREGATION );
}
@Override
public List<Category> getDisaggregationDataDimensionCategoriesNoAcl()
{
return categoryStore.getCategoriesNoAcl( DataDimensionType.DISAGGREGATION, true );
}
@Override
public List<Category> getAttributeCategories()
{
return categoryStore.getCategoriesByDimensionType( DataDimensionType.ATTRIBUTE );
}
@Override
public List<Category> getAttributeDataDimensionCategoriesNoAcl()
{
return categoryStore.getCategoriesNoAcl( DataDimensionType.ATTRIBUTE, true );
}
// -------------------------------------------------------------------------
// CategoryOption
// -------------------------------------------------------------------------
@Override
public int addCategoryOption( CategoryOption dataElementCategoryOption )
{
categoryOptionStore.save( dataElementCategoryOption );
return dataElementCategoryOption.getId();
}
@Override
public void updateCategoryOption( CategoryOption dataElementCategoryOption )
{
categoryOptionStore.update( dataElementCategoryOption );
}
@Override
public void deleteCategoryOption( CategoryOption dataElementCategoryOption )
{
categoryOptionStore.delete( dataElementCategoryOption );
}
@Override
public CategoryOption getCategoryOption( int id )
{
return categoryOptionStore.get( id );
}
@Override
public CategoryOption getCategoryOption( String uid )
{
return categoryOptionStore.getByUid( uid );
}
@Override
public CategoryOption getCategoryOptionByName( String name )
{
return categoryOptionStore.getByName( name );
}
@Override
public CategoryOption getDefaultCategoryOption()
{
return getCategoryOptionByName( CategoryOption.DEFAULT_NAME );
}
@Override
public List<CategoryOption> getAllCategoryOptions()
{
return categoryOptionStore.getAll();
}
@Override
public List<CategoryOption> getCategoryOptions( Category category )
{
return categoryOptionStore.getCategoryOptions( category );
}
@Override
public Set<CategoryOption> getCoDimensionConstraints( UserCredentials userCredentials )
{
Set<CategoryOption> options = null;
Set<Category> catConstraints = userCredentials.getCatDimensionConstraints();
if ( catConstraints != null && !catConstraints.isEmpty() )
{
options = new HashSet<>();
for ( Category category : catConstraints )
{
options.addAll( getCategoryOptions( category ) );
}
}
return options;
}
// -------------------------------------------------------------------------
// CategoryCombo
// -------------------------------------------------------------------------
@Override
public int addCategoryCombo( CategoryCombo dataElementCategoryCombo )
{
categoryComboStore.save( dataElementCategoryCombo );
return dataElementCategoryCombo.getId();
}
@Override
public void updateCategoryCombo( CategoryCombo dataElementCategoryCombo )
{
categoryComboStore.update( dataElementCategoryCombo );
}
@Override
public void deleteCategoryCombo( CategoryCombo dataElementCategoryCombo )
{
categoryComboStore.delete( dataElementCategoryCombo );
}
@Override
public List<CategoryCombo> getAllCategoryCombos()
{
return categoryComboStore.getAll();
}
@Override
public CategoryCombo getCategoryCombo( int id )
{
return categoryComboStore.get( id );
}
@Override
public CategoryCombo getCategoryCombo( String uid )
{
return categoryComboStore.getByUid( uid );
}
@Override
public CategoryCombo getCategoryComboByName( String name )
{
return categoryComboStore.getByName( name );
}
@Override
public CategoryCombo getDefaultCategoryCombo()
{
return getCategoryComboByName( CategoryCombo.DEFAULT_CATEGORY_COMBO_NAME );
}
@Override
public List<CategoryCombo> getDisaggregationCategoryCombos()
{
return categoryComboStore.getCategoryCombosByDimensionType( DataDimensionType.DISAGGREGATION );
}
@Override
public List<CategoryCombo> getAttributeCategoryCombos()
{
return categoryComboStore.getCategoryCombosByDimensionType( DataDimensionType.ATTRIBUTE );
}
@Override
public String validateCategoryCombo( CategoryCombo categoryCombo )
{
if ( categoryCombo == null )
{
return "category_combo_is_null";
}
if ( categoryCombo.getCategories() == null || categoryCombo.getCategories().isEmpty() )
{
return "category_combo_must_have_at_least_one_category";
}
if ( Sets.newHashSet( categoryCombo.getCategories() ).size() < categoryCombo.getCategories().size() )
{
return "category_combo_cannot_have_duplicate_categories";
}
Set<CategoryOption> categoryOptions = new HashSet<CategoryOption>();
for ( Category category : categoryCombo.getCategories() )
{
if ( category == null || category.getCategoryOptions().isEmpty() )
{
return "categories_must_have_at_least_one_category_option";
}
if ( !Sets.intersection( categoryOptions, Sets.newHashSet( category.getCategoryOptions() ) ).isEmpty() )
{
return "categories_cannot_share_category_options";
}
}
return null;
}
// -------------------------------------------------------------------------
// CategoryOptionCombo
// -------------------------------------------------------------------------
@Override
public int addCategoryOptionCombo( CategoryOptionCombo dataElementCategoryOptionCombo )
{
categoryOptionComboStore.save( dataElementCategoryOptionCombo );
return dataElementCategoryOptionCombo.getId();
}
@Override
public void updateCategoryOptionCombo( CategoryOptionCombo dataElementCategoryOptionCombo )
{
categoryOptionComboStore.update( dataElementCategoryOptionCombo );
}
@Override
public void deleteCategoryOptionCombo( CategoryOptionCombo dataElementCategoryOptionCombo )
{
categoryOptionComboStore.delete( dataElementCategoryOptionCombo );
}
@Override
public CategoryOptionCombo getCategoryOptionCombo( int id )
{
return categoryOptionComboStore.get( id );
}
@Override
public CategoryOptionCombo getCategoryOptionCombo( String uid )
{
return categoryOptionComboStore.getByUid( uid );
}
@Override
public CategoryOptionCombo getCategoryOptionComboByCode( String code )
{
return categoryOptionComboStore.getByCode( code );
}
@Override
public CategoryOptionCombo getCategoryOptionCombo( CategoryCombo categoryCombo,
Set<CategoryOption> categoryOptions )
{
return categoryOptionComboStore.getCategoryOptionCombo( categoryCombo, categoryOptions );
}
@Override
public List<CategoryOptionCombo> getAllCategoryOptionCombos()
{
return categoryOptionComboStore.getAll();
}
@Override
public void generateDefaultDimension()
{
// ---------------------------------------------------------------------
// CategoryOption
// ---------------------------------------------------------------------
CategoryOption categoryOption = new CategoryOption( CategoryOption.DEFAULT_NAME );
categoryOption.setUid( "xYerKDKCefk" );
categoryOption.setCode( "default" );
addCategoryOption( categoryOption );
categoryOption.setPublicAccess( AccessStringHelper.CATEGORY_OPTION_DEFAULT );
updateCategoryOption( categoryOption );
// ---------------------------------------------------------------------
// Category
// ---------------------------------------------------------------------
Category category = new Category( Category.DEFAULT_NAME, DataDimensionType.DISAGGREGATION );
category.setUid( "GLevLNI9wkl" );
category.setCode( "default" );
category.setDataDimension( false );
category.addCategoryOption( categoryOption );
addCategory( category );
category.setPublicAccess( AccessStringHelper.CATEGORY_NO_DATA_SHARING_DEFAULT );
updateCategory( category );
// ---------------------------------------------------------------------
// CategoryCombo
// ---------------------------------------------------------------------
CategoryCombo categoryCombo = new CategoryCombo( CategoryCombo.DEFAULT_CATEGORY_COMBO_NAME, DataDimensionType.DISAGGREGATION );
categoryCombo.setUid( "bjDvmb4bfuf" );
categoryCombo.setCode( "default" );
categoryCombo.setDataDimensionType( DataDimensionType.DISAGGREGATION );
categoryCombo.addCategory( category );
addCategoryCombo( categoryCombo );
categoryCombo.setPublicAccess( AccessStringHelper.CATEGORY_NO_DATA_SHARING_DEFAULT );
updateCategoryCombo( categoryCombo );
// ---------------------------------------------------------------------
// CategoryOptionCombo
// ---------------------------------------------------------------------
CategoryOptionCombo categoryOptionCombo = new CategoryOptionCombo();
categoryOptionCombo.setUid( "HllvX50cXC0" );
categoryOptionCombo.setCode( "default" );
categoryOptionCombo.setCategoryCombo( categoryCombo );
categoryOptionCombo.addCategoryOption( categoryOption );
addCategoryOptionCombo( categoryOptionCombo );
categoryOptionCombo.setPublicAccess( AccessStringHelper.CATEGORY_NO_DATA_SHARING_DEFAULT );
updateCategoryOptionCombo( categoryOptionCombo );
Set<CategoryOptionCombo> categoryOptionCombos = new HashSet<>();
categoryOptionCombos.add( categoryOptionCombo );
categoryCombo.setOptionCombos( categoryOptionCombos );
updateCategoryCombo( categoryCombo );
categoryOption.setCategoryOptionCombos( categoryOptionCombos );
updateCategoryOption( categoryOption );
}
@Override
public CategoryOptionCombo getDefaultCategoryOptionCombo()
{
CategoryCombo categoryCombo = getCategoryComboByName( CategoryCombo.DEFAULT_CATEGORY_COMBO_NAME );
return categoryCombo != null && categoryCombo.hasOptionCombos() ? categoryCombo.getOptionCombos().iterator().next() : null;
}
@Override
public void generateOptionCombos( CategoryCombo categoryCombo )
{
categoryCombo.generateOptionCombos();
for ( CategoryOptionCombo optionCombo : categoryCombo.getOptionCombos() )
{
categoryCombo.getOptionCombos().add( optionCombo );
addCategoryOptionCombo( optionCombo );
}
updateCategoryCombo( categoryCombo );
}
@Override
public void updateOptionCombos( Category category )
{
for ( CategoryCombo categoryCombo : getAllCategoryCombos() )
{
if ( categoryCombo.getCategories().contains( category ) )
{
updateOptionCombos( categoryCombo );
}
}
}
@Override
public void updateOptionCombos( CategoryCombo categoryCombo )
{
if ( categoryCombo == null || !categoryCombo.isValid() )
{
log.warn( "Category combo is null or invalid, could not update option combos: " + categoryCombo );
return;
}
List<CategoryOptionCombo> generatedOptionCombos = categoryCombo.generateOptionCombosList();
Set<CategoryOptionCombo> persistedOptionCombos = categoryCombo.getOptionCombos();
boolean modified = false;
for ( CategoryOptionCombo optionCombo : generatedOptionCombos )
{
if ( !persistedOptionCombos.contains( optionCombo ) )
{
categoryCombo.getOptionCombos().add( optionCombo );
addCategoryOptionCombo( optionCombo );
log.info( "Added missing category option combo: " + optionCombo + " for category combo: "
+ categoryCombo.getName() );
modified = true;
}
}
if ( modified )
{
updateCategoryCombo( categoryCombo );
}
}
@Override
public CategoryOptionCombo getCategoryOptionComboAcl( IdentifiableProperty property, String id )
{
CategoryOptionCombo coc = idObjectManager.getObject( CategoryOptionCombo.class, property, id );
if ( coc != null )
{
User user = currentUserService.getCurrentUser();
for ( CategoryOption categoryOption : coc.getCategoryOptions() )
{
if ( !aclService.canDataWrite( user, categoryOption ) )
{
return null;
}
}
}
return coc;
}
@Override
public void updateCategoryOptionComboNames()
{
categoryOptionComboStore.updateNames();
}
// -------------------------------------------------------------------------
// DataElementOperand
// -------------------------------------------------------------------------
@Override
public List<DataElementOperand> getOperands( Collection<DataElement> dataElements )
{
return getOperands( dataElements, false );
}
@Override
public List<DataElementOperand> getOperands( Collection<DataElement> dataElements, boolean includeTotals )
{
List<DataElementOperand> operands = Lists.newArrayList();
for ( DataElement dataElement : dataElements )
{
Set<CategoryCombo> categoryCombos = dataElement.getCategoryCombos();
boolean anyIsDefault = categoryCombos.stream().anyMatch( cc -> cc.isDefault() );
if ( includeTotals && !anyIsDefault )
{
operands.add( new DataElementOperand( dataElement ) );
}
for ( CategoryCombo categoryCombo : categoryCombos )
{
operands.addAll( getOperands( dataElement, categoryCombo ) );
}
}
return operands;
}
@Override
public List<DataElementOperand> getOperands( DataSet dataSet, boolean includeTotals )
{
List<DataElementOperand> operands = Lists.newArrayList();
for ( DataSetElement element : dataSet.getDataSetElements() )
{
CategoryCombo categoryCombo = element.getResolvedCategoryCombo();
if ( includeTotals && !categoryCombo.isDefault() )
{
operands.add( new DataElementOperand( element.getDataElement() ) );
}
operands.addAll( getOperands( element.getDataElement(), element.getResolvedCategoryCombo() ) );
}
return operands;
}
private List<DataElementOperand> getOperands( DataElement dataElement, CategoryCombo categoryCombo )
{
List<DataElementOperand> operands = Lists.newArrayList();
for ( CategoryOptionCombo categoryOptionCombo : categoryCombo.getSortedOptionCombos() )
{
operands.add( new DataElementOperand( dataElement, categoryOptionCombo ) );
}
return operands;
}
// -------------------------------------------------------------------------
// CategoryOptionGroup
// -------------------------------------------------------------------------
@Override
public int saveCategoryOptionGroup( CategoryOptionGroup group )
{
categoryOptionGroupStore.save( group );
return group.getId();
}
@Override
public void updateCategoryOptionGroup( CategoryOptionGroup group )
{
categoryOptionGroupStore.update( group );
}
@Override
public CategoryOptionGroup getCategoryOptionGroup( int id )
{
return categoryOptionGroupStore.get( id );
}
@Override
public CategoryOptionGroup getCategoryOptionGroup( String uid )
{
return categoryOptionGroupStore.getByUid( uid );
}
@Override
public void deleteCategoryOptionGroup( CategoryOptionGroup group )
{
categoryOptionGroupStore.delete( group );
}
@Override
public List<CategoryOptionGroup> getAllCategoryOptionGroups()
{
return categoryOptionGroupStore.getAll();
}
@Override
public List<CategoryOptionGroup> getCategoryOptionGroups( CategoryOptionGroupSet groupSet )
{
return categoryOptionGroupStore.getCategoryOptionGroups( groupSet );
}
@Override
public Set<CategoryOptionGroup> getCogDimensionConstraints( UserCredentials userCredentials )
{
Set<CategoryOptionGroup> groups = null;
Set<CategoryOptionGroupSet> cogsConstraints = userCredentials.getCogsDimensionConstraints();
if ( cogsConstraints != null && !cogsConstraints.isEmpty() )
{
groups = new HashSet<>();
for ( CategoryOptionGroupSet cogs : cogsConstraints )
{
groups.addAll( getCategoryOptionGroups( cogs ) );
}
}
return groups;
}
// -------------------------------------------------------------------------
// CategoryOptionGroupSet
// -------------------------------------------------------------------------
@Override
public int saveCategoryOptionGroupSet( CategoryOptionGroupSet group )
{
categoryOptionGroupSetStore.save( group );
return group.getId();
}
@Override
public void updateCategoryOptionGroupSet( CategoryOptionGroupSet group )
{
categoryOptionGroupSetStore.update( group );
}
@Override
public CategoryOptionGroupSet getCategoryOptionGroupSet( int id )
{
return categoryOptionGroupSetStore.get( id );
}
@Override
public CategoryOptionGroupSet getCategoryOptionGroupSet( String uid )
{
return categoryOptionGroupSetStore.getByUid( uid );
}
@Override
public void deleteCategoryOptionGroupSet( CategoryOptionGroupSet group )
{
categoryOptionGroupSetStore.delete( group );
}
@Override
public List<CategoryOptionGroupSet> getAllCategoryOptionGroupSets()
{
return categoryOptionGroupSetStore.getAll();
}
@Override
public List<CategoryOptionGroupSet> getDisaggregationCategoryOptionGroupSetsNoAcl()
{
return categoryOptionGroupSetStore.getCategoryOptionGroupSetsNoAcl( DataDimensionType.DISAGGREGATION, true );
}
@Override
public List<CategoryOptionGroupSet> getAttributeCategoryOptionGroupSetsNoAcl()
{
return categoryOptionGroupSetStore.getCategoryOptionGroupSetsNoAcl( DataDimensionType.ATTRIBUTE, true );
}
}
| vietnguyen/dhis2-core | dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/dataelement/DefaultCategoryService.java | Java | bsd-3-clause | 26,872 |
package com.ra4king.opengl.superbible.osb4.chapter3;
import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.Display;
import com.ra4king.opengl.GLProgram;
public class Example3_7 extends GLProgram {
public static void main(String[] args) {
new Example3_7().run();
}
public Example3_7() {
super("LSTIPPLE", 800, 600, true);
}
private float xRot, yRot;
public void init() {
glClearColor(0, 0, 0, 1);
glColor3f(0, 1, 0);
glEnable(GL_LINE_STIPPLE);
}
public void update(long deltaTime) {
if(Keyboard.isKeyDown(Keyboard.KEY_LEFT))
xRot += 5;
if(Keyboard.isKeyDown(Keyboard.KEY_RIGHT))
xRot -= 5;
if(Keyboard.isKeyDown(Keyboard.KEY_DOWN))
yRot -= 5;
if(Keyboard.isKeyDown(Keyboard.KEY_UP))
yRot += 5;
if(Keyboard.isKeyDown(Keyboard.KEY_R))
xRot = yRot = 0;
}
public void render() {
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glRotatef(yRot, 1, 0, 0);
glRotatef(xRot, 0, 1, 0);
for(int y = -90, factor = 0; y <= 90; y += 20, factor++) {
glLineStipple(factor, (short)0x5555);
glBegin(GL_LINES);
glVertex2f(-80, y);
glVertex2f(80, y);
glEnd();
}
glPopMatrix();
}
public void resized() {
int w = Display.getWidth(), h = Display.getHeight();
if(h == 0)
h = 1;
glViewport(0, 0, Display.getWidth(), Display.getHeight());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
float aspect = (float)w / h;
if(w <= h)
glOrtho(-100, 100, -100 / aspect, 100 / aspect, 100, -100);
else
glOrtho(-100 * aspect, 100 * aspect, -100, 100, 100, -100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
}
| ra4king/LWJGL-OpenGL-Tutorials | src/com/ra4king/opengl/superbible/osb4/chapter3/Example3_7.java | Java | bsd-3-clause | 1,762 |
package com.madgnome.stash.plugins.buccaneer.rest;
import com.atlassian.stash.repository.Repository;
import com.atlassian.stash.repository.RepositoryService;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.madgnome.stash.plugins.buccaneer.model.Tag;
import com.madgnome.stash.plugins.buccaneer.model.Tags;
import com.madgnome.stash.plugins.buccaneer.model.TagsRepository;
import com.madgnome.stash.plugins.buccaneer.rest.data.RestTag;
import com.madgnome.stash.plugins.buccaneer.rest.data.RestTags;
import com.sun.jersey.spi.resource.Singleton;
import javax.annotation.Nullable;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;
@Path("/tags")
@Singleton
@Produces({MediaType.APPLICATION_JSON + ";charset=UTF-8"})
public class TagResource
{
private final TagsRepository tagsRepository;
private final RepositoryService repositoryService;
public TagResource(TagsRepository tagsRepository, RepositoryService repositoryService)
{
this.tagsRepository = tagsRepository;
this.repositoryService = repositoryService;
}
@GET
@Produces({MediaType.APPLICATION_JSON})
public Response getTag(@QueryParam("projectKey") String projectKey, @QueryParam("slug") String slug, @QueryParam("path") String filePath, @QueryParam("type") String type)
{
final Repository repository = repositoryService.findRepositoryBySlug("PROJECT_1", "rep_1");
final Tags tags = tagsRepository.getTags(repository);
final List<Tag> symbolTags = tags.getTags(type);
final List<RestTag> restSymbolTags = Lists.transform(symbolTags, new Function<Tag, RestTag>()
{
@Override
public RestTag apply(@Nullable Tag tag)
{
return new RestTag(tag.getSymbol(), tag.getPath(), tag.getLineNumber(), tag.getExcerpt());
}
});
final RestTags restTags = new RestTags(type, restSymbolTags);
return Response.ok(restTags).build ();
}
}
| madgnome/Buccaneer | src/main/java/com/madgnome/stash/plugins/buccaneer/rest/TagResource.java | Java | bsd-3-clause | 2,067 |
package com.petuum.ps.oplog;
import com.google.common.util.concurrent.Striped;
import com.petuum.ps.thread.GlobalContext;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by ZengJichuan on 2014/8/28.
*/
public class PartitionOpLogIndex {
private ReadWriteLock sharedLock;
private Striped<Lock> locks;
private HashMap<Integer, Boolean> sharedOpLogIndex;
public PartitionOpLogIndex(){
sharedLock = new ReentrantReadWriteLock();
locks = Striped.lock(GlobalContext.getLockPoolSize());
sharedOpLogIndex = new HashMap<Integer, Boolean>();
}
public void addIndex(Set<Integer> opLogIndex){
try {
sharedLock.readLock().lock();
for (int index : opLogIndex) {
Lock lock = locks.get(index);
try {
lock.lock();
sharedOpLogIndex.put(index, true);
} finally {
lock.unlock();
}
}
}finally {
sharedLock.readLock().unlock();
}
}
public HashMap<Integer, Boolean> reset() {
HashMap<Integer, Boolean> oldIndex;
try {
sharedLock.writeLock().lock();
oldIndex = sharedOpLogIndex;
sharedOpLogIndex = new HashMap<Integer, Boolean>();
}finally {
sharedLock.writeLock().unlock();
}
return oldIndex;
}
}
| zengjichuan/jetuum | src/main/java/com/petuum/ps/oplog/PartitionOpLogIndex.java | Java | bsd-3-clause | 1,644 |
// RobotBuilder Version: 2.0
//
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc5933.Rosieppbs.commands;
import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc5933.Rosieppbs.Robot;
import org.usfirst.frc5933.Rosieppbs.subsystems.BallLauncher;
/**
*
*/
public class StartMediumFlyWheel extends Command {
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_DECLARATIONS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
public StartMediumFlyWheel() {
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=VARIABLE_SETTING
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
requires(Robot.ballLauncher);
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=REQUIRES
}
// Called just before this Command runs the first time
protected void initialize() {
Robot.ballLauncher.resetFlyWheelManualAdjustment();
Robot.ballLauncher.set(BallLauncher.FlyWheelSpeed.MEDIUM);
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
Robot.ballLauncher.set(BallLauncher.FlyWheelSpeed.MEDIUM);
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
| jmchs-robotics/Rosieppbs | src/org/usfirst/frc5933/Rosieppbs/commands/StartMediumFlyWheel.java | Java | bsd-3-clause | 2,137 |
package abi42_0_0.host.exp.exponent.modules.api.components.picker;
import com.facebook.infer.annotation.Assertions;
import abi42_0_0.com.facebook.react.uimanager.LayoutShadowNode;
public class ReactPickerShadowNode extends LayoutShadowNode {
@Override
public void setLocalData(Object data) {
Assertions.assertCondition(data instanceof ReactPickerLocalData);
setStyleMinHeight(((ReactPickerLocalData) data).getHeight());
}
}
| exponentjs/exponent | android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/picker/ReactPickerShadowNode.java | Java | bsd-3-clause | 454 |
/*
* Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the United States Government nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package gov.hhs.fha.nhinc.unsubscribe.entity;
import java.util.List;
import javax.xml.xpath.XPathExpressionException;
import oasis.names.tc.xacml._2_0.context.schema.os.DecisionType;
import org.apache.log4j.Logger;
import org.oasis_open.docs.wsn.b_2.UnableToDestroySubscriptionFaultType;
import org.oasis_open.docs.wsn.b_2.Unsubscribe;
import org.oasis_open.docs.wsn.b_2.UnsubscribeResponse;
import org.oasis_open.docs.wsn.bw_2.UnableToDestroySubscriptionFault;
import org.oasis_open.docs.wsrf.rw_2.ResourceUnknownFault;
import gov.hhs.fha.nhinc.auditrepository.AuditRepositoryLogger;
import gov.hhs.fha.nhinc.auditrepository.nhinc.proxy.AuditRepositoryProxy;
import gov.hhs.fha.nhinc.auditrepository.nhinc.proxy.AuditRepositoryProxyObjectFactory;
import gov.hhs.fha.nhinc.common.auditlog.LogEventRequestType;
import gov.hhs.fha.nhinc.common.eventcommon.UnsubscribeEventType;
import gov.hhs.fha.nhinc.common.eventcommon.UnsubscribeMessageType;
import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetCommunityType;
import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.CheckPolicyRequestType;
import gov.hhs.fha.nhinc.common.nhinccommonadapter.CheckPolicyResponseType;
import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements;
import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper;
import gov.hhs.fha.nhinc.hiem.dte.TargetBuilder;
import gov.hhs.fha.nhinc.hiem.processor.faults.SubscriptionManagerSoapFaultFactory;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.nhinclib.NullChecker;
import gov.hhs.fha.nhinc.policyengine.PolicyEngineChecker;
import gov.hhs.fha.nhinc.policyengine.adapter.proxy.PolicyEngineProxy;
import gov.hhs.fha.nhinc.policyengine.adapter.proxy.PolicyEngineProxyObjectFactory;
import gov.hhs.fha.nhinc.subscription.repository.data.HiemSubscriptionItem;
import gov.hhs.fha.nhinc.subscription.repository.service.HiemSubscriptionRepositoryService;
import gov.hhs.fha.nhinc.subscription.repository.service.SubscriptionRepositoryException;
public class EntityUnsubscribeOrchImpl {
private static final Logger LOG = Logger.getLogger(EntityUnsubscribeOrchImpl.class);
/**
* This method performs the entity orchestration for an unsubscribe at the entity.
* @param unsubscribe - This request
* @param assertion - The assertion of the message
* @param targetCommunitites - The target of the request
* @return a subscription response of success or fail
* @throws Exception
* @throws UnableToDestroySubscriptionFault
*/
public UnsubscribeResponse processUnsubscribe(Unsubscribe unsubscribe,
String subscriptionId, AssertionType assertion)
throws UnableToDestroySubscriptionFault, Exception {
UnsubscribeResponse response = null;
auditRequestFromAdapter(unsubscribe, assertion);
// retrieve by consumer reference
HiemSubscriptionRepositoryService repo = new HiemSubscriptionRepositoryService();
HiemSubscriptionItem subscriptionItem = null;
try {
LOG.debug("lookup subscription by reference parameters");
subscriptionItem = repo.retrieveBySubscriptionId(subscriptionId);
LOG.debug("subscriptionItem isnull? = " + (subscriptionItem == null));
} catch (SubscriptionRepositoryException ex) {
LOG.error(ex);
throw new SubscriptionManagerSoapFaultFactory().getErrorDuringSubscriptionRetrieveFault(ex);
}
if (subscriptionItem == null) {
throw new SubscriptionManagerSoapFaultFactory().getUnableToFindSubscriptionFault();
}
// todo: if has parent, retrieve parent, forward unsubscribe to agency
List<HiemSubscriptionItem> childSubscriptions = null;
try {
LOG.debug("checking to see if subscription has child subscription");
childSubscriptions = repo.retrieveByParentSubscriptionReference(subscriptionItem
.getSubscriptionReferenceXML());
LOG.debug("childSubscriptions isnull? = " + (childSubscriptions == null));
} catch (SubscriptionRepositoryException ex) {
LOG.warn("failed to check for child subscription", ex);
}
if (NullChecker.isNotNullish(childSubscriptions)) {
LOG.debug("send unsubscribe(s) to child [" + childSubscriptions.size() + "]");
for (HiemSubscriptionItem childSubscription : childSubscriptions) {
LOG.debug("sending unsubscribe to child");
response = unsubscribeToChild(unsubscribe, childSubscription, assertion, subscriptionId);
}
}
// "remove" from local repo
LOG.debug("invoking subscription storage service to delete subscription");
try {
repo.deleteSubscription(subscriptionItem);
} catch (SubscriptionRepositoryException ex) {
LOG.error("unable to delete subscription. This should result in a unable to remove subscription fault", ex);
throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex);
}
auditResponseToAdapter(response, assertion);
return response;
}
private UnsubscribeResponse unsubscribeToChild(Unsubscribe parentUnsubscribe, HiemSubscriptionItem childSubscriptionItem,
AssertionType parentAssertion, String subscriptionId) throws UnableToDestroySubscriptionFault, ResourceUnknownFault, Exception {
UnsubscribeResponse response = null;
try {
LOG.debug("unsubscribing to child subscription");
LOG.debug("building target");
NhinTargetSystemType target;
target = new TargetBuilder().buildSubscriptionManagerTarget(childSubscriptionItem
.getSubscriptionReferenceXML());
LOG.debug("target url = " + target.getUrl());
if (NullChecker.isNullish(target.getUrl())) {
throw new UnableToDestroySubscriptionFault(
"Unable to determine where to send the unsubscribe for the child subscription",
new UnableToDestroySubscriptionFaultType());
}
ReferenceParametersHelper referenceParametersHelper = new ReferenceParametersHelper();
SoapMessageElements referenceParametersElements = referenceParametersHelper
.createReferenceParameterElementsFromSubscriptionReference(childSubscriptionItem
.getSubscriptionReferenceXML());
LOG.debug("extracted " + referenceParametersElements.getElements().size() + " element(s)");
response = getResponseFromTarget(parentUnsubscribe,referenceParametersElements,
parentAssertion, target,childSubscriptionItem.getStorageObject().getSubscriptionId());
HiemSubscriptionRepositoryService repo = new HiemSubscriptionRepositoryService();
repo.deleteSubscription(childSubscriptionItem);
} catch (SubscriptionRepositoryException ex) {
LOG.error("failed to remove child subscription for repository");
throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex);
} catch (XPathExpressionException ex) {
LOG.error("failed to parse subscription reference");
throw new SubscriptionManagerSoapFaultFactory().getFailedToRemoveSubscriptionFault(ex);
}
return response;
}
private UnsubscribeResponse createFailedPolicyCheckResponse() {
// TODO Auto-generated method stub
return null;
}
/**
* Audit the request from the adapter.
* @param request The request to be audited
* @param assertion The assertion to be audited
*/
private void auditRequestFromAdapter(Unsubscribe unsubscribe,
AssertionType assertion) {
LOG.debug("In EntitysubscribeOrchImpl.auditInputMessage");
try {
AuditRepositoryLogger auditLogger = new AuditRepositoryLogger();
gov.hhs.fha.nhinc.common.nhinccommoninternalorch.UnsubscribeRequestType message = new gov.hhs.fha.nhinc.common.nhinccommoninternalorch.UnsubscribeRequestType();
message.setAssertion(assertion);
message.setUnsubscribe(unsubscribe);
LogEventRequestType auditLogMsg = auditLogger.logNhinUnsubscribeRequest(message,
NhincConstants.AUDIT_LOG_INBOUND_DIRECTION, NhincConstants.AUDIT_LOG_ENTITY_INTERFACE);
if (auditLogMsg != null) {
AuditRepositoryProxyObjectFactory auditRepoFactory = new AuditRepositoryProxyObjectFactory();
AuditRepositoryProxy proxy = auditRepoFactory.getAuditRepositoryProxy();
proxy.auditLog(auditLogMsg, assertion);
}
} catch (Throwable t) {
LOG.error("Error logging subscribe message: " + t.getMessage(), t);
}
}
/**
* Audit the request to the adapter.
* @param response The response to be audited
* @param assertion The assertion to be audited
*/
private void auditResponseToAdapter(UnsubscribeResponse response, AssertionType assertion) {
LOG.debug("In EntitysubscribeOrchImpl.auditResponseMessage");
try {
AuditRepositoryLogger auditLogger = new AuditRepositoryLogger();
gov.hhs.fha.nhinc.common.hiemauditlog.UnsubscribeResponseMessageType message = new gov.hhs.fha.nhinc.common.hiemauditlog.UnsubscribeResponseMessageType();
message.setAssertion(assertion);
message.setUnsubscribeResponse(response);
LogEventRequestType auditLogMsg = auditLogger.logUnsubscribeResponse(message,
NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_ENTITY_INTERFACE);
if (auditLogMsg != null) {
AuditRepositoryProxyObjectFactory auditRepoFactory = new AuditRepositoryProxyObjectFactory();
AuditRepositoryProxy proxy = auditRepoFactory.getAuditRepositoryProxy();
proxy.auditLog(auditLogMsg, assertion);
}
} catch (Throwable t) {
LOG.error("Error logging subscribe response message: " + t.getMessage(), t);
}
}
/**
* Send subscription response to target.
* @param request The subscribe to send.
* @param assertion The assertion to send
* @param targetCommunitites The targets to be sent to
* @return the response from the foreign entity
*/
private UnsubscribeResponse getResponseFromTarget(
Unsubscribe request, SoapMessageElements referenceParameters,
AssertionType assertion, NhinTargetSystemType targetSystem, String subscriptionId) {
UnsubscribeResponse nhinResponse = new UnsubscribeResponse();
if(isPolicyValid(request, assertion)){
LOG.info("Policy check successful");
//send request to nhin proxy
try {
nhinResponse = sendToNhinProxy(request, referenceParameters, assertion, targetSystem,subscriptionId );
} catch (Exception e) {
//TODO nhinResponse = createFailedNhinSendResponse(hcid);
String hcid = targetSystem.getHomeCommunity().getHomeCommunityId();
LOG.error("Fault encountered while trying to send message to the nhin " + hcid, e);
}
} else {
LOG.error("Failed policy check. Sending error response.");
nhinResponse = createFailedPolicyCheckResponse();
}
return nhinResponse;
}
private UnsubscribeResponse sendToNhinProxy(
Unsubscribe request, SoapMessageElements referenceParameters,
AssertionType assertion, NhinTargetSystemType nhinTargetSystem, String subscriptionId) {
OutboundUnsubscribeDelegate dsDelegate = getOutboundUnsubscribeDelegate();
OutboundUnsubscribeOrchestratable dsOrchestratable = createOrchestratable(dsDelegate, request,
referenceParameters, assertion, nhinTargetSystem, subscriptionId);
UnsubscribeResponse response = ((OutboundUnsubscribeOrchestratable) dsDelegate
.process(dsOrchestratable)).getResponse();
return response;
}
protected OutboundUnsubscribeDelegate getOutboundUnsubscribeDelegate() {
return new OutboundUnsubscribeDelegate();
}
private OutboundUnsubscribeOrchestratable createOrchestratable(
OutboundUnsubscribeDelegate delegate, Unsubscribe request,
SoapMessageElements referenceParameters, AssertionType assertion,
NhinTargetSystemType nhinTargetSystem, String subscriptionId) {
OutboundUnsubscribeOrchestratable dsOrchestratable = new OutboundUnsubscribeOrchestratable(delegate);
dsOrchestratable.setAssertion(assertion);
dsOrchestratable.setRequest(request);
dsOrchestratable.setReferenceParameters(referenceParameters);
dsOrchestratable.setTarget(nhinTargetSystem);
dsOrchestratable.setSubscriptionId(subscriptionId);
return dsOrchestratable;
}
/**
* Check if policy for message is valid.
* @param subscribe The message to be checked.
* @param assertion The assertion to be checked.
* @return
*/
private boolean isPolicyValid(Unsubscribe unsubscribe,
AssertionType assertion) {
LOG.debug("In NhinHiemSubscribeWebServiceProxy.checkPolicy");
boolean policyIsValid = false;
UnsubscribeEventType policyCheckReq = new UnsubscribeEventType();
policyCheckReq.setDirection(NhincConstants.POLICYENGINE_OUTBOUND_DIRECTION);
UnsubscribeMessageType request = new UnsubscribeMessageType();
request.setAssertion(assertion);
request.setUnsubscribe(unsubscribe);
policyCheckReq.setMessage(request);
PolicyEngineChecker policyChecker = new PolicyEngineChecker();
CheckPolicyRequestType policyReq = policyChecker.checkPolicyUnsubscribe(policyCheckReq);
policyReq.setAssertion(assertion);
PolicyEngineProxyObjectFactory policyEngFactory = new PolicyEngineProxyObjectFactory();
PolicyEngineProxy policyProxy = policyEngFactory.getPolicyEngineProxy();
CheckPolicyResponseType policyResp = policyProxy.checkPolicy(policyReq, assertion);
if (policyResp.getResponse() != null && NullChecker.isNotNullish(policyResp.getResponse().getResult())
&& policyResp.getResponse().getResult().get(0).getDecision() == DecisionType.PERMIT) {
policyIsValid = true;
}
LOG.debug("Finished NhinHiemUnsubscribeWebServiceProxy.checkPolicy - valid: " + policyIsValid);
return policyIsValid;
}
/**
* Check if there is a valid target to send the request to.
* @param targetCommunities The communities object to check for targets
* @return true if there is a valid target
*/
protected boolean hasNhinTargetHomeCommunityId(
NhinTargetCommunityType targetCommunity) {
if (targetCommunity != null
&& targetCommunity.getHomeCommunity() != null
&& NullChecker.isNotNullish(targetCommunity.getHomeCommunity().getHomeCommunityId())) {
return true;
}
return false;
}
}
| sailajaa/CONNECT | Product/Production/Services/HIEMCore/src/main/java/gov/hhs/fha/nhinc/unsubscribe/entity/EntityUnsubscribeOrchImpl.java | Java | bsd-3-clause | 17,205 |
/*
* Copyright (c) 2015-2016 William Bittle http://www.praisenter.org/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Praisenter nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.praisenter.data.bible;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.praisenter.data.DataFormatProvider;
import org.praisenter.data.DataReadResult;
import org.praisenter.data.InvalidFormatException;
import org.praisenter.utility.MimeType;
import org.praisenter.utility.Streams;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* A bible importer for the OpenSong bible format.
* @author William Bittle
* @version 3.0.0
* @since 3.0.0
*/
final class OpenSongBibleFormatProvider implements DataFormatProvider<Bible> {
/** The class level-logger */
private static final Logger LOGGER = LogManager.getLogger();
/** The source */
private static final String SOURCE = "OpenSong (http://www.opensong.org/)";
@Override
public boolean isSupported(Path path) {
try (Reader reader = new BufferedReader(new FileReader(path.toFile()))) {
XMLInputFactory f = XMLInputFactory.newInstance();
// prevent XXE attacks
// https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XMLInputFactory_.28a_StAX_parser.29
f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
XMLStreamReader r = f.createXMLStreamReader(reader);
while(r.hasNext()) {
r.next();
if (r.isStartElement()) {
if (r.getLocalName().equalsIgnoreCase("bible")) {
return true;
}
}
}
} catch (Exception ex) {
LOGGER.trace("Failed to read the path as an XML document.", ex);
}
return false;
}
@Override
public boolean isSupported(String mimeType) {
return MimeType.XML.is(mimeType) || mimeType.toLowerCase().startsWith("text");
}
@Override
public boolean isSupported(String resourceName, InputStream stream) {
try {
XMLInputFactory f = XMLInputFactory.newInstance();
// prevent XXE attacks
// https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#XMLInputFactory_.28a_StAX_parser.29
f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
XMLStreamReader r = f.createXMLStreamReader(stream);
while(r.hasNext()) {
r.next();
if (r.isStartElement()) {
if (r.getLocalName().equalsIgnoreCase("bible")) {
return true;
}
}
}
} catch (Exception ex) {
LOGGER.trace("Failed to read the input stream as an XML document.", ex);
}
return false;
}
@Override
public List<DataReadResult<Bible>> read(Path path) throws IOException {
try (FileInputStream stream = new FileInputStream(path.toFile())) {
return this.read(path.getFileName().toString(), stream);
}
}
@Override
public List<DataReadResult<Bible>> read(String resourceName, InputStream stream) throws IOException {
String name = resourceName;
int i = resourceName.lastIndexOf('.');
if (i >= 0) {
name = resourceName.substring(0, i);
}
List<DataReadResult<Bible>> results = new ArrayList<>();
try {
results.add(this.parse(stream, name));
} catch (SAXException | ParserConfigurationException ex) {
throw new InvalidFormatException(ex);
}
return results;
}
@Override
public void write(OutputStream stream, Bible bible) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void write(Path path, Bible bible) throws IOException {
throw new UnsupportedOperationException();
}
/**
* Attempts to parse the given input stream into the internal bible format.
* @param stream the input stream
* @param name the name
* @throws IOException if an IO error occurs
* @throws InvalidFormatException if the stream was not in the expected format
* @return {@link Bible}
* @throws SAXException
* @throws ParserConfigurationException
*/
private DataReadResult<Bible> parse(InputStream stream, String name) throws ParserConfigurationException, SAXException, IOException {
byte[] content = Streams.read(stream);
// read the bytes
SAXParserFactory factory = SAXParserFactory.newInstance();
// prevent XXE attacks
// https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
SAXParser parser = factory.newSAXParser();
OpenSongHandler handler = new OpenSongHandler(name);
parser.parse(new ByteArrayInputStream(content), handler);
return new DataReadResult<Bible>(handler.getBible(), handler.warnings);
}
/**
* A SAX parser handler for the OpenSong Bible format.
* @author William Bittle
* @version 3.0.0
* @since 3.0.0
*/
private final class OpenSongHandler extends DefaultHandler {
// imported data
/** The bible */
private Bible bible;
// temp data
/** The current book */
private Book book;
/** The book number */
private int bookNumber;
/** The current chapter */
private Chapter chapter;
/** The chapter number */
private int chapterNumber;
/** The verse number */
private int number;
/** The verse range */
private int verseTo;
/** Buffer for tag contents */
private StringBuilder dataBuilder;
private List<String> warnings;
/**
* Full constructor.
* @param name the bible name
*/
public OpenSongHandler(String name) {
this.bible = new Bible();
this.bible.setName(name);
this.bible.setSource(SOURCE);
this.bookNumber = 1;
this.chapterNumber = 1;
this.number = 1;
this.warnings = new ArrayList<>();
}
/**
* Returns the bible.
* @return {@link Bible}
*/
public Bible getBible() {
return this.bible;
}
/* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// inspect the tag name
if (qName.equalsIgnoreCase("bible")) {
// get the name if present
String name = attributes.getValue("n");
if (name != null) {
this.bible.setName(name.trim());
}
} else if (qName.equalsIgnoreCase("b")) {
book = new Book(bookNumber, attributes.getValue("n"));
this.bible.getBooks().add(book);
bookNumber++;
} else if (qName.equalsIgnoreCase("c")) {
String number = attributes.getValue("n");
try {
this.chapterNumber = Short.parseShort(number);
} catch (NumberFormatException ex) {
LOGGER.warn("Failed to parse chapter number '" + number + "' for '" + this.book.getName() + "' in '" + this.bible.getName() + "'. Using next chapter number in sequence instead.");
this.chapterNumber++;
}
this.chapter = new Chapter(this.chapterNumber);
this.book.getChapters().add(this.chapter);
this.number = 0;
} else if (qName.equalsIgnoreCase("v")) {
this.verseTo = -1;
String number = attributes.getValue("n");
String to = attributes.getValue("t");
try {
this.number = Short.parseShort(number);
} catch (NumberFormatException ex) {
LOGGER.warn("Failed to parse verse number '" + number + "' for '" + this.book.getName() + "' chatper '" + this.chapter.getNumber() + "' in '" + this.bible.getName() + "'. Using next verse number in sequence instead.");
this.number++;
}
if (to != null) {
try {
this.verseTo = Short.parseShort(to);
} catch (NumberFormatException ex) {
LOGGER.warn("Failed to parse the to verse number '" + to + "' for '" + this.bible.getName() + "'. Skipping.");
}
}
}
}
/* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// this method can be called a number of times for the contents of a tag
// this is done to improve performance so we need to append the text before
// using it
String s = new String(ch, start, length);
if (this.dataBuilder == null) {
this.dataBuilder = new StringBuilder();
}
this.dataBuilder.append(s);
}
/* (non-Javadoc)
* @see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("v".equalsIgnoreCase(qName)) {
// check for embedded verses (n="1" t="4") ...why oh why...
if (this.verseTo > 0 && this.verseTo > this.number) {
String warning = "The bible '" + this.bible.getName() + "' included a verse that is a collection of verses with a range of " + this.number + " to " + this.verseTo + ". These were imported as separate verses, all with the same text.";
this.warnings.add(warning);
LOGGER.warn(warning);
// just duplicate the verse content for each
for (int i = this.number; i <= this.verseTo; i++) {
this.chapter.getVerses().add(new Verse(i, this.dataBuilder.toString().trim()));
}
} else {
// add as normal
this.chapter.getVerses().add(new Verse(this.number, this.dataBuilder.toString().trim()));
}
}
this.dataBuilder = null;
}
}
}
| wnbittle/praisenter | src/main/java/org/praisenter/data/bible/OpenSongBibleFormatProvider.java | Java | bsd-3-clause | 11,965 |
/*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum VirtualMachineConnectionState {
connected ("connected"),
disconnected ("disconnected"),
orphaned ("orphaned"),
inaccessible ("inaccessible"),
invalid ("invalid");
@SuppressWarnings("unused")
private final String val;
private VirtualMachineConnectionState(String val)
{
this.val = val;
}
} | paksv/vijava | src/com/vmware/vim25/VirtualMachineConnectionState.java | Java | bsd-3-clause | 2,066 |
/*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.benchmark.mario.engine.level;
/**
* Created by IntelliJ IDEA.
* User: Sergey Karakovskiy, [email protected]
* Date: 4/16/11
* Time: 4:12 PM
* Package: ch.idsia.benchmark.mario.engine.level
*/
public class NewLevelGenerator implements ILevelGenerator
{
public Level generateLevel()
{
final int height = 15;
final int length = 320;
Level level = new Level(length, height);
return level;
}
public int[] giveLevelComponents()
{
return new int[0]; //To change body of implemented methods use File | Settings | File Templates.
}
public void buildLevelPart()
{
//To change body of implemented methods use File | Settings | File Templates.
}
}
| kavanj/marioai | src/ch/idsia/benchmark/mario/engine/level/NewLevelGenerator.java | Java | bsd-3-clause | 2,381 |
package com.ra4king.jdoodlejump;
import java.awt.Image;
import java.awt.geom.Rectangle2D;
import com.ra4king.gameutils.Entity;
import com.ra4king.gameutils.gameworld.GameWorld;
import com.ra4king.jdoodlejump.bars.Bar;
import com.ra4king.jdoodlejump.bars.BreakingBar;
import com.ra4king.jdoodlejump.bars.DisappearingBar;
import com.ra4king.jdoodlejump.bars.MovingBar;
import com.ra4king.jdoodlejump.bars.StationaryBar;
import com.ra4king.jdoodlejump.monsters.AlienMonster;
import com.ra4king.jdoodlejump.monsters.BlackHoleMonster;
import com.ra4king.jdoodlejump.monsters.MovingMonster;
import com.ra4king.jdoodlejump.monsters.StationaryMonster;
import com.ra4king.jdoodlejump.powerups.BigRocketPowerUp;
import com.ra4king.jdoodlejump.powerups.CopterHatPowerUp;
import com.ra4king.jdoodlejump.powerups.PowerUp;
import com.ra4king.jdoodlejump.powerups.RocketPowerUp;
import com.ra4king.jdoodlejump.powerups.ShieldPowerUp;
import com.ra4king.jdoodlejump.powerups.SpringShoesPowerUp;
public class PlatformGenerator {
private GameWorld gameWorld;
private int monsterNum = 6;
private int powerupNum = 4;
private double highestBar;
public PlatformGenerator(GameWorld gameWorld) {
this.gameWorld = gameWorld;
}
public double getHighestBar() {
return highestBar;
}
public void addToHighestBar(double value) {
highestBar += value;
}
public void setHighestBar(double highestBar) {
this.highestBar = highestBar;
}
public void reset() {
highestBar = 0;
}
public void loadWorld(Doodle doodle, int level, int extent) {
double prevHighestBar;
if(highestBar == 0) {
gameWorld.add(new StationaryBar(gameWorld.getWidth() / 2 - 25, gameWorld.getHeight() - 20));
highestBar = gameWorld.getHeight() - 20;
prevHighestBar = gameWorld.getHeight() - 20;
}
else
prevHighestBar = highestBar;
// gameWorld.add(new BlackHoleMonster(50,-100));
long time = System.currentTimeMillis();
int bar = 0;
for(int a = 0; highestBar > prevHighestBar - extent; bar++) {
double x, y;
int random = (int)Math.round(Math.random() * 100);
if(level > 0 && a < 2 && random > 90 && doodle.getVelocityY() <= doodle.getDefaultMaxVelocityY()) {
PowerUp powerup = null;
switch((int)(Math.random() * powerupNum)) {
case 0:
powerup = new CopterHatPowerUp();
break;
case 1:
powerup = new RocketPowerUp();
break;
case 2:
powerup = Themes.getThemes().getCurrentTheme() == 5 ? new BigRocketPowerUp() : new SpringShoesPowerUp();
break;
case 3:
powerup = new ShieldPowerUp();
}
x = Math.random() * (gameWorld.getWidth() - 50);
y = highestBar - (Math.random() * (level * 3) + 50);
gameWorld.add(4, powerup);
((Bar)gameWorld.add(new StationaryBar(x, y))).installPowerUp(powerup);
y -= powerup.getHeight();
a++;
}
else if((level > 3 && random > 30 && random < 50) || (level > 0 && level % 7 == 0 && level % 8 == 0 && random > 50)) {
x = (Math.random() * (gameWorld.getWidth() - 50));
y = highestBar - (Math.random() * (level * 3) + 50);
gameWorld.add(new MovingBar(x, y, x, true));
}
else {
x = Math.random() * (gameWorld.getWidth() - 50);
y = highestBar - (Math.random() * (level * 3) + 50);
double random2 = Math.random() * 100;
if(random2 > 80 && level > 2)
gameWorld.add(new DisappearingBar(x, y));
else
gameWorld.add(new StationaryBar(x, y));
}
highestBar = y;
}
long dif = System.currentTimeMillis() - time;
System.out.println((bar--) + " linear bars\t" + dif + " milliseconds");
time = System.currentTimeMillis();
double length = prevHighestBar - highestBar;
int tries = 5;
bar = 0;
for(int a = 0; a < 25 - (level / 2); a++) {
double x, y;
if(a % 10 == 0 && level > 5 && Math.random() < 0.25 && doodle.getVelocityY() <= doodle.getDefaultMaxVelocityY()) {
Image monster;
if(Math.random() * 100 > 50)
monster = gameWorld.getGame().getArt().get("blackhole");
else
monster = gameWorld.getGame().getArt().get("alien");
boolean tooclose;
int count = 0;
do {
x = Math.random() * (gameWorld.getWidth() - monster.getWidth(null));
y = prevHighestBar - (Math.random() * length);
tooclose = false;
count++;
if(count >= tries)
break;
for(Entity e : gameWorld.getEntities()) {
if(e.getBounds().intersects(new Rectangle2D.Double(x, y, monster.getWidth(null), monster.getHeight(null)))) {
tooclose = true;
break;
}
}
} while(tooclose);
if(count < tries) {
bar++;
if(monster == gameWorld.getGame().getArt().get("blackhole"))
gameWorld.add(1, new BlackHoleMonster(x, y));
else
gameWorld.add(1, new AlienMonster(x, y));
}
}
else if(a % 4 == 0 && level > 0 && doodle.getVelocityY() <= doodle.getDefaultMaxVelocityY()) {
int b = (int)(Math.random() * monsterNum) + 1;
Image monster = gameWorld.getGame().getArt().get("monster" + b);
boolean tooclose;
int count = 0;
do {
x = Math.random() * (gameWorld.getWidth() - 50);
y = prevHighestBar - (Math.random() * length);
tooclose = false;
count++;
if(count >= tries)
break;
for(Entity e : gameWorld.getEntities()) {
if(e.getBounds().intersects(new Rectangle2D.Double(x - 20, y - 10 - monster.getHeight(null), 90, 30 + monster.getHeight(null)))) {
tooclose = true;
break;
}
}
} while(tooclose);
if(count < tries) {
bar++;
StationaryMonster m = (StationaryMonster)gameWorld.add(1, new StationaryMonster(b, (int)Math.round(Math.random() * (level / 10) + 1)));
((Bar)gameWorld.add(new StationaryBar(x, y))).installMonster(m);
}
}
else if(((level > 5 && a % 3 == 0) || (level > 0 && level % 8 == 0 && level % 9 == 0 && a % 2 == 0)) && doodle.getVelocityY() <= doodle.getDefaultMaxVelocityY()) {
int b = (int)(Math.random() * monsterNum) + 1;
Image monster = gameWorld.getGame().getArt().get("monster" + b);
boolean tooclose;
int count = 0;
do {
x = Math.random() * (gameWorld.getWidth() - monster.getWidth(null));
y = prevHighestBar - (Math.random() * length);
tooclose = false;
count++;
if(count >= tries)
break;
for(Entity e : gameWorld.getEntities()) {
if(e.getBounds().intersects(new Rectangle2D.Double(0, y, gameWorld.getWidth(), monster.getHeight(null)))) {
tooclose = true;
break;
}
}
} while(tooclose);
if(count < tries) {
bar++;
gameWorld.add(1, new MovingMonster(b, x, y, (int)Math.round(Math.random() * (level / 10) + 1)));
}
}
else if((level > 3 && (a % 2 == 0 || a % 5 == 0)) || (level > 0 && level % 7 == 0 && level % 8 == 0 && (a % 2 == 0 || a % 5 == 0))) {
double startDist;
boolean tooclose;
int count = 0;
do {
x = Math.random() * (gameWorld.getWidth() - 50);
y = prevHighestBar - (Math.random() * (length - 300));
tooclose = false;
startDist = Math.random() * 400;
count++;
if(count >= tries)
break;
for(Entity e : gameWorld.getEntities()) {
if(e.getBounds().intersects(new Rectangle2D.Double(x, y - startDist, 50, 410))) {
tooclose = true;
break;
}
}
} while(tooclose);
if(count < tries) {
bar++;
gameWorld.add(new MovingBar(x, y, startDist, false));
}
}
else {
boolean tooclose;
int count = 0;
do {
x = Math.random() * (gameWorld.getWidth() - 50);
y = prevHighestBar - (Math.random() * length);
tooclose = false;
if(count >= tries)
break;
for(Entity e : gameWorld.getEntities()) {
if(e.getBounds().intersects(new Rectangle2D.Double(x - 20, y - 20, 90, 50))) {
tooclose = true;
break;
}
}
} while(tooclose);
if(count < tries) {
bar++;
double random2 = Math.random() * 100;
if(random2 > 40)
gameWorld.add(new StationaryBar(x, y));
else if(random2 > 30 && level > 2)
gameWorld.add(new DisappearingBar(x, y));
else
gameWorld.add(new BreakingBar(x, y));
}
}
}
dif = System.currentTimeMillis() - time;
System.out.println(bar + " random bars " + dif + " milliseconds");
}
}
| ra4king/JDoodle-Jump | src/com/ra4king/jdoodlejump/PlatformGenerator.java | Java | bsd-3-clause | 8,728 |
/*
* Copyright (c) 2016, SRCH2
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the SRCH2 nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SRCH2 BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.srch2.android.sdk;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class TestSearchResultsListener implements SearchResultsListener {
public int httpResponseCode;
public String jsonResultsLiteral;
public HashMap<String, ArrayList<JSONObject>> resultRecordMap;
public void reset() {
httpResponseCode = 0;
jsonResultsLiteral = null;
resultRecordMap = null;
}
@Override
public void onNewSearchResults(int httpResponseCode,
String jsonResultsLiteral,
HashMap<String, ArrayList<JSONObject>> resultRecordMap) {
Cat.d("onNewSearchResults:", jsonResultsLiteral);
this.httpResponseCode = httpResponseCode;
this.jsonResultsLiteral = jsonResultsLiteral;
this.resultRecordMap = resultRecordMap;
}
}
| SRCH2/srch2-ngn | srch2-android-sdk/source/SRCH2-Android-SDK/simpleApp/src/com/srch2/android/sdk/TestSearchResultsListener.java | Java | bsd-3-clause | 2,476 |
/*
* Created on Dec 1, 2004
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.tolweb.treegrowserver;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.tolweb.dao.ContributorDAO;
import org.tolweb.dao.NodeDAO;
import org.tolweb.hibernate.MappedNode;
import org.tolweb.hibernate.MappedOtherName;
import org.tolweb.hibernate.MappedPage;
import org.tolweb.hibernate.MappedTextSection;
import org.tolweb.hibernate.TitleIllustration;
import org.tolweb.treegrow.main.Contributor;
import org.tolweb.treegrow.main.Keywords;
import org.tolweb.treegrow.main.NodeImage;
import org.tolweb.treegrow.main.StringUtils;
import org.tolweb.treegrow.main.XMLConstants;
import org.tolweb.treegrow.main.XMLReader;
import org.tolweb.treegrow.page.Page;
import org.tolweb.treegrow.page.TextSection;
import org.tolweb.treegrow.tree.Node;
import org.tolweb.treegrow.tree.OtherName;
/**
* @author dmandel
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class ServerXMLReader extends XMLReader {
private ContributorDAO contributorDAO;
private NodeDAO workingNodeDAO;
public Document parseXML(String xmlString) {
StringReader reader = new StringReader(xmlString);
try {
xmlDocument = new SAXBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
return xmlDocument;
}
public List getChildNodeElements(Element nodeElement) {
Element nodesElement = nodeElement.getChild(XMLConstants.NODES);
if (nodesElement != null) {
return nodesElement.getChildren(XMLConstants.NODE);
} else {
return new ArrayList();
}
}
/**
* Walks the tree and returns a list of all the node ids (if they are
* greater than 0 that are contained in the document)
* @param document
* @return a set of the node ids in the document
*/
public Set getNodeIdsFromRootNodeElement(Element rootNodeElement) {
Set nodeIds = new HashSet();
addChildNodeIdsForNodeElement(rootNodeElement, nodeIds);
return nodeIds;
}
private void addChildNodeIdsForNodeElement(Element nodeElement, Set nodeIdsSet) {
String nodeIdString = nodeElement.getAttributeValue(XMLConstants.ID);
try {
int nodeIdInt = Integer.parseInt(nodeIdString);
nodeIdsSet.add(new Long(nodeIdInt));
} catch (Exception e) {}
Element nodesElement = nodeElement.getChild(XMLConstants.NODES);
if (nodesElement != null) {
for (Iterator it = nodesElement.getChildren(XMLConstants.NODE).iterator(); it.hasNext();) {
Element currentNodeElement = (Element) it.next();
addChildNodeIdsForNodeElement(currentNodeElement, nodeIdsSet);
}
}
}
public int getRootNodeId(Document document) {
Element rootNodeElement = getRootNodeElement(document);
return getNodeIdFromNodeElement(rootNodeElement);
}
public Element getRootNodeElement(Document document) {
Element nodesElement = document.getRootElement().getChild(XMLConstants.NODES);
if (nodesElement != null) {
return nodesElement.getChild(XMLConstants.NODE);
} else {
return document.getRootElement().getChild(XMLConstants.NODE);
}
}
public Element getPageElementFromNodeElement(Element nodeElement) {
return nodeElement.getChild(XMLConstants.PAGE);
}
public boolean getNodeHasPage(Element nodeElement) {
String hasPage = nodeElement.getAttributeValue(XMLConstants.HASPAGE);
boolean returnVal = false;
if (StringUtils.notEmpty(hasPage)) {
if (hasPage.equals(XMLConstants.ONE)) {
returnVal = true;
}
}
return returnVal;
}
protected void setAuthorityDateForNode(Node node, int date) {
if (date > 0) {
((MappedNode) node).setAuthorityDate(new Integer(date));
}
}
protected void setNodeRankForNode(Node node, int nodeRank) {
((MappedNode) node).setNodeRankInteger(new Integer(nodeRank));
}
protected void setSequenceForNode(Node node, int sequence) {
((MappedNode) node).setOrderOnParent(new Integer(sequence));
}
protected Collection getSynonymCollectionInstance() {
return new TreeSet();
}
protected void setOtherNamesForNode(Node node, Collection syns) {
node.setSynonyms((SortedSet) syns);
}
protected OtherName getOtherNameInstanceForNode(Node node) {
return new MappedOtherName();
}
protected void setYearForOtherName(OtherName name, int year) {
((MappedOtherName) name).setAuthorityYear(new Integer(year));
}
protected void setOrderForOtherName(OtherName name, int order) {
((MappedOtherName) name).setOrder(order);
}
/* (non-Javadoc)
* @see org.tolweb.treegrow.main.XMLReader#decodeImageListElement(org.jdom.Element, org.tolweb.treegrow.page.Page)
*/
protected void decodeImageListElement(Element imageListElement, Page tempPage) {
SortedSet titleIllustrations = new TreeSet();
Iterator it = imageListElement.getChildren(XMLConstants.IMAGE).iterator();
while (it.hasNext()) {
Element nextImgElement = (Element) it.next();
TitleIllustration illustration = new TitleIllustration();
illustration.setVersionId(new Long(nextImgElement.getAttributeValue(XMLConstants.IMAGEID)));
illustration.setOrder(new Integer(nextImgElement.getAttributeValue(XMLConstants.ORDER)).intValue());
titleIllustrations.add(illustration);
}
((MappedPage) tempPage).setTitleIllustrations(titleIllustrations);
}
protected void decodeTextListElement(Element textListElement, Page tempPage) {
// TODO Auto-generated method stub
List textSectionList = textListElement.getChildren();
SortedSet textSections = new TreeSet();
Iterator it = textSectionList.iterator();
while (it.hasNext()) {
Element textSectionElem = (Element)it.next();
MappedTextSection tempTextSection = new MappedTextSection();
String attribValue = textSectionElem.getAttributeValue(XMLConstants.CHANGED);
tempTextSection.setChangedFromServer( attribValue!=null && attribValue.equals(XMLConstants.TRUE) );
Element headingElem = textSectionElem.getChild(XMLConstants.HEADING);
Element textElem = textSectionElem.getChild(XMLConstants.TEXT);
String tempOrderString = textSectionElem.getAttributeValue(XMLConstants.SEQUENCE);
if (headingElem != null) {
tempTextSection.setHeading(headingElem.getTextTrim());
} else {
tempTextSection.setHeading("");
}
if(textElem != null) {
tempTextSection.setText(textElem.getTextTrim());
} else {
tempTextSection.setText("");
}
tempTextSection.setOrder(new Integer(tempOrderString).intValue());
textSections.add(tempTextSection);
}
((MappedPage) tempPage).setTextSections(textSections);
}
public void readNodeProperties(Node node, Element nodeElem, boolean isNewVersion) {
super.readNodeProperties(node, nodeElem, isNewVersion);
// also check some properties that aren't read in when doing treegrow stuff
String incSubgroups = nodeElem.getAttributeValue(XMLConstants.INCOMPLETESUBGROUPS);
if (StringUtils.notEmpty(incSubgroups)) {
node.setHasIncompleteSubgroups(XMLReader.getBooleanValue(nodeElem, XMLConstants.INCOMPLETESUBGROUPS));
}
String showAuthContaining = nodeElem.getAttributeValue(XMLConstants.SHOWAUTHORITYCONTAINING);
if (StringUtils.notEmpty(showAuthContaining)) {
((MappedNode) node).setShowAuthorityInContainingGroup(XMLReader.getBooleanValue(nodeElem, XMLConstants.SHOWAUTHORITYCONTAINING));
}
String italicizeName = nodeElem.getAttributeValue(XMLConstants.ITALICIZE_NAME);
if (StringUtils.notEmpty(italicizeName)) {
((MappedNode) node).setItalicizeName(XMLReader.getBooleanValue(nodeElem, XMLConstants.ITALICIZE_NAME));
}
String newCombination = nodeElem.getAttributeValue(XMLConstants.IS_NEW_COMBINATION);
if (StringUtils.notEmpty(newCombination)) {
((MappedNode) node).setIsNewCombination(XMLReader.getBooleanValue(nodeElem, XMLConstants.IS_NEW_COMBINATION));
}
String nameComment = nodeElem.getChildText(XMLConstants.NAMECOMMENT);
if (nameComment != null) {
((MappedNode) node).setNameComment(nameComment);
}
String combAuthor = nodeElem.getChildText(XMLConstants.COMBINATION_AUTHOR);
if (combAuthor != null) {
((MappedNode) node).setCombinationAuthor(combAuthor);
}
String combDate = nodeElem.getChildText(XMLConstants.COMBINATION_DATE);
if (StringUtils.notEmpty(combDate)) {
try {
// if the date isn't an int just ignore it
((MappedNode) node).setCombinationDate(new Integer(combDate));
} catch (Exception e) {}
}
}
protected void fetchNote(Element nodeElem, Node node) {
super.fetchNote(nodeElem, node);
}
protected void fetchSynonyms(Element nodeElem, Node node) {
super.fetchSynonyms(nodeElem, node);
}
protected void fetchAuthorities(Element nodeElem, Node node) {
super.fetchAuthorities(nodeElem, node);
}
/* (non-Javadoc)
* @see org.tolweb.treegrow.main.XMLReader#getCollectionInstanceForPageContributors()
*/
protected Collection getCollectionInstanceForPageContributors() {
return new TreeSet();
}
/* (non-Javadoc)
* @see org.tolweb.treegrow.main.XMLReader#setPageContributorsForPage(org.tolweb.treegrow.page.Page, java.util.Collection)
*/
protected void setPageContributorsForPage(Page page, Collection pageContributors) {
((MappedPage) page).setContributors((SortedSet) pageContributors);
}
public boolean getIsNewVersion(Element rootElement) {
String newVersionString = rootElement.getAttributeValue(XMLConstants.NEW_VERSION);
return StringUtils.notEmpty(newVersionString) && newVersionString.equals(XMLConstants.ONE);
}
public void getNodeImageFromElement(NodeImage newImage, Element imgElem, Contributor contr2) {
String copyrightOwner = imgElem.getChildText(XMLConstants.copyrightowner);
if (StringUtils.notEmpty(copyrightOwner)) {
if (StringUtils.getIsNumeric(copyrightOwner)) {
// It's an id, so lookup the contributor and set them.
Contributor contr = getContributorDAO().getContributorWithId(copyrightOwner);
if (contr != null) {
newImage.setCopyrightOwnerContributor(contr);
}
} else if (copyrightOwner.equalsIgnoreCase(XMLConstants.pd)) {
// public domain
newImage.setInPublicDomain(true);
newImage.setCopyrightOwnerContributor(null);
} else {
newImage.setCopyrightOwner(copyrightOwner);
newImage.setCopyrightEmail(imgElem.getChildText(XMLConstants.copyrightemail));
newImage.setCopyrightUrl(imgElem.getChildText(XMLConstants.copyrighturl));
newImage.setCopyrightOwnerContributor(null);
}
} else {
newImage.setCopyrightOwnerContributor(contr2);
}
String copyrightDate = imgElem.getChildText(XMLConstants.copyrightdate);
if (StringUtils.notEmpty(copyrightDate)) {
newImage.setCopyrightDate(copyrightDate);
}
String use = imgElem.getChildText(XMLConstants.license);
boolean notEmpty = StringUtils.notEmpty(use);
byte usePermission = NodeImage.TOL_USE;
boolean modificationPermitted = false;
if (notEmpty && use.equalsIgnoreCase(XMLConstants.restricted)) {
usePermission = NodeImage.RESTRICTED_USE;
} else if (notEmpty && use.equalsIgnoreCase(XMLConstants.tolusemod)) {
modificationPermitted = true;
} else if (notEmpty && use.equalsIgnoreCase(XMLConstants.tolsharenomod)) {
usePermission = NodeImage.EVERYWHERE_USE;
} else if (notEmpty && use.equalsIgnoreCase(XMLConstants.tolsharemod)) {
usePermission = NodeImage.EVERYWHERE_USE;
modificationPermitted = true;
} else if (notEmpty && use.equalsIgnoreCase(XMLConstants.cc)) {
usePermission = NodeImage.CC_BY_NC20;
modificationPermitted = true;
}
List nodesList = getNodesFromElements(imgElem, XMLConstants.group, false);
if (nodesList.size() > 0) {
Object lastElement = nodesList.get(nodesList.size() - 1);
if (!MappedNode.class.isInstance(lastElement)) {
nodesList.remove(lastElement);
}
}
Set nodes = new HashSet(nodesList);
if (nodes.size() > 0) {
newImage.setNodesSet(nodes);
}
newImage.setUsePermission(usePermission);
newImage.setModificationPermitted(new Boolean(modificationPermitted));
newImage.setReference(imgElem.getChildText(XMLConstants.reference));
newImage.setCreator(imgElem.getChildText(XMLConstants.creator));
newImage.setAcknowledgements(imgElem.getChildText(XMLConstants.acknowledgements));
newImage.setIsSpecimen(getBooleanAttributeValue(imgElem, XMLConstants.specimen));
newImage.setIsBodyParts(getBooleanAttributeValue(imgElem, XMLConstants.bodyparts));
newImage.setIsUltrastructure(getBooleanAttributeValue(imgElem, XMLConstants.ultrastructure));
newImage.setIsHabitat(getBooleanAttributeValue(imgElem, XMLConstants.habitat));
newImage.setIsEquipment(getBooleanAttributeValue(imgElem, XMLConstants.equipment));
newImage.setIsPeopleWorking(getBooleanAttributeValue(imgElem, XMLConstants.people));
String subject = imgElem.getChildText(XMLConstants.subject);
if (StringUtils.notEmpty(subject)) {
decodeSubjects(newImage, subject);
}
newImage.getKeywords().setAdditionalKeywords(imgElem.getChildText(XMLConstants.keywords));
newImage.setGeoLocation(imgElem.getChildText(XMLConstants.geolocation));
newImage.setUserCreationDate(imgElem.getChildText(XMLConstants.time));
String condition = imgElem.getChildText(XMLConstants.condition);
if (StringUtils.notEmpty(condition)) {
String conditionValue = condition;
if (condition.equalsIgnoreCase(XMLConstants.l) || condition.equalsIgnoreCase(XMLConstants.live)) {
conditionValue = NodeImage.ALIVE;
} else if (condition.equalsIgnoreCase(XMLConstants.d) || condition.equalsIgnoreCase(XMLConstants.dead)) {
conditionValue = NodeImage.DEAD;
} else if (condition.equalsIgnoreCase(XMLConstants.f) || condition.equalsIgnoreCase(XMLConstants.fossil)) {
conditionValue = NodeImage.FOSSIL;
} else if (condition.equalsIgnoreCase(XMLConstants.m) || condition.equalsIgnoreCase(XMLConstants.model)) {
conditionValue = NodeImage.MODEL;
}
newImage.setAlive(conditionValue);
}
newImage.setPeriod(imgElem.getChildText(XMLConstants.period));
newImage.setScientificName(imgElem.getChildText(XMLConstants.scientificname));
newImage.setIdentifier(imgElem.getChildText(XMLConstants.identifier));
newImage.setBehavior(imgElem.getChildText(XMLConstants.behavior));
newImage.setSex(imgElem.getChildText(XMLConstants.sex));
newImage.setStage(imgElem.getChildText(XMLConstants.stage));
newImage.setBodyPart(imgElem.getChildText(XMLConstants.partofbody));
newImage.setView(imgElem.getChildText(XMLConstants.view));
newImage.setSize(imgElem.getChildText(XMLConstants.size));
newImage.setCollection(imgElem.getChildText(XMLConstants.collection));
newImage.setType(imgElem.getChildText(XMLConstants.type));
newImage.setVoucherNumber(imgElem.getChildText(XMLConstants.vouchernumber));
newImage.setVoucherNumberCollection(imgElem.getChildText(XMLConstants.vouchercollection));
newImage.setCollector(imgElem.getChildText(XMLConstants.collector));
newImage.setComments(imgElem.getChildText(XMLConstants.comments));
newImage.setAltText(imgElem.getChildText(XMLConstants.alt));
newImage.setTechnicalInformation(imgElem.getChildText(XMLConstants.technical));
newImage.setNotes(imgElem.getChildText(XMLConstants.notes));
newImage.setArtisticInterpretation(getBooleanAttributeValue(imgElem, XMLConstants.artistic));
String imgType = imgElem.getChildText(XMLConstants.imagetype);
if (StringUtils.notEmpty(imgType)) {
String imgTypeValue = imgType;
if (imgType.equalsIgnoreCase(XMLConstants.photo)) {
imgTypeValue = NodeImage.PHOTOGRAPH;
} else if (imgType.equalsIgnoreCase(XMLConstants.drawing) || imgType.equalsIgnoreCase(XMLConstants.painting)) {
imgTypeValue = NodeImage.DRAWING_PAINTING;
} else if (imgType.equalsIgnoreCase(XMLConstants.diagram)) {
imgTypeValue = NodeImage.DIAGRAM;
}
newImage.setImageType(imgTypeValue);
}
}
/**
* Return a list of nodes decoded from the xml. The last element in the
* list is a list of names that didn't match any nodes
* @param parentElement
* @param nodeElementName
* @param checkPermission
* @return
*/
private List getNodesFromElements(Element parentElement, String nodeElementName, boolean checkPermission) {
List nodes = new ArrayList();
List<String> namesMissingNodes = new ArrayList<String>();
NodeDAO workingDAO = getWorkingNodeDAO();
Hashtable nodesToPermissions = new Hashtable();
for (Iterator iter = parentElement.getChildren(nodeElementName).iterator(); iter.hasNext();) {
Element nextGroup = (Element) iter.next();
String nodeName = nextGroup.getTextTrim();
List matches = workingDAO.findNodesExactlyNamed(nodeName);
if (matches.size() > 0) {
nodes.addAll(matches);
} else {
namesMissingNodes.add(nodeName);
}
if (checkPermission) {
// record the permission for each node in a hashtable
boolean hasPermission = false;
String permissionString = nextGroup.getAttributeValue(XMLConstants.permission);
if (StringUtils.notEmpty(permissionString)) {
if (permissionString.equals(XMLConstants.ONE)) {
hasPermission = true;
}
}
for (Iterator iterator = matches.iterator(); iterator.hasNext();) {
MappedNode nextNode = (MappedNode) iterator.next();
nodesToPermissions.put(nextNode, hasPermission);
}
}
}
nodes.add(namesMissingNodes);
if (checkPermission) {
nodes.add(nodesToPermissions);
}
return nodes;
}
private void decodeSubjects(NodeImage img, String subjectsString) {
String[] subjectNumbers = subjectsString.split(",");
Keywords keywords = img.getKeywords();
for (int i = 0; i < subjectNumbers.length; i++) {
String nextSubjectNumber = subjectNumbers[i];
if (StringUtils.getIsNumeric(nextSubjectNumber)) {
decodeSubjectNumber(Integer.parseInt(nextSubjectNumber), keywords);
}
}
}
private void decodeSubjectNumber(int number, Keywords keywords) {
switch (number) {
case 1: keywords.setEvolution(true); break;
case 2: keywords.setPhylogenetics(true); break;
case 3: keywords.setTaxonomy(true); break;
case 4: keywords.setBiodiversity(true); break;
case 5: keywords.setEcology(true); break;
case 6: keywords.setConservation(true); break;
case 7: keywords.setBiogeography(true); break;
case 8: keywords.setPaleobiology(true); break;
case 9: keywords.setMorphology(true); break;
case 10: keywords.setLifehistory(true); break;
case 11: keywords.setPhysiology(true); break;
case 12: keywords.setNeurobiology(true); break;
case 13: keywords.setHistology(true); break;
case 14: keywords.setGenetics(true); break;
case 15: keywords.setMolecular(true); break;
case 16: keywords.setMethods(true); break;
}
}
public Element getImageElementWithFilename(String filename, org.jdom.Document doc) {
try {
Element foundElement = null;
for (Iterator iter = doc.getRootElement().getChildren(XMLConstants.image).iterator(); iter.hasNext();) {
Element imgElement = (Element) iter.next();
String location = imgElement.getChildText(XMLConstants.filename);
if (location != null && location.equals(filename)) {
foundElement = imgElement;
}
}
return foundElement;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private boolean getBooleanAttributeValue(Element imgElem, String elementName) {
String elementValue = imgElem.getChildTextTrim(elementName);
boolean returnVal = false;
if (StringUtils.notEmpty(elementValue)) {
if (elementValue.equalsIgnoreCase(XMLConstants.y) || elementValue.equals(XMLConstants.ONE)) {
returnVal = true;
}
}
return returnVal;
}
/**
* Return a list of: 1) the contributor 2) the non-permission nodes 3) the permission nodes
* 4) unmatched nodes 5) whether to send email or not
* @param contributorElement
* @return
*/
public List getContributorAndNodesFromElement(Element contributorElement, Contributor existingContributor) {
List returnList = new ArrayList();
Contributor contributor = existingContributor;
if (contributor == null) {
contributor = new Contributor();
}
contributor.setSurname(contributorElement.getChildText(XMLConstants.surname));
contributor.setFirstName(contributorElement.getChildText(XMLConstants.firstname));
contributor.setEmail(contributorElement.getChildText(XMLConstants.email));
contributor.setHomepage(contributorElement.getChildText(XMLConstants.webpageurl));
contributor.setInstitution(contributorElement.getChildText(XMLConstants.institution));
contributor.setAddress(contributorElement.getChildText(XMLConstants.address));
contributor.setBio(contributorElement.getChildText(XMLConstants.bio));
contributor.setNotes(contributorElement.getChildText(XMLConstants.comments));
contributor.setPhone(contributorElement.getChildText(XMLConstants.phone));
contributor.setFax(contributorElement.getChildText(XMLConstants.fax));
contributor.setDontShowEmail(getBooleanValue(contributorElement, XMLConstants.dontpublishemail));
contributor.setWillingToCoordinate(getBooleanValue(contributorElement, XMLConstants.coordinator));
String interests = contributorElement.getChildText(XMLConstants.interests);
if (StringUtils.notEmpty(interests)) {
decodeInterests(contributor, interests);
}
contributor.setGeographicAreaInterest(contributorElement.getChildText(XMLConstants.geographicareainterest));
contributor.setOtherInterests(contributorElement.getChildText(XMLConstants.otherinterests));
byte contributorType = Contributor.OTHER_SCIENTIST;
String typeString = contributorElement.getChildText(XMLConstants.type);
if (StringUtils.notEmpty(typeString)) {
if (typeString.equalsIgnoreCase("core")) {
contributorType = Contributor.SCIENTIFIC_CONTRIBUTOR;
} else if (typeString.equalsIgnoreCase("general")) {
contributorType = Contributor.ACCESSORY_CONTRIBUTOR;
}
}
contributor.setContributorType(contributorType);
returnList.add(contributor);
List nodes = getNodesFromElements(contributorElement, XMLConstants.group, true);
// peel off the last two elements of the list because they aren't really nodes at all
Hashtable nodesToPermissions = (Hashtable) nodes.remove(nodes.size() - 1);
List missingNamesList = (List) nodes.remove(nodes.size() - 1);
List nodesList = new ArrayList();
List noPermissionNodesList = new ArrayList();
for (Iterator iter = nodes.iterator(); iter.hasNext();) {
MappedNode nextNode = (MappedNode) iter.next();
Boolean hasPermission = (Boolean) nodesToPermissions.get(nextNode);
if (hasPermission != null && hasPermission) {
nodesList.add(nextNode);
} else {
noPermissionNodesList.add(nextNode);
}
}
returnList.add(noPermissionNodesList);
returnList.add(nodesList);
returnList.add(missingNamesList);
String sendEmail = contributorElement.getChildText(XMLConstants.sendemail);
boolean shouldSendEmail = StringUtils.notEmpty(sendEmail) &&
(sendEmail.equals(XMLConstants.TRUE) || sendEmail.equals(XMLConstants.ONE));
returnList.add(shouldSendEmail);
return returnList;
}
private void decodeInterests(Contributor contr, String interestsString) {
String[] interestNumbers = interestsString.split(",");
for (int i = 0; i < interestNumbers.length; i++) {
String nextInterestNumber = interestNumbers[i];
if (StringUtils.getIsNumeric(nextInterestNumber)) {
int interestNum = Integer.parseInt(nextInterestNumber);
switch (interestNum) {
case 1: contr.setInterestedInTaxonomy(true); break;
case 2: contr.setInterestedInPhylogenetics(true); break;
case 3: contr.setInterestedInMorphology(true); break;
case 4: contr.setInterestedInBiogeography(true); break;
case 5: contr.setInterestedInImmatureStages(true); break;
case 6: contr.setInterestedInEcology(true); break;
case 7: contr.setInterestedInBehavior(true); break;
case 8: contr.setInterestedInCytogenetics(true); break;
case 9: contr.setInterestedInProteins(true); break;
}
}
}
}
public ContributorDAO getContributorDAO() {
return contributorDAO;
}
public void setContributorDAO(ContributorDAO contributorDAO) {
this.contributorDAO = contributorDAO;
}
public NodeDAO getWorkingNodeDAO() {
return workingNodeDAO;
}
public void setWorkingNodeDAO(NodeDAO workingNodeDAO) {
this.workingNodeDAO = workingNodeDAO;
}
}
| tolweb/tolweb-app | TreeGrowServer/src/org/tolweb/treegrowserver/ServerXMLReader.java | Java | bsd-3-clause | 27,282 |
/* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.web.templatemodels.individual;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_LITERAL;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_PREDICATE;
import static edu.cornell.mannlib.vitro.webapp.auth.requestedAction.RequestedAction.SOME_URI;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.cornell.mannlib.vedit.beans.LoginStatusBean;
import edu.cornell.mannlib.vitro.webapp.auth.permissions.SimplePermission;
import edu.cornell.mannlib.vitro.webapp.auth.policy.PolicyHelper;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddDataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.auth.requestedAction.propstmt.AddObjectPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.DataPropertyStatement;
import edu.cornell.mannlib.vitro.webapp.beans.Individual;
import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.config.ConfigurationProperties;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder.Route;
import edu.cornell.mannlib.vitro.webapp.dao.ObjectPropertyStatementDao;
import edu.cornell.mannlib.vitro.webapp.dao.VClassDao;
import edu.cornell.mannlib.vitro.webapp.dao.WebappDaoFactory;
import edu.cornell.mannlib.vitro.webapp.reasoner.SimpleReasoner;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.BaseTemplateModel;
public abstract class BaseIndividualTemplateModel extends BaseTemplateModel {
private static final Log log = LogFactory.getLog(BaseIndividualTemplateModel.class);
protected final Individual individual;
protected final LoginStatusBean loginStatusBean;
protected final VitroRequest vreq;
private final ServletContext ctx;
private final boolean editing;
protected GroupedPropertyList propertyList;
public BaseIndividualTemplateModel(Individual individual, VitroRequest vreq) {
this.vreq = vreq;
this.ctx = vreq.getSession().getServletContext();
this.individual = individual;
this.loginStatusBean = LoginStatusBean.getBean(vreq);
// Needed for getting portal-sensitive urls. Remove if multi-portal support is removed.
this.editing = isEditable();
}
protected boolean isVClass(String vClassUri) {
boolean isVClass = individual.isVClass(vClassUri);
// If reasoning is asynchronous, this inference may not have been made yet.
// Check the superclasses of the individual's vclass.
SimpleReasoner simpleReasoner = (SimpleReasoner) ctx.getAttribute(SimpleReasoner.class.getName());
if (!isVClass && simpleReasoner != null && simpleReasoner.isABoxReasoningAsynchronous()) {
log.debug("Checking superclasses to see if individual is a " + vClassUri + " because reasoning is asynchronous");
List<VClass> directVClasses = individual.getVClasses(true);
for (VClass directVClass : directVClasses) {
VClassDao vcDao = vreq.getWebappDaoFactory().getVClassDao();
List<String> superClassUris = vcDao.getAllSuperClassURIs(directVClass.getURI());
if (superClassUris.contains(vClassUri)) {
isVClass = true;
break;
}
}
}
return isVClass;
}
/* Template properties */
public String getProfileUrl() {
return UrlBuilder.getIndividualProfileUrl(individual, vreq);
}
public String getImageUrl() {
String imageUrl = individual.getImageUrl();
return imageUrl == null ? null : getUrl(imageUrl);
}
public String getThumbUrl() {
String thumbUrl = individual.getThumbUrl();
return thumbUrl == null ? null : getUrl(thumbUrl);
}
// Used to create a link to generate the individual's rdf.
public String getRdfUrl() {
String individualUri = getUri();
String profileUrl = getProfileUrl();
if (UrlBuilder.isUriInDefaultNamespace(individualUri, vreq)) {
return UrlBuilder.getUrl("/individual/" + getLocalName() + "/" + getLocalName() + ".rdf") ;
} else {
return UrlBuilder.addParams(profileUrl, "format", "rdfxml");
}
}
public GroupedPropertyList getPropertyList() {
if (propertyList == null) {
propertyList = new GroupedPropertyList(individual, vreq, editing);
}
return propertyList;
}
/**
* This page is editable if the user is authorized to add a data property or
* an object property to the Individual being shown.
*/
public boolean isEditable() {
AddDataPropertyStatement adps = new AddDataPropertyStatement(
vreq.getJenaOntModel(), individual.getURI(),
SOME_URI, SOME_LITERAL);
AddObjectPropertyStatement aops = new AddObjectPropertyStatement(
vreq.getJenaOntModel(), individual.getURI(),
SOME_PREDICATE, SOME_URI);
return PolicyHelper.isAuthorizedForActions(vreq, adps.or(aops));
}
public boolean getShowAdminPanel() {
return PolicyHelper.isAuthorizedForActions(vreq,
SimplePermission.SEE_INDVIDUAL_EDITING_PANEL.ACTION);
}
/* rdfs:label needs special treatment, because it is not possible to construct a
* DataProperty from it. It cannot be handled the way the vitro links and vitro public image
* are handled like ordinary ObjectProperty instances.
*/
public NameStatementTemplateModel getNameStatement() {
return new NameStatementTemplateModel(getUri(), vreq);
}
/* These methods simply forward to the methods of the wrapped individual. It would be desirable to
* implement a scheme for proxying or delegation so that the methods don't need to be simply listed here.
* A Ruby-style method missing method would be ideal.
* Update: DynamicProxy doesn't work because the proxied object is of type Individual, so we cannot
* declare new methods here that are not declared in the Individual interface.
*/
public String getName() {
return individual.getName();
}
public Collection<String> getMostSpecificTypes() {
ObjectPropertyStatementDao opsDao = vreq.getWebappDaoFactory().getObjectPropertyStatementDao();
Map<String, String> types = opsDao.getMostSpecificTypesInClassgroupsForIndividual(getUri());
return types.values();
}
public String getUri() {
return individual.getURI();
}
public String getLocalName() {
return individual.getLocalName();
}
// For testing dump
// // Properties
// public String getANullString() {
// return null;
// }
// public String getAnEmptyString() {
// return "";
// }
// public String[] getANullArray() {
// return null;
// }
// public String[] getAnEmptyArray() {
// String[] a = {};
// return a;
// }
// public List<String> getANullList() {
// return null;
// }
// public List<String> getAnEmptyList() {
// return Collections.emptyList();
// }
// public Map<String, String> getANullMap() {
// return null;
// }
// public Map<String, String> getAnEmptyMap() {
// return Collections.emptyMap();
// }
//
// // Methods
// public String nullString() {
// return null;
// }
// public String emptyString() {
// return "";
// }
// public String[] nullArray() {
// return null;
// }
// public String[] emptyArray() {
// String[] a = {};
// return a;
// }
// public List<String> nullList() {
// return null;
// }
// public List<String> emptyList() {
// return Collections.emptyList();
// }
// public Map<String, String> nullMap() {
// return null;
// }
// public Map<String, String> emptyMap() {
// return Collections.emptyMap();
// }
/* Template methods */
public String selfEditingId() {
String id = null;
String idMatchingProperty =
ConfigurationProperties.getBean(ctx).getProperty("selfEditing.idMatchingProperty");
if (! StringUtils.isBlank(idMatchingProperty)) {
WebappDaoFactory wdf = vreq.getUnfilteredWebappDaoFactory();
Collection<DataPropertyStatement> ids =
wdf.getDataPropertyStatementDao().getDataPropertyStatementsForIndividualByDataPropertyURI(individual, idMatchingProperty);
if (ids.size() > 0) {
id = ids.iterator().next().getData();
}
}
return id;
}
public String controlPanelUrl() {
return UrlBuilder.getUrl(Route.INDIVIDUAL_EDIT, "uri", getUri());
}
}
| vivo-project/Vitro | api/src/main/java/edu/cornell/mannlib/vitro/webapp/web/templatemodels/individual/BaseIndividualTemplateModel.java | Java | bsd-3-clause | 9,136 |
package edu.umass.cs.jfoley.coop.prf;
import ciir.jfoley.chai.collections.list.IntList;
import ciir.jfoley.chai.io.Directory;
import ciir.jfoley.chai.io.IO;
import edu.umass.cs.jfoley.coop.PMITerm;
import edu.umass.cs.jfoley.coop.bills.IntCoopIndex;
import edu.umass.cs.jfoley.coop.experiments.rels.ScoreDocumentsForSnippets;
import edu.umass.cs.jfoley.coop.front.TermPositionsIndex;
import edu.umass.cs.jfoley.coop.front.eval.EvaluateBagOfWordsMethod;
import edu.umass.cs.jfoley.coop.front.eval.NearbyTermFinder;
import edu.umass.cs.jfoley.coop.front.eval.PMITermScorer;
import edu.umass.cs.jfoley.coop.querying.eval.DocumentResult;
import gnu.trove.map.hash.TIntIntHashMap;
import org.lemurproject.galago.core.parse.TagTokenizer;
import org.lemurproject.galago.core.retrieval.LocalRetrieval;
import org.lemurproject.galago.core.retrieval.Results;
import org.lemurproject.galago.core.retrieval.ScoredDocument;
import org.lemurproject.galago.core.retrieval.query.Node;
import org.lemurproject.galago.utility.Parameters;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* @author jfoley
*/
public class PassagePMITermExpansion {
public static void main(String[] args) throws IOException {
Parameters argp = Parameters.parseArgs(args);
//String dataset = "clue12a.sdm";
String dataset = argp.get("dataset", "robust");
//String dataset = "clue12a.sdm";
LocalRetrieval ret = new LocalRetrieval("/mnt/scratch3/jfoley/"+dataset+".galago");
IntCoopIndex target = new IntCoopIndex(Directory.Read("/mnt/scratch3/jfoley/"+dataset+".ints"));
TermPositionsIndex index = target.getPositionsIndex();
Map<String, String> queries = new TreeMap<>(ScoreDocumentsForSnippets.loadQueries(dataset));
String baselineModel = argp.get("baseline", "sdm");
if(baselineModel.equals("ql")) {
baselineModel = "combine";
}
double expansionWeight = argp.get("expansionWeight", 0.8);
int K = 100;
int minTermFrequency = argp.get("minTermFrequency", 2);
int numTerms = argp.get("numTerms", 50);
TagTokenizer tok = new TagTokenizer();
try (PrintWriter trecrun = IO.openPrintWriter(dataset+"."+baselineModel+"-exppmi.mtf"+minTermFrequency+".numTerms"+numTerms+".w"+Double.toString(expansionWeight).replace('.', '_')+".trecrun")) {
for (Map.Entry<String, String> kv : queries.entrySet()) {
String qid = kv.getKey();
List<String> qterms = tok.tokenize(kv.getValue()).terms;
System.err.println("# "+qid+" "+qterms);
Node sdm = new Node(baselineModel);
sdm.addTerms(qterms);
Results requested = ret.transformAndExecuteQuery(sdm, Parameters.parseArray("requested", 3000));
List<String> workingSet = new ArrayList<>(requested.resultSet());
//IntList docFilter = target.getNames().translateReverse(workingSet, -1);
Parameters bom = Parameters.create();
bom.put("query", kv.getValue());
bom.put("passageSize", 150);
Parameters info = Parameters.create();
EvaluateBagOfWordsMethod method = new EvaluateBagOfWordsMethod(bom, info, index);
List<DocumentResult<Integer>> hits = method.computeTimed();
int phraseWidth = method.getPhraseWidth();
int queryFrequency = hits.size();
NearbyTermFinder termFinder = new NearbyTermFinder(target, argp, info, phraseWidth);
TIntIntHashMap termProxCounts = termFinder.termCounts(hits);
PMITermScorer termScorer = new PMITermScorer(index, minTermFrequency, queryFrequency, index.getCollectionLength());
List<PMITerm<Integer>> pmiTerms = termScorer.scoreTerms(termProxCounts, numTerms);
IntList termIds = new IntList();
for (PMITerm<Integer> topTerm : pmiTerms) {
termIds.add(topTerm.term);
}
Map<Integer, String> forwardMap = target.getTermVocabulary().getForwardMap(termIds);
Node expansion = new Node("combine");
int expansionTermIndex = 0;
for (PMITerm<Integer> pmiTerm : pmiTerms) {
double weight = pmiTerm.pmi();
String termAsStr = forwardMap.get(pmiTerm.term);
if (termAsStr == null) continue;
expansion.addChild(Node.Text(termAsStr));
expansion.getNodeParameters().set(Integer.toString(expansionTermIndex++), weight);
}
Node total = new Node("combine");
total.add(sdm);
total.add(expansion);
total.getNodeParameters().set("0", expansionWeight);
total.getNodeParameters().set("1", (1.0 - expansionWeight));
Parameters qp = Parameters.create();
qp.put("workingSet", workingSet);
Results reranked = ret.transformAndExecuteQuery(total, qp);
for (ScoredDocument scoredDocument : reranked.scoredDocuments) {
trecrun.println(scoredDocument.toTRECformat(qid, "sdm-exppmi"));
}
}
}
}
}
| jjfiv/coop | src/main/java/edu/umass/cs/jfoley/coop/prf/PassagePMITermExpansion.java | Java | bsd-3-clause | 4,969 |
package net.thecodersbreakfast.seren.filter;
import java.io.Serializable;
/**
* @author olivier
*/
public class PojoSerializable implements Serializable {
}
| OlivierCroisier/seren | src/test/java/net/thecodersbreakfast/seren/filter/PojoSerializable.java | Java | bsd-3-clause | 161 |
package swidgets;
import sodium.*;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SButton extends JButton {
public SButton(String label) {
this(label, new Cell<Boolean>(true));
}
public SButton(String label, Cell<Boolean> enabled) {
super(label);
StreamSink<Unit> sClickedSink = new StreamSink<>();
this.sClicked = sClickedSink;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sClickedSink.send(Unit.UNIT);
}
});
// Do it at the end of the transaction so it works with looped cells
Transaction.post(() -> setEnabled(enabled.sample()));
l = Operational.updates(enabled).listen(
ena -> {
if (SwingUtilities.isEventDispatchThread())
this.setEnabled(ena);
else {
SwingUtilities.invokeLater(() -> {
this.setEnabled(ena);
});
}
}
);
}
private final Listener l;
public final Stream<Unit> sClicked;
public void removeNotify() {
l.unlisten();
super.removeNotify();
}
}
| kevintvh/sodium | book/swidgets/java/swidgets/src/swidgets/SButton.java | Java | bsd-3-clause | 1,329 |
package src.frc2022.subsystems;
public interface Drive_Generic {
/**
* Set the speed of the motors on the left side of the robot.
*
* @param speed The speed at which the motors move
* @returns
*/
void setLeft(double speed);
/**
* Set the speed of the motors on the right side of the robot.
*
* @param speed The speed at which the motors move
* @returns
*/
void setRight(double speed);
/**
* Move the robot. Only go forward and back.
*
* @param speed The speed of the motors
* @returns
*/
void drive(double speed);
/**
* Move the robot. Each side can have a different speed to allow for
* turning.
*
* @param speedLeft The speed of the left motors
* @param speedRight The speed of the right motors
* @returns
*/
void drive(double speedLeft, double speedRight);
/**
* Halt the motors
*
* @param
* @return
*/
void stop();
/**
* Function that checks if a number is even. Specifically used for checking
* the size of arrays.
*
* @param size
* @return whether or not the number passed through is even
*/
boolean checkEven(int size);
}
| seniorcheeseman/Lovely | src/src/frc2022/subsystems/Drive_Generic.java | Java | bsd-3-clause | 1,124 |
package org.basex.core.cmd;
import static org.basex.core.Text.*;
import org.basex.core.*;
import org.basex.core.parse.*;
import org.basex.core.parse.Commands.Cmd;
import org.basex.core.parse.Commands.CmdCreate;
import org.basex.core.users.*;
/**
* Evaluates the 'create user' command and creates a new user.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public final class CreateUser extends AUser {
/**
* Default constructor.
* @param name user name
* @param pw password
*/
public CreateUser(final String name, final String pw) {
super(name, pw);
}
@Override
protected boolean run() {
final String name = args[0], pw = args[1];
if(!Databases.validName(name)) return error(NAME_INVALID_X, name);
if(name.equals(UserText.ADMIN)) return error(ADMIN_STATIC);
final Users users = context.users;
users.add(new User(name, pw));
users.write();
return info(USER_CREATED_X, args[0]);
}
@Override
public void build(final CmdBuilder cb) {
cb.init(Cmd.CREATE + " " + CmdCreate.USER).arg(0);
if(!cb.conf()) cb.arg(1);
}
}
| BaseXdb/basex | basex-core/src/main/java/org/basex/core/cmd/CreateUser.java | Java | bsd-3-clause | 1,117 |
/*
Copyright (c) 2016, Shanghai YUEWEN Information Technology Co., Ltd.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Shanghai YUEWEN Information Technology Co., Ltd.
* nor the names of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY SHANGHAI YUEWEN INFORMATION TECHNOLOGY CO., LTD.
AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Copyright (c) 2016 著作权由上海阅文信息技术有限公司所有。著作权人保留一切权利。
这份授权条款,在使用者符合以下三条件的情形下,授予使用者使用及再散播本软件包装原始码及二进位可执行形式的权利,无论此包装是否经改作皆然:
* 对于本软件源代码的再散播,必须保留上述的版权宣告、此三条件表列,以及下述的免责声明。
* 对于本套件二进位可执行形式的再散播,必须连带以文件以及/或者其他附于散播包装中的媒介方式,重制上述之版权宣告、此三条件表列,以及下述的免责声明。
* 未获事前取得书面许可,不得使用柏克莱加州大学或本软件贡献者之名称,来为本软件之衍生物做任何表示支持、认可或推广、促销之行为。
免责声明:本软件是由上海阅文信息技术有限公司及本软件之贡献者以现状提供,本软件包装不负任何明示或默示之担保责任,
包括但不限于就适售性以及特定目的的适用性为默示性担保。加州大学董事会及本软件之贡献者,无论任何条件、无论成因或任何责任主义、
无论此责任为因合约关系、无过失责任主义或因非违约之侵权(包括过失或其他原因等)而起,对于任何因使用本软件包装所产生的任何直接性、间接性、
偶发性、特殊性、惩罚性或任何结果的损害(包括但不限于替代商品或劳务之购用、使用损失、资料损失、利益损失、业务中断等等),
不负任何责任,即在该种使用已获事前告知可能会造成此类损害的情形下亦然。
*/
package org.albianj.security;
import org.albianj.service.AlbianBuiltinServiceNamePair;
import org.albianj.service.IAlbianService;
public interface IAlbianSecurityService extends IAlbianService {
final String Name = AlbianBuiltinServiceNamePair.AlbianSecurityServiceName;
public String decryptDES(String message) throws RuntimeException;
public String decryptDES(String key, String message) throws RuntimeException;
public String encryptDES(String message) throws RuntimeException;
public String encryptDES(String key, String message) throws RuntimeException;
public byte[] decryptBASE64(String key) throws RuntimeException;
public String encryptBASE64(byte[] key) throws RuntimeException;
public String encryptMD5(String data) throws RuntimeException;
public String encryptSHA(String data) throws RuntimeException;
public String initMacKey() throws RuntimeException;
public String initMacKey(MACStyle style) throws RuntimeException;
public String encryptHMAC(String key, MACStyle style, byte[] data)
throws RuntimeException;
public String encryptHMAC(String key, MACStyle style, String data)
throws RuntimeException;
public String encryptHMAC(String key, byte[] data) throws RuntimeException;
public String encryptHMAC(String key, String data) throws RuntimeException;
}
| crosg/Albianj2 | Albianj.Security/src/main/java/org/albianj/security/IAlbianSecurityService.java | Java | bsd-3-clause | 4,667 |
/*
* Copyright 2012 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.
*/
package net.idlesoft.android.apps.github.ui.adapters;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.ListView.FixedViewInfo;
import java.util.ArrayList;
/**
* Utility adapter that supports adding headers and footers
*/
public class HeaderFooterListAdapter<E extends BaseAdapter> extends
HeaderViewListAdapter {
private final ListView list;
private final ArrayList<FixedViewInfo> headers;
private final ArrayList<FixedViewInfo> footers;
private final E wrapped;
/**
* Create header footer adapter
*/
public HeaderFooterListAdapter(ListView view, E adapter) {
this(new ArrayList<FixedViewInfo>(), new ArrayList<FixedViewInfo>(),
view, adapter);
}
private HeaderFooterListAdapter(ArrayList<FixedViewInfo> headerViewInfos,
ArrayList<FixedViewInfo> footerViewInfos, ListView view, E adapter) {
super(headerViewInfos, footerViewInfos, adapter);
headers = headerViewInfos;
footers = footerViewInfos;
list = view;
wrapped = adapter;
}
/**
* Add header
*
* @return this adapter
*/
public HeaderFooterListAdapter<E> addHeader(View view, Object data,
boolean isSelectable) {
FixedViewInfo info = list.new FixedViewInfo();
info.view = view;
info.data = data;
info.isSelectable = isSelectable;
headers.add(info);
wrapped.notifyDataSetChanged();
return this;
}
/**
* Add header
*
* @return this adapter
*/
public HeaderFooterListAdapter<E> addFooter(View view, Object data,
boolean isSelectable) {
FixedViewInfo info = list.new FixedViewInfo();
info.view = view;
info.data = data;
info.isSelectable = isSelectable;
footers.add(info);
wrapped.notifyDataSetChanged();
return this;
}
@Override
public boolean removeHeader(View v) {
boolean removed = super.removeHeader(v);
if (removed) {
wrapped.notifyDataSetChanged();
}
return removed;
}
@Override
public boolean removeFooter(View v) {
boolean removed = super.removeFooter(v);
if (removed) {
wrapped.notifyDataSetChanged();
}
return removed;
}
@Override
public E getWrappedAdapter() {
return wrapped;
}
@Override
public boolean isEmpty() {
return wrapped.isEmpty();
}
} | EddieRingle/hubroid | src/net/idlesoft/android/apps/github/ui/adapters/HeaderFooterListAdapter.java | Java | bsd-3-clause | 3,211 |
/*================================================================================
Copyright (c) 2013 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class DVSNetworkResourcePoolAllocationInfo extends DynamicData {
public Long limit;
public SharesInfo shares;
public Integer priorityTag;
public Long getLimit() {
return this.limit;
}
public SharesInfo getShares() {
return this.shares;
}
public Integer getPriorityTag() {
return this.priorityTag;
}
public void setLimit(Long limit) {
this.limit=limit;
}
public void setShares(SharesInfo shares) {
this.shares=shares;
}
public void setPriorityTag(Integer priorityTag) {
this.priorityTag=priorityTag;
}
} | paksv/vijava | src/com/vmware/vim25/DVSNetworkResourcePoolAllocationInfo.java | Java | bsd-3-clause | 2,335 |
package ork.sevenstates.apng.filter;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
abstract class LocalMinimum extends Filter {
private final Filter[] simpleFilters = {
new None(),
new Sub(),
new Up(),
new Average(),
new Paeth()
};
private ExecutorService tpe = new ForkJoinPool();
@Override
public void setBpp(int bpp) {
super.setBpp(bpp);
for (int i = 0; i < simpleFilters.length; i++) {
simpleFilters[i].setBpp(bpp);
}
}
@Override
public void setHeight(int height) {
super.setHeight(height);
for (int i = 0; i < simpleFilters.length; i++) {
simpleFilters[i].setHeight(height);
}
}
@Override
public void setWidth(int width) {
super.setWidth(width);
for (int i = 0; i < simpleFilters.length; i++) {
simpleFilters[i].setWidth(width);
}
}
@Override
public void close() {
tpe.shutdown();
super.close();
}
@Override
protected void encodeRow(final ByteBuffer in, final int srcOffset, ByteBuffer out, final int len,
int destOffset) {
Integer minsize = null;
List<Callable<Entry<Integer, ByteBuffer>>> tasks = new ArrayList<>();
for (int i = 0; i < simpleFilters.length; i++) {
final Filter filter = simpleFilters[i];
tasks.add(new Callable<Map.Entry<Integer,ByteBuffer>>() {
@Override
public Entry<Integer, ByteBuffer> call() {
return doCall(in, srcOffset, len, filter);
}
});
}
List<Future<Entry<Integer, ByteBuffer>>> results = null;
try {
results = tpe.invokeAll(tasks);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Entry<Integer, ByteBuffer> min = null;
for (int i = 0; i < simpleFilters.length; i++) {
Entry<Integer, ByteBuffer> e = min;
try {
e = results.get(i).get();
} catch (InterruptedException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (ExecutionException ex) {
// doCall throws no exception, anything here is not something we'd expect
throw new RuntimeException(ex);
}
// e = doCall(in, srcOffset, len, filter[i]);
if (minsize == null || e.getKey() < minsize) {
minsize = e.getKey();
min = e;
}
}
out.position(destOffset);
out.put(min.getValue());
}
protected abstract Entry<Integer, ByteBuffer> doCall(ByteBuffer src, int srcOffset, int len, Filter f);
}
| Weoulren/apng-writer | apng-writer-core/src/main/java/ork/sevenstates/apng/filter/LocalMinimum.java | Java | bsd-3-clause | 2,638 |
package de.bwaldvogel.mongo.oplog;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import org.junit.jupiter.api.Test;
class OperationTypeTest {
@Test
void testGetCode() {
assertThat(OperationType.INSERT.getCode()).isEqualTo("i");
assertThat(OperationType.UPDATE.getCode()).isEqualTo("u");
assertThat(OperationType.DELETE.getCode()).isEqualTo("d");
}
@Test
void testFromCode() {
for (OperationType operationType : OperationType.values()) {
OperationType operationTypeFromCode = OperationType.fromCode(operationType.getCode());
assertThat(operationTypeFromCode).isEqualTo(operationType);
}
}
@Test()
void testFromCode_throwException() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> OperationType.fromCode("wrongCode"))
.withMessage("unknown operation type: wrongCode");
}
}
| bwaldvogel/mongo-java-server | core/src/test/java/de/bwaldvogel/mongo/oplog/OperationTypeTest.java | Java | bsd-3-clause | 1,024 |
/**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
/**
* CQLObjectResult.java
*
* This file was auto-generated from WSDL by the Apache Axis 1.2RC2 Apr 28, 2006
* (12:42:00 EDT) WSDL2Java emitter.
*/
package org.cagrid.cql2.results;
// import org.apache.axis.message.MessageElement;
// import org.cagrid.cql.utilities.AnyNodeHelper;
import org.exolab.castor.types.AnyNode;
/**
* Result object
*/
public class CQLObjectResult extends org.cagrid.cql2.results.CQLResult implements java.io.Serializable {
private AnyNode _any;
public CQLObjectResult() {
}
public CQLObjectResult(AnyNode _any) {
this._any = _any;
}
/**
* Gets the _any value for this CQLObjectResult.
*
* @return _any
*/
public AnyNode get_any() {
return _any;
}
/**
* Sets the _any value for this CQLObjectResult.
*
* @param _any
*/
public void set_any(AnyNode _any) {
this._any = _any;
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CQLObjectResult))
return false;
CQLObjectResult other = (CQLObjectResult) obj;
if (obj == null)
return false;
if (this == obj)
return true;
boolean _equals;
_equals = super.equals(obj) && anysEqual(other);
return _equals;
}
public synchronized int hashCode() {
int _hashCode = super.hashCode();
if (get_any() != null) {
_hashCode += get_any().hashCode();
}
return _hashCode;
}
private boolean anysEqual(CQLObjectResult other) {
AnyNode oAny = other.get_any();
if (this._any == null && oAny == null) {
return true;
} else if ((this._any != null && oAny == null)
|| (this._any == null && oAny != null)) {
return false;
} else {
try {
//MessageElement myAnyElement = AnyNodeHelper.convertAnyNodeToMessageElement(_any);
// MessageElement theirAnyElement = AnyNodeHelper.convertAnyNodeToMessageElement(oAny);
// return myAnyElement.equals(theirAnyElement);
// HACK:
return true;
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
}
}
}
| NCIP/cagrid-core | caGrid/projects/cql/src/java/beans/cql2/org/cagrid/cql2/results/CQLObjectResult.java | Java | bsd-3-clause | 2,935 |
/*******************************************************************************
* Copyright (c) 2013, SAP AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the SAP AG nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.sap.research.primelife.dc.timebasedtrigger;
import com.sap.research.primelife.dc.entity.OEEStatus;
public interface ITimeBasedTriggerHandler {
public void start();
public void stop();
public void handle(OEEStatus oeeStatus);
public void unHandle(OEEStatus oeeStatus);
}
| fdicerbo/fiware-ppl | ppl-engine-dc/src/main/java/com/sap/research/primelife/dc/timebasedtrigger/ITimeBasedTriggerHandler.java | Java | bsd-3-clause | 2,045 |
package org.tolweb.tapestry;
import org.apache.tapestry.BaseComponent;
import org.apache.tapestry.annotations.InjectObject;
import org.tolweb.misc.PasswordUtils;
import org.tolweb.tapestry.injections.BaseInjectable;
import org.tolweb.treegrow.main.Contributor;
public abstract class NewScientificContributorEmail extends BaseComponent implements BaseInjectable {
@InjectObject("spring:passwordUtils")
public abstract PasswordUtils getPasswordUtils();
public abstract Contributor getContributor();
public String getPlaintextPassword() {
String password = getPasswordUtils().resetPassword(getContributor());
return password;
}
}
| tolweb/tolweb-app | OnlineContributors/src/org/tolweb/tapestry/NewScientificContributorEmail.java | Java | bsd-3-clause | 640 |
package org.antlr.intellij.plugin.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.refactoring.actions.BaseRefactoringAction;
import org.antlr.intellij.plugin.generators.LiteralChooser;
import org.antlr.intellij.plugin.parser.ANTLRv4Parser;
import org.antlr.intellij.plugin.parsing.ParsingResult;
import org.antlr.intellij.plugin.parsing.ParsingUtils;
import org.antlr.intellij.plugin.psi.MyPsiUtils;
import org.antlr.intellij.plugin.refactor.RefactorUtils;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.misc.Interval;
import org.antlr.v4.runtime.misc.Utils;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.pattern.ParseTreeMatch;
import org.antlr.v4.runtime.tree.pattern.ParseTreePattern;
import org.antlr.v4.runtime.tree.xpath.XPath;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
public class GenerateLexerRulesForLiteralsAction extends AnAction {
public static final Logger LOG = Logger.getInstance("ANTLR GenerateLexerRulesForLiterals");
/** Only show if selection is a literal */
@Override
public void update(AnActionEvent e) {
Presentation presentation = e.getPresentation();
VirtualFile grammarFile = MyActionUtils.getGrammarFileFromEvent(e);
if ( grammarFile==null ) {
presentation.setEnabled(false);
return;
}
PsiFile file = e.getData(LangDataKeys.PSI_FILE);
Editor editor = e.getData(PlatformDataKeys.EDITOR);
PsiElement selectedElement = BaseRefactoringAction.getElementAtCaret(editor, file);
if ( selectedElement==null ) { // we clicked somewhere outside text
presentation.setEnabled(false);
return;
}
//
// IElementType tokenType = selectedElement.getNode().getElementType();
// if ( tokenType == ANTLRv4TokenTypes.TOKEN_ELEMENT_TYPES.get(ANTLRv4Parser.STRING_LITERAL) ) {
// presentation.setEnabled(true);
// presentation.setVisible(true);
// }
// else {
// presentation.setEnabled(false);
// }
}
@Override
public void actionPerformed(AnActionEvent e) {
LOG.info("actionPerformed");
final Project project = e.getProject();
final PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
if (psiFile == null) {
return;
}
String inputText = psiFile.getText();
ParsingResult results = ParsingUtils.parseANTLRGrammar(inputText);
final Parser parser = results.parser;
final ParseTree tree = results.tree;
Collection<ParseTree> literalNodes = XPath.findAll(tree, "//ruleBlock//STRING_LITERAL", parser);
LinkedHashMap<String, String> lexerRules = new LinkedHashMap<String, String>();
for (ParseTree node : literalNodes) {
String literal = node.getText();
String ruleText = String.format("%s : %s ;",
RefactorUtils.getLexerRuleNameFromLiteral(literal), literal);
lexerRules.put(literal, ruleText);
}
// remove those already defined
String lexerRulesXPath = "//lexerRule";
String treePattern = "<TOKEN_REF> : <STRING_LITERAL>;";
ParseTreePattern p = parser.compileParseTreePattern(treePattern, ANTLRv4Parser.RULE_lexerRule);
List<ParseTreeMatch> matches = p.findAll(tree, lexerRulesXPath);
for (ParseTreeMatch match : matches) {
ParseTree lit = match.get("STRING_LITERAL");
if (lexerRules.containsKey(lit.getText())) { // we have rule for this literal already
lexerRules.remove(lit.getText());
}
}
final LiteralChooser chooser =
new LiteralChooser(project, new ArrayList<String>(lexerRules.values()));
chooser.show();
List<String> selectedElements = chooser.getSelectedElements();
// chooser disposed automatically.
final Editor editor = e.getData(PlatformDataKeys.EDITOR);
final Document doc = editor.getDocument();
final CommonTokenStream tokens = (CommonTokenStream) parser.getTokenStream();
// System.out.println(selectedElements);
if (selectedElements != null) {
String text = doc.getText();
int cursorOffset = editor.getCaretModel().getOffset();
// make sure it's not in middle of rule; put between.
// System.out.println("offset "+cursorOffset);
Collection<ParseTree> allRuleNodes = XPath.findAll(tree, "//ruleSpec", parser);
for (ParseTree r : allRuleNodes) {
Interval extent = r.getSourceInterval(); // token indexes
int start = tokens.get(extent.a).getStartIndex();
int stop = tokens.get(extent.b).getStopIndex();
// System.out.println("rule "+r.getChild(0).getText()+": "+start+".."+stop);
if (cursorOffset < start) {
// before this rule, so must be between previous and this one
cursorOffset = start; // put right before this rule
break;
} else if (cursorOffset >= start && cursorOffset <= stop) {
// cursor in this rule
cursorOffset = stop + 2; // put right before this rule (after newline)
if (cursorOffset >= text.length()) {
cursorOffset = text.length();
}
break;
}
}
String allRules = Utils.join(selectedElements.iterator(), "\n");
text =
text.substring(0, cursorOffset) +
"\n" + allRules + "\n" +
text.substring(cursorOffset, text.length());
final PsiFile newPsiFile = MyPsiUtils.createFile(project, text);
WriteCommandAction setTextAction = new WriteCommandAction(project) {
@Override
protected void run(final Result result) throws Throwable {
psiFile.deleteChildRange(psiFile.getFirstChild(), psiFile.getLastChild());
psiFile.addRange(newPsiFile.getFirstChild(), newPsiFile.getLastChild());
}
};
setTextAction.execute();
}
}
}
| rojaster/intellij-plugin-v4 | src/java/org/antlr/intellij/plugin/actions/GenerateLexerRulesForLiteralsAction.java | Java | bsd-3-clause | 6,170 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class EVCAdmissionFailedHostDisconnected extends EVCAdmissionFailed {
} | xebialabs/vijava | src/com/vmware/vim25/EVCAdmissionFailedHostDisconnected.java | Java | bsd-3-clause | 1,844 |
/*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*
* $Id: ResourcePanel.java,v 1.1.1.1 2001/05/22 08:13:01 jstrachan Exp $
*/
package org.dom4j.visdom.util;
import org.dom4j.visdom.util.Log;
import org.dom4j.visdom.util.SystemExitManager;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.*;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.*;
import javax.swing.*;
/**
* Base class for a panel which implements general resource
* finding methods plus specific helper methods for menus and toolBars
*/
public class ResourcePanel extends JPanel
{
public ResourcePanel()
{
super(true);
}
public ResourcePanel(ResourceBundle resources)
{
super(true);
this.resources = resources;
}
//-------------------------------------------------------------------------
// getters and setters
//-------------------------------------------------------------------------
public ResourceBundle getResources()
{
return resources;
}
public void setResources(ResourceBundle resources)
{
this.resources = resources;
}
/**
* Fetch the menu item that was created for the given
* command.
* @param cmd Name of the action.
* @returns item created for the given command or null
* if one wasn't created.
*/
protected JMenuItem getMenuItem(String cmd)
{
return (JMenuItem) menuItems.get(cmd);
}
/**
* get an Action object by the Action.NAME attribute
*
*/
public Action getAction(String cmd)
{
// install the command table via lazy construction
// rather than in the constructor
if ( commands == null )
{
commands = new Hashtable();
Action[] actions = getActions();
for (int i = 0; i < actions.length; i++)
{
Action a = actions[i];
commands.put(a.getValue(Action.NAME), a);
}
}
return (Action) commands.get(cmd);
}
/**
* Fetch the list of actions supported by this
* editor. It is implemented to return the list
* of actions supported by the embedded JTextComponent
* augmented with the actions defined locally.
*/
public Action[] getActions()
{
return new Action[0];
}
/**
* Returns the status bar for this component
* if one has been created. May return null.
*
* @return the statusBar for this component; may be null
* if one hasn't been created
*/
public Container getStatusBar()
{
return statusBar;
}
//-------------------------------------------------------------------------
// public make methods: adorn existing toolBar/menuBars
//-------------------------------------------------------------------------
/**
* adds component specific menu items to the given menuBar
*
*/
public void makeMenuBar(JMenuBar menuBar)
{
JMenuItem mi;
String temp = getResourceString("menubar");
if ( temp != null )
{
String[] menuKeys = tokenize(temp);
for (int i = 0; i < menuKeys.length; i++)
{
JMenu m = createMenu(menuKeys[i]);
if (m != null)
{
menuBar.add(m);
}
}
}
}
/**
* adds component specific buttons to the given toolBar
*
*/
public void makeToolBar(JToolBar toolBar)
{
String temp = getResourceString("toolbar");
if ( temp != null )
{
String[] toolKeys = tokenize(temp);
for (int i = 0; i < toolKeys.length; i++)
{
if (toolKeys[i].equals("-"))
{
toolBar.add(Box.createHorizontalStrut(5));
}
else
{
toolBar.add(createTool(toolKeys[i]));
}
}
toolBar.add(Box.createHorizontalGlue());
}
}
//-------------------------------------------------------------------------
// factory methods
//-------------------------------------------------------------------------
/**
* Create the menuBar for the app. By default this pulls the
* definition of the menu from the associated resource file.
*/
public JMenuBar createMenuBar()
{
JMenuBar mb = new JMenuBar();
mb.setName( "MenuBar" );
makeMenuBar(mb);
return mb;
}
/**
* Create the toolBar. By default this reads the
* resource file for the definition of the toolBar.
*/
public Component createToolBar()
{
JToolBar toolBar = new JToolBar();
toolBar.setName( "ToolBar" );
makeToolBar(toolBar);
return toolBar;
}
/**
* Create a status bar
*/
public Component createStatusBar()
{
// need to do something reasonable here
statusBar = new StatusBar();
statusBar.setName( "StatusBar" );
return statusBar;
}
/**
* To shutdown when run as an application. This is a
* fairly lame implementation. A more self-respecting
* implementation would at least check to see if a save
* was needed.
*/
public static WindowAdapter createApplicationCloser()
{
return new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
SystemExitManager.exit(0);
}
};
}
//-------------------------------------------------------------------------
// menu implmentation methods
//-------------------------------------------------------------------------
/**
* Create a menu for the app. By default this pulls the
* definition of the menu from the associated resource file.
*/
protected JMenu createMenu(String key)
{
/*
if ( key.equals( GoMenuFactory.GO_MENU_KEY ) )
{
GoMenuFactory factory = new GoMenuFactory( getResources() );
return factory.createMenu();
}
*/
String label = getResourceString(key + LABEL_SUFFIX);
JMenu menu = new JMenu( label );
makeMenu(menu, key);
return menu;
}
protected void makeMenu(JMenu menu, String key)
{
menu.setName( key );
String temp = getResourceString(key);
if ( temp != null )
{
String[] itemKeys = tokenize(temp);
for (int i = 0; i < itemKeys.length; i++)
{
if (itemKeys[i].equals("-"))
{
menu.addSeparator();
}
else
{
JMenuItem mi = createMenuItem(itemKeys[i]);
menu.add(mi);
}
}
}
}
/**
* This is the hook through which all menu items are
* created. It registers the result with the menuitem
* hashtable so that it can be fetched with getMenuItem().
* @see #getMenuItem
*/
protected JMenuItem createMenuItem(String cmd)
{
String label = getLabelString(cmd );
final JMenuItem mi = new JMenuItem( label );
mi.setName( cmd );
Icon icon = getResourceIcon(cmd);
//URL url = getResource(cmd + IMAGE_SUFFIX);
//if (url != null)
if ( icon != null )
{
mi.setHorizontalTextPosition(JButton.RIGHT);
mi.setIcon(icon);
//mi.setIcon(new ImageIcon(url));
}
String astr = getResourceString(cmd + ACTION_SUFFIX);
if (astr == null)
{
astr = cmd;
}
mi.setActionCommand(astr);
Action a = getAction(astr);
if (a != null)
{
mi.addActionListener(a);
// #### swing should do this but I'll add it anyway
if ( ! a.isEnabled() )
{
mi.setEnabled(false);
}
a.addPropertyChangeListener(
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
String name = evt.getPropertyName();
Object value = evt.getNewValue();
if ( name.equals( ACTION_ENABLED ) &&
value instanceof Boolean )
{
mi.setEnabled( ((Boolean)value).booleanValue() );
}
}
}
);
}
else
{
mi.setEnabled(false);
}
menuItems.put(cmd, mi);
return mi;
}
// #### should be protected
public JMenuItem createActionMenuItem(Action action)
{
String cmd = (String) action.getValue(Action.NAME);
final JMenuItem mi = new JMenuItem( getLabelString(cmd ));
mi.setName( cmd );
Icon icon = getResourceIcon(cmd);
//URL url = getResource(cmd + IMAGE_SUFFIX);
//if (url != null)
if ( icon != null )
{
mi.setHorizontalTextPosition(JButton.RIGHT);
mi.setIcon(icon);
//mi.setIcon(new ImageIcon(url));
}
String astr = getResourceString(cmd + ACTION_SUFFIX);
if (astr == null)
{
astr = cmd;
}
mi.setActionCommand(astr);
mi.addActionListener(action);
// #### swing should do this but I'll add it anyway
if ( ! action.isEnabled() )
{
mi.setEnabled(false);
}
action.addPropertyChangeListener(
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
String name = evt.getPropertyName();
Object value = evt.getNewValue();
if ( name.equals( ACTION_ENABLED ) &&
value instanceof Boolean )
{
mi.setEnabled( ((Boolean)value).booleanValue() );
}
}
}
);
menuItems.put(cmd, mi);
return mi;
}
//-------------------------------------------------------------------------
// toolBar implmentation methods
//-------------------------------------------------------------------------
/**
* Hook through which every toolBar item is created.
*/
protected Component createTool(String key)
{
return createToolBarButton(key);
}
/**
* Create a button to go inside of the toolBar. By default this
* will load an image resource. The image filename is relative to
* the classpath (including the '.' directory if its a part of the
* classpath), and may either be in a JAR file or a separate file.
*
* @param key The key in the resource file to serve as the basis
* of lookups.
*/
protected JButton createToolBarButton(String key)
{
final JButton b = new JButton(getResourceIcon(key));
b.setName( key );
/*
//URL url = getResource(key + IMAGE_SUFFIX);
//JButton b = new JButton(new ImageIcon(url))
{
public float getAlignmentY() { return 0.5f; }
};
*/
b.setRequestFocusEnabled(false);
b.setMargin(new Insets(1,1,1,1));
String astr = getResourceString(key + ACTION_SUFFIX);
if (astr == null)
{
astr = key;
}
Action a = getAction(astr);
if (a != null)
{
b.setActionCommand(astr);
b.addActionListener(a);
// #### swing should do this but I'll add it anyway
if ( ! a.isEnabled() )
{
b.setEnabled(false);
}
a.addPropertyChangeListener(
new PropertyChangeListener()
{
public void propertyChange(PropertyChangeEvent evt)
{
String name = evt.getPropertyName();
Object value = evt.getNewValue();
if ( name.equals( ACTION_ENABLED ) &&
value instanceof Boolean )
{
b.setEnabled( ((Boolean)value).booleanValue() );
}
}
}
);
}
else
{
b.setEnabled(false);
}
String tip = getResourceString(key + TOOLTIP_SUFFIX);
if (tip != null)
{
b.setToolTipText(tip);
}
return b;
}
//-------------------------------------------------------------------------
// Resource fetching methods
//-------------------------------------------------------------------------
protected String getResourceString(String nm)
{
String str;
try
{
str = getResources().getString(nm);
}
catch (MissingResourceException mre)
{
str = null;
}
catch (NullPointerException e)
{
str = null;
}
return str;
}
protected String getLabelString(String cmd)
{
String answer = getResourceString(cmd + LABEL_SUFFIX);
if ( answer == null )
return cmd;
return answer;
}
protected Icon getResourceIcon(String key)
{
String s = getResourceString(key + IMAGE_SUFFIX);
if ( s != null )
{
String name = getResourceString(key + IMAGE_SUFFIX);
URL url = ClassLoader.getSystemResource( name );
if ( url != null )
{
return new ImageIcon(url);
}
else
{
Log.info( "Could not load system resource: " + name );
}
/*
try
{
String name = getResourceString(key + IMAGE_SUFFIX);
URL url = ClassLoader.getSystemResource( name );
//URL url = new URL(name);
if ( url != null )
{
return new ImageIcon(url);
}
catch (MalformedURLException e)
{
Log.exception(e);
}
//return new ImageIcon(getResourceString(key + IMAGE_SUFFIX));
*/
}
return null;
}
protected URL getResource(String key)
{
String name = getResourceString(key);
if (name != null)
{
URL url = this.getClass().getResource(name);
System.out.println( "Resource for key: " + key +
" is name: " + name +
" and URL: " + url );
return url;
}
return null;
}
/**
* Take the given string and chop it up into a series
* of strings on whitespace boundries. This is useful
* for trying to get an array of strings out of the
* resource file.
*/
protected String[] tokenize(String input)
{
Vector v = new Vector();
StringTokenizer t = new StringTokenizer(input);
String cmd[];
while (t.hasMoreTokens())
v.addElement(t.nextToken());
cmd = new String[v.size()];
for (int i = 0; i < cmd.length; i++)
cmd[i] = (String) v.elementAt(i);
return cmd;
}
//-------------------------------------------------------------------------
// StatusBar
//-------------------------------------------------------------------------
/**
* #### FIXME - I'm not very useful yet
*/
class StatusBar extends Container
{
public StatusBar()
{
super();
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
}
public void paint(Graphics g)
{
super.paint(g);
}
}
//-------------------------------------------------------------------------
// Attributes
//-------------------------------------------------------------------------
private Hashtable menuItems = new Hashtable();
private ResourceBundle resources;
private Hashtable commands;
private JMenuBar menuBar;
private JToolBar toolBar;
private Container statusBar;
/**
* Suffix applied to the key used in resource file
* lookups for an image.
*/
public static final String IMAGE_SUFFIX = ".image";
/**
* Suffix applied to the key used in resource file
* lookups for a label.
*/
public static final String LABEL_SUFFIX = ".label";
/**
* Suffix applied to the key used in resource file
* lookups for an action.
*/
public static final String ACTION_SUFFIX = ".action";
/**
* Suffix applied to the key used in resource file
* lookups for tooltip text.
*/
public static final String TOOLTIP_SUFFIX = ".tooltip";
// #### should be moved into Swing
public static final String ACTION_ENABLED = "enabled";
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "DOM4J" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of MetaStuff, Ltd. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "DOM4J"
* nor may "DOM4J" appear in their names without prior written
* permission of MetaStuff, Ltd. DOM4J is a registered
* trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project
* (http://dom4j.org/).
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* $Id: ResourcePanel.java,v 1.1.1.1 2001/05/22 08:13:01 jstrachan Exp $
*/
| dom4j/visdom | src/java/org/dom4j/visdom/util/ResourcePanel.java | Java | bsd-3-clause | 20,303 |
/*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
@SuppressWarnings("all")
public class HourlyTaskScheduler extends RecurrentTaskScheduler {
public int minute;
public int getMinute() {
return this.minute;
}
public void setMinute(int minute) {
this.minute=minute;
}
} | xebialabs/vijava | src/com/vmware/vim25/HourlyTaskScheduler.java | Java | bsd-3-clause | 1,977 |
package org.infernus.idea.checkstyle.handlers;
import com.intellij.CommonBundle;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.checkin.CheckinHandler;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.util.ui.UIUtil;
import org.infernus.idea.checkstyle.CheckStyleConfiguration;
import org.infernus.idea.checkstyle.CheckStyleConstants;
import org.infernus.idea.checkstyle.CheckStylePlugin;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.text.MessageFormat;
import java.util.*;
import java.util.List;
/**
* Before Checkin Handler to scan files with Checkstyle.
*/
public class ScanFilesBeforeCheckinHandler extends CheckinHandler {
private final CheckStylePlugin plugin;
private final CheckinProjectPanel checkinPanel;
/**
* Checkstyle before checkin handler.
*
* @param plugin Checkstyle plugin reference
* @param myCheckinPanel checkin project panel
*/
public ScanFilesBeforeCheckinHandler(final CheckStylePlugin plugin,
final CheckinProjectPanel myCheckinPanel) {
if (plugin == null) {
throw new IllegalArgumentException("Plugin is required");
}
if (myCheckinPanel == null) {
throw new IllegalArgumentException("CheckinPanel is required");
}
this.plugin = plugin;
this.checkinPanel = myCheckinPanel;
}
@Nullable
public RefreshableOnComponent getBeforeCheckinConfigurationPanel() {
final ResourceBundle resources = ResourceBundle.getBundle(
CheckStyleConstants.RESOURCE_BUNDLE);
final JCheckBox checkBox = new JCheckBox(resources.getString("handler.before.checkin.checkbox"));
return new RefreshableOnComponent() {
public JComponent getComponent() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(checkBox);
return panel;
}
public void refresh() {
}
public void saveState() {
getSettings().setScanFilesBeforeCheckin(checkBox.isSelected());
}
public void restoreState() {
checkBox.setSelected(getSettings().isScanFilesBeforeCheckin());
}
};
}
/**
* Run Check if selected.
*
* @param commitExecutor commit executor
* @return ReturnResult
*/
public ReturnResult beforeCheckin(@Nullable final CommitExecutor commitExecutor) {
if (getSettings().isScanFilesBeforeCheckin()) {
final ResourceBundle resources = ResourceBundle.getBundle(
CheckStyleConstants.RESOURCE_BUNDLE);
try {
final Map<PsiFile, List<ProblemDescriptor>> scanResults
= new HashMap<PsiFile, List<ProblemDescriptor>>();
new Task.Modal(this.plugin.getProject(), resources.getString("handler.before.checkin.scan.text"), false) {
public void run(@NotNull final ProgressIndicator progressIndicator) {
progressIndicator.setText(resources.getString("handler.before.checkin.scan.in-progress"));
progressIndicator.setIndeterminate(true);
ScanFilesBeforeCheckinHandler.this.plugin.scanFiles(
new ArrayList<VirtualFile>(checkinPanel.getVirtualFiles()), scanResults);
}
}.queue();
if (!scanResults.isEmpty()) {
return processScanResults(scanResults, commitExecutor);
} else {
return ReturnResult.COMMIT;
}
}
catch (ProcessCanceledException e) {
return ReturnResult.CANCEL;
}
} else {
return ReturnResult.COMMIT;
}
}
/**
* Get plugin configuration.
*
* @return CheckStyleConfiguration plugin configuration
*/
private CheckStyleConfiguration getSettings() {
return this.plugin.getConfiguration();
}
/**
* Process scan results and allow user to decide what to do.
*
* @param results scan results.
* @param executor commit executor
* @return ReturnResult Users decision.
*/
private ReturnResult processScanResults(final Map<PsiFile, List<ProblemDescriptor>> results,
final CommitExecutor executor) {
int errorCount = results.keySet().size();
String commitButtonText;
if (executor != null) {
commitButtonText = executor.getActionText();
} else {
commitButtonText = checkinPanel.getCommitActionName();
}
if (commitButtonText.endsWith("...")) {
commitButtonText = commitButtonText.substring(0, commitButtonText.length() - 3);
}
final ResourceBundle resources = ResourceBundle.getBundle(
CheckStyleConstants.RESOURCE_BUNDLE);
final String[] buttons = new String[]{resources.getString("handler.before.checkin.error.review"),
commitButtonText, CommonBundle.getCancelButtonText()};
final MessageFormat errorFormat = new MessageFormat(resources.getString("handler.before.checkin.error.text"));
final int answer = Messages.showDialog(errorFormat.format(new Object[]{errorCount}),
resources.getString("handler.before.checkin.error.title"),
buttons, 0, UIUtil.getWarningIcon());
if (answer == 0) {
this.plugin.getToolWindowPanel().displayResults(results);
this.plugin.getToolWindowPanel().expandTree();
this.plugin.activeToolWindow(true);
return ReturnResult.CLOSE_WINDOW;
} else if (answer == 2 || answer == -1) {
return ReturnResult.CANCEL;
} else {
return ReturnResult.COMMIT;
}
}
}
| CedricGatay/Checkstyle-IDEA-no-logger-dependency | src/main/java/org/infernus/idea/checkstyle/handlers/ScanFilesBeforeCheckinHandler.java | Java | bsd-3-clause | 6,501 |
/**
*
*/
package org.knopflerfish.bundle.repository.expression; | knopflerfish/knopflerfish.org | osgi/bundles/repository/repository_xml/src/org/knopflerfish/bundle/repository/expression/package-info.java | Java | bsd-3-clause | 66 |
package org.sbml.libsbml;
/**
* Class for managing lists of {@link SBase} objects.
* <p>
* <em style='color: #555'>
* This class of objects is defined by libSBML only and has no direct
* equivalent in terms of SBML components.
* </em>
* <p>
* This class is necessary because of programming language differences
* between Java and the underlying C++ core of libSBML's implementation.
* It would of course be preferable to have a common list type for all
* lists returned by libSBML (e.g., lists of {@link SBase} objects, lists
* of {@link CVTerm} objects, etc.). However, this is currently impossible
* to achieve given the way the underlying C++ lists are implemented. (The
* basic problem concerns the lack of an equivalent to <code>void *</code>
* pointers in Java.)
* <p>
* As a result of this incompatibility, libSBML must implement the Java
* versions of the lists in another way. The approach taken is to
* define specialized list types for each kind of object that needs
* a list; that is, {@link SBaseList} for {@link SBase} objects,
* {@link CVTermList} for {@link CVTerm} objects, and a few others.
* These list objects provide the same kind of functionality that
* the underlying C++ generic lists provide (such as <code>get()</code>,
* <code>add()</code>, <code>remove()</code>, etc.), yet still
* maintain the strong data typing requiring by Java.
*/
public class SBaseList {
/**
* Explicit constructor for this list.
* <p>
* In most circumstances, callers will obtain an {@link SBaseList}
* object from a call to a libSBML method that returns the list.
* However, the constructor is provided in case callers need to
* construct the lists themselves.
* <p>
* @warning Note that the internal implementation of the list nodes uses
* C++ objects. If callers use this constructor to create the list
* object deliberately, those objects are in a sense "owned" by the caller
* when this constructor is used. Callers need to remember to call
* {@link #delete()} on this list object after it is no longer
* needed or risk leaking memory.
*/
public SBaseList() { }
/**
* Destructor for this list.
* <p>
* If a caller created this list using the {@link #SBaseList()}
* constructor, the caller should use this method to delete this list
* object after it is no longer in use.
*/
public synchronized void delete() { }
/**
* Adds the given {@link SBase} object <code>item</code> to this
* list.
* <p>
* @param item the {@link SBase} object to add to add
*/
public void add(SBase item) { }
/**
* Returns the <em>n</em>th SBase object from this list.
* <p>
* If the index number <code>n</code> is greater than the size of the list
* (as indicated by {@link #getSize()}), then this method returns
* <code>null</code>.
* <p>
* @param n the index number of the item to get, with indexing
* beginning at number <code>0</code>.
* <p>
* @return the nth item in this {@link SBaseList} items.
* <p>
* @see #getSize()
*/
public SBase get(long n) { }
/**
* Adds the {@link SBase} object <code>item</code> to the beginning
* of this list.
* <p>
* @param item a pointer to the item to be prepended.
* <p>
*/
public void prepend(SBase item) { }
/**
* Removes the <em>n</em>th {@link SBase} object from this list and
* returns it.
* <p>
* Callers can use {@link #getSize()} to find out the length of the list.
* If <code>n > </code>{@link #getSize()}, this method returns
* <code>null</code> and does not delete anything.
* <p>
* @param n the index number of the item to remove
* <p>
* @return the item indexed by <code>n</code>
* </p>
* @see #getSize()
*/
public SBase remove(long n) { }
/**
* Returns the number of items in this list.
* <p>
* @return the number of elements in this list.
*/
public long getSize() { }
}
| TheCoSMoCompany/biopredyn | Prototype/src/libsbml-5.10.0/docs/src/java-substitutions/SBaseList.java | Java | bsd-3-clause | 4,111 |
//*********************************************************************************************************************
// FuzzerComponent.java
//
// Copyright 2014 ELECTRIC POWER RESEARCH INSTITUTE, INC. All rights reserved.
//
// PT2 ("this software") is licensed under BSD 3-Clause license.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// • Redistributions of source code must retain the above copyright notice, this list of conditions and
// the following disclaimer.
//
// • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
// the following disclaimer in the documentation and/or other materials provided with the distribution.
//
// • Neither the name of the Electric Power Research Institute, Inc. (“EPRI”) nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL EPRI BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//
//*********************************************************************************************************************
//
// Code Modification History:
// -------------------------------------------------------------------------------------------------------------------
// 11/20/2012 - Tam T. Do, Southwest Research Institute (SwRI)
// Generated original version of source code.
// 10/22/2014 - Tam T. Do, Southwest Research Institute (SwRI)
// Added DNP3 software capabilities.
//*********************************************************************************************************************
//
package org.epri.pt2.fuzzer;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
/**
* Contains the FuzzerPanel component.
* @author Southwest Research Institute
*
*/
public class FuzzerComponent extends JPanel implements ChangeListener {
/**
*
*/
private static final long serialVersionUID = -6582031289147338163L;
protected RequestPanel requestPanel;
protected ResponsePanel responsePanel;
protected JTabbedPane tabbedPane;
protected JFrame parentFrame;
/**
*
*
*/
public FuzzerComponent() {
super();
initComponents();
}
private void initComponents() {
requestPanel = new RequestPanel();
responsePanel = new ResponsePanel();
tabbedPane = new JTabbedPane();
tabbedPane.add("Requests", requestPanel);
tabbedPane.add("Responses", responsePanel);
tabbedPane.addChangeListener(this);
setLayout(new MigLayout());
add(tabbedPane, "dock center");
}
public void stateChanged(ChangeEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource().equals(tabbedPane)) {
if(tabbedPane.getSelectedComponent().equals(requestPanel)) {
requestPanel.requestPacketTableModel.fireTableDataChanged();
} else if(tabbedPane.getSelectedComponent().equals(responsePanel)) {
responsePanel.responsePacketTableModel.fireTableDataChanged();
}
}
}
}
| epri-dev/PT2 | src/main/java/org/epri/pt2/fuzzer/FuzzerComponent.java | Java | bsd-3-clause | 3,914 |
package org.hamcrest.generator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.junit.Test;
public final class QDoxFactoryReaderTest {
@Test public void
extractsOriginalParameterNamesFromSource() {
FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType");
method.addParameter("java.lang.String", "badParamName");
String input = "" +
"package org;\n" +
"class SomeClass {\n" +
" @org.hamcrest.Factory" +
" public static Matcher someMethod(String realParamName) { ... } \n" +
"}\n";
FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input);
assertEquals("java.lang.String", factoryMethod.getParameters().get(0).getType());
assertEquals("realParamName", factoryMethod.getParameters().get(0).getName());
}
@Test public void
extractsOriginalGenericParameterNamesFromSource() {
FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType");
method.addParameter("java.util.Collection<java.lang.String>", "badParamName");
String input = "" +
"package org;\n" +
"class SomeClass {\n" +
" @org.hamcrest.Factory" +
" public static Matcher someMethod(java.util.Collection<String> realParamName) { ... } \n" +
"}\n";
FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input);
assertEquals("java.util.Collection<java.lang.String>", factoryMethod.getParameters().get(0).getType());
assertEquals("realParamName", factoryMethod.getParameters().get(0).getName());
}
@Test public void
extractsOriginalVarArgParameterNamesFromSource() {
FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType");
method.addParameter("java.lang.String...", "badParamName");
String input = "" +
"package org;\n" +
"class SomeClass {\n" +
" @org.hamcrest.Factory" +
" public static Matcher someMethod(java.lang.String... realParamName) { ... } \n" +
"}\n";
FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input);
assertEquals("java.lang.String...", factoryMethod.getParameters().get(0).getType());
assertEquals("realParamName", factoryMethod.getParameters().get(0).getName());
}
@Test public void
extractsOriginalJavaDocFromSource() {
FactoryMethod method = new FactoryMethod("org.SomeClass", "someMethod", "unusedReturnType");
String input = "" +
"package org;\n" +
"class SomeClass {\n" +
" /**\n" +
" * This class does something.\n" +
" *\n" +
" * @return stuff.\n" +
" */\n" +
" @org.hamcrest.Factory" +
" public static Matcher someMethod() { ... } \n" +
"}\n";
FactoryMethod factoryMethod = wrapUsingQDoxedSource(method, "org.SomeClass", input);
assertEquals("This class does something.\n\n@return stuff.\n",
factoryMethod.getJavaDoc());
}
@Test public void
iteratesOverFactoryMethods() throws FileNotFoundException {
final QDoxFactoryReader reader = readerForTestClass("SimpleSetOfMatchers");
final List<FactoryMethod> methods = methodsReadBy(reader);
assertEquals(2, methods.size());
final String expectedClass = "test.SimpleSetOfMatchers";
assertEquals("firstMethod", methods.get(0).getName());
assertEquals(expectedClass, methods.get(0).getMatcherClass());
assertEquals("secondMethod", methods.get(1).getName());
assertEquals(expectedClass, methods.get(1).getMatcherClass());
}
@Test public void
onlyReadsPublicStaticAnnotatedMethodsThatReturnNonVoid() throws FileNotFoundException {
final QDoxFactoryReader reader = readerForTestClass("MatchersWithDodgySignatures");
final List<FactoryMethod> methods = methodsReadBy(reader);
assertEquals(2, methods.size());
assertEquals("anotherGoodMethod", methods.get(0).getName());
assertEquals("goodMethod", methods.get(1).getName());
}
@Test public void
readsFullyQualifiedGenericType() throws FileNotFoundException {
FactoryMethod method = readMethod("GenerifiedMatchers", "generifiedType");
assertEquals("org.hamcrest.Matcher<java.util.Comparator<java.lang.String>>", method.getReturnType());
}
@Test public void
readsNullGenerifiedTypeIfNotPresent() throws FileNotFoundException {
FactoryMethod method = readMethod("GenerifiedMatchers", "noGenerifiedType");
assertEquals("org.hamcrest.Matcher", method.getReturnType());
}
@Test public void
readsGenericsInGenericType() throws FileNotFoundException {
FactoryMethod method = readMethod("GenerifiedMatchers", "crazyType");
assertEquals(
"org.hamcrest.Matcher<java.util.Map<? extends java.util.Set<java.lang.Long>,org.hamcrest.Factory>>",
method.getReturnType());
}
@Test public void
readsParameterTypes() throws FileNotFoundException {
FactoryMethod method = readMethod("ParameterizedMatchers", "withParam");
List<FactoryMethod.Parameter> params = method.getParameters();
assertEquals(3, params.size());
assertEquals("java.lang.String", params.get(0).getType());
assertEquals("int[]", params.get(1).getType());
assertEquals("java.util.Collection<java.lang.Object>", params.get(2).getType());
}
@Test public void
readsArrayAndVarArgParameterTypes() throws FileNotFoundException {
FactoryMethod arrayMethod = readMethod("ParameterizedMatchers", "withArray");
assertEquals("java.lang.String[]", arrayMethod.getParameters().get(0).getType());
FactoryMethod varArgsMethod = readMethod("ParameterizedMatchers", "withVarArgs");
assertEquals("java.lang.String...", varArgsMethod.getParameters().get(0).getType());
}
@Test public void
readsGenerifiedParameterTypes() throws FileNotFoundException {
FactoryMethod method = readMethod("ParameterizedMatchers", "withGenerifiedParam");
assertEquals("java.util.Collection<? extends java.lang.Comparable<java.lang.String>>",
method.getParameters().get(0).getType());
String expected = "java.util.Set<java.lang.String[]>[]";
assertEquals(expected, method.getParameters().get(1).getType());
}
@Test public void
canReadParameterNames() throws FileNotFoundException {
FactoryMethod method = readMethod("ParameterizedMatchers", "withParam");
List<FactoryMethod.Parameter> params = method.getParameters();
assertEquals("someString", params.get(0).getName());
assertEquals("numbers", params.get(1).getName());
assertEquals("things", params.get(2).getName());
}
@Test public void
readsExceptions() throws FileNotFoundException {
FactoryMethod method = readMethod("ExceptionalMatchers", "withExceptions");
List<String> exceptions = method.getExceptions();
assertEquals(3, exceptions.size());
assertEquals("java.lang.Error", exceptions.get(0));
assertEquals("java.io.IOException", exceptions.get(1));
assertEquals("java.lang.RuntimeException", exceptions.get(2));
}
@Test public void
canReadJavaDoc() throws FileNotFoundException {
FactoryMethod method = readMethod("WithJavaDoc", "documented");
assertEquals("Look at me!\n\n@return something\n", method.getJavaDoc());
}
@Test public void
readsGenericTypeParameters() throws FileNotFoundException {
FactoryMethod method = readMethod("G", "x");
assertEquals("T", method.getGenericTypeParameters().get(0));
assertEquals("V extends java.util.List<java.lang.String> & java.lang.Comparable<java.lang.String>",
method.getGenericTypeParameters().get(1));
assertEquals("org.hamcrest.Matcher<java.util.Map<T,V[]>>", method.getReturnType());
assertEquals("java.util.Set<T>", method.getParameters().get(0).getType());
assertEquals("V", method.getParameters().get(1).getType());
}
@Test public void
catchesSubclasses() throws FileNotFoundException {
assertNotNull(readMethod("SubclassOfMatcher", "subclassMethod"));
}
@Test public void
usesCorrectNameForNestedClasses() throws FileNotFoundException {
FactoryMethod method = readMethod("MatcherWithNestedClass", "firstMethod");
assertEquals("test.MatcherWithNestedClass.SpecificMatcher", method.getReturnType());
}
private static List<FactoryMethod> methodsReadBy(final Iterable<FactoryMethod> reader) {
final List<FactoryMethod> extractedMethods = new ArrayList<FactoryMethod>();
for (FactoryMethod factoryMethod : reader) {
extractedMethods.add(factoryMethod);
}
Collections.sort(extractedMethods, new Comparator<FactoryMethod>() {
@Override public int compare(FactoryMethod o1, FactoryMethod o2) {
return o1.getName().compareTo(o2.getName());
}
});
return extractedMethods;
}
private static QDoxFactoryReader readerForTestClass(String name)
throws FileNotFoundException {
QDox qdox = new QDox();
qdox.addSource(new FileReader("src/test/java-source/test/" + name + ".java"));
return new QDoxFactoryReader(qdox, "test." + name);
}
private static FactoryMethod readMethod(String name, String methodName) throws FileNotFoundException {
for (FactoryMethod method : readerForTestClass(name)) {
if (method.getName().equals(methodName)) {
return method;
}
}
return null;
}
private static FactoryMethod wrapUsingQDoxedSource(FactoryMethod originalMethod, String className, String input) {
List<FactoryMethod> originalMethods = new ArrayList<FactoryMethod>();
originalMethods.add(originalMethod);
QDox qdox = new QDox();
qdox.addSource(new StringReader(input));
QDoxFactoryReader qDoxFactoryReader = new QDoxFactoryReader(qdox, className);
return getFirstFactoryMethod(qDoxFactoryReader);
}
private static FactoryMethod getFirstFactoryMethod(QDoxFactoryReader qDoxFactoryReader) {
Iterator<FactoryMethod> iterator = qDoxFactoryReader.iterator();
assertTrue(iterator.hasNext());
return iterator.next();
}
}
| josephw/JavaHamcrest | hamcrest-generator/src/test/java/org/hamcrest/generator/QDoxFactoryReaderTest.java | Java | bsd-3-clause | 11,219 |
package serf.data;
import java.util.HashMap;
import java.util.Map;
public abstract class BasicMatcherMerger implements MatcherMerger {
protected RecordFactory _factory;
private long _matchCount = 0;
private long _mergeCount = 0;
private long _matchTime = 0;
private long _mergeTime = 0;
public BasicMatcherMerger() {
super();
}
public boolean match(Record r1, Record r2)
{
long startTime = System.currentTimeMillis();
boolean retval = false;
try
{
_matchCount++;
retval = matchInternal(r1, r2);
return retval;
}
finally
{
_matchTime += System.currentTimeMillis() - startTime;
}
}
protected boolean matchInternal(Record r1, Record r2)
{
return false;
}
public Record merge(Record r1, Record r2)
{
long startTime = System.currentTimeMillis();
try
{
_mergeCount++;
return mergeInternal(r1, r2);
}
finally
{
_mergeTime += System.currentTimeMillis() - startTime;
}
}
protected double calculateConfidence(double c1, double c2)
{
return c1*c2;
}
private Record mergeInternal(Record r1, Record r2)
{
// To guarantee idempotence
if (r1.equals(r2))
return r1;
// Otherwise, just multiply the confidences and
// union the attributes.
double conf = calculateConfidence(r1.getConfidence(), r2.getConfidence());
HashMap<String, Attribute> attrs = new HashMap<String, Attribute>();
attrs.putAll(r1.getAttributes());
for (Map.Entry<String, Attribute> entry : r2.getAttributes().entrySet())
{
String attrName = entry.getKey();
Attribute newAttr = entry.getValue();
Attribute oldAttr = attrs.get(attrName);
if (oldAttr == null)
{
attrs.put(attrName, newAttr);
}
else
{
Attribute mergedAttr = new Attribute(oldAttr.getType());
for (String val : oldAttr)
mergedAttr.addValue(val);
for (String val : newAttr)
mergedAttr.addValue(val);
attrs.put(attrName, mergedAttr);
}
}
return _factory.create(conf, attrs, r1, r2);
}
}
| trevorprater/serf | src/serf/data/BasicMatcherMerger.java | Java | bsd-3-clause | 2,006 |
/*
Copyright © dkms, artaround
*/
package dkms.service;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import kiwi.api.content.ContentItemService;
import kiwi.api.entity.KiWiEntityManager;
import kiwi.api.search.KiWiSearchCriteria;
import kiwi.api.search.KiWiSearchResults;
import kiwi.api.search.SolrService;
import kiwi.api.search.KiWiSearchResults.SearchResult;
import kiwi.api.triplestore.TripleStore;
import kiwi.model.Constants;
import kiwi.model.content.ContentItem;
import kiwi.model.user.User;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.log.Log;
import dkms.action.dkmsContentItem.DkmsBlogManager;
import dkms.action.dkmsContentItem.DkmsCombinedComponentManager;
import dkms.action.dkmsContentItem.DkmsContentItemBean;
import dkms.action.dkmsContentItem.DkmsFileManager;
import dkms.action.dkmsContentItem.DkmsMovieManager;
import dkms.action.dkmsContentItem.DkmsSequenceComponentManager;
import dkms.action.dkmsContentItem.DkmsSlideManager;
import dkms.action.dkmsContentItem.DkmsWikiManager;
import dkms.action.utils.DkmsLastSubmittedComparator;
import dkms.datamodel.dkmsContentItem.DkmsBlogFacade;
import dkms.datamodel.dkmsContentItem.DkmsCombinedComponentFacade;
import dkms.datamodel.dkmsContentItem.DkmsContentItemFacade;
import dkms.datamodel.dkmsContentItem.DkmsMovieFacade;
import dkms.datamodel.dkmsContentItem.DkmsMultimediaFacade;
import dkms.datamodel.dkmsContentItem.DkmsSequenceComponentFacade;
import dkms.datamodel.dkmsContentItem.DkmsSlideFacade;
import dkms.datamodel.dkmsContentItem.DkmsWikiFacade;
@Scope(ScopeType.STATELESS)
@Name("dkmsContentItemService")
@Transactional
@AutoCreate
public class DkmsContentItemService {
@In
private TripleStore tripleStore;
@In
private KiWiEntityManager kiwiEntityManager;
@In
private SolrService solrService;
@In(required = false)
private Comparator<DkmsContentItemFacade> comp;
@In(create = true)
private User currentUser;
@In
private ContentItemService contentItemService;
@Logger
private Log log;
public List<DkmsContentItemFacade> getAllDkmsContentItems(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setLimit(Integer.MAX_VALUE);
criteria.setSortField("modified");
List <DkmsContentItemFacade> allDkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
return allDkmsContentItems;
}
public List<DkmsContentItemFacade> getNewestDkmsContentItems(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setLimit(25);
criteria.setSortField("modified");
List <DkmsContentItemFacade> allDkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
return allDkmsContentItems;
}
/**
* This class <b>returns TrashedContentItems</b>
* @param no parameters
* @return returns TrashedContentItems by logged in user
*/
public List<DkmsContentItemFacade> getTrashedContentItems(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> trashedContentItems = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if ((cif.getTrashState() == true)){
trashedContentItems.add(cif);
}
}
return trashedContentItems;
}
/**
* This class <b>returns dkmsContentItems</b>
* @param no parameters
* @return returns dkmsContentItems by logged in user
*/
public List<DkmsContentItemFacade> getDkmsContentItems(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> dkmsContentItems = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItemList = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItemList){
if ((cif.getTrashState() == false)){
dkmsContentItems.add(cif);
}
}
return dkmsContentItems;
}
public List<DkmsContentItemFacade> getSimpleResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("1") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
public List<DkmsContentItemFacade> getSegmentedResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("2") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
public List<DkmsContentItemFacade> getUploadedResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("3") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
public List<DkmsContentItemFacade> getAllWikiResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("4") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
public List<DkmsContentItemFacade> getAllBlogResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("5") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
public List<DkmsContentItemFacade> getCombinedResources(){
KiWiSearchCriteria criteria = new KiWiSearchCriteria();
criteria.getTypes().add(tripleStore.createUriResource(Constants.DKMS_CORE + "DkmsContentItem").getKiwiIdentifier());
criteria.setPerson(currentUser.getLogin());
criteria.setLimit(Integer.MAX_VALUE);
List <DkmsContentItemFacade> simpleResources = new LinkedList<DkmsContentItemFacade>();
List <DkmsContentItemFacade> dkmsContentItems = getDkmsContentItemsWithCriteria(criteria);
for (DkmsContentItemFacade cif : dkmsContentItems){
if (cif.getDkmsContentItemType().equals("6") && (cif.getTrashState() == false)){
simpleResources.add(cif);
}
}
return simpleResources;
}
private List<DkmsContentItemFacade> getDkmsContentItemsWithCriteria(KiWiSearchCriteria criteria){
List <DkmsContentItemFacade> allDkmsContentItems = new LinkedList<DkmsContentItemFacade>();
KiWiSearchResults results = solrService.search(criteria);
//log.info("Number of DkmsContentItems: "+results.getResultCount());
for(SearchResult r : results.getResults()) {
if(r.getItem() != null) {
DkmsContentItemFacade i = kiwiEntityManager.createFacade(r.getItem(),
DkmsContentItemFacade.class);
//log.info("TimeStamp: #0", i.getCreated()+" "+i.getModified());
allDkmsContentItems.add(i);
}
}
//log.info(comp == null?"comp is null":"comp is not null");
if(comp == null){
comp = new DkmsLastSubmittedComparator();
}
Collections.sort(allDkmsContentItems,comp);
return allDkmsContentItems;
}
//updates an existing DkmsContentItem by values hold in a given DkmsContentItemBean
public void updateDkmsContentItem(DkmsContentItemFacade dkmsContentItemFacade, DkmsContentItemBean dkmsContentItemBean){
Date d = new Date();
dkmsContentItemFacade.setModified(d);
dkmsContentItemBean.setLastUpdate(d.toString());
createDkmsContentItem(dkmsContentItemBean, dkmsContentItemFacade);
}
//creates a new DkmsContentItem by values hold in a given DkmsContentItemBean
public DkmsContentItemFacade createDkmsContentItem(DkmsContentItemBean dkmsContentItemBean){
final ContentItem dkmsContentItemItem = contentItemService.createContentItem();
DkmsContentItemFacade dkmsContentItem = kiwiEntityManager.createFacade(dkmsContentItemItem, DkmsContentItemFacade.class);
return createDkmsContentItem(dkmsContentItemBean, dkmsContentItem);
}
/**
* @param dkmsContentItemBean
* @param dkmsContentItem
*/
private DkmsContentItemFacade createDkmsContentItem(DkmsContentItemBean dkmsContentItemBean, DkmsContentItemFacade dkmsContentItem) {
contentItemService.updateTitle(dkmsContentItem, dkmsContentItemBean.getDkmsContentItemName());
dkmsContentItem.setAuthor(currentUser);
dkmsContentItem.setDescription(dkmsContentItemBean.getDescription());
dkmsContentItem.setCommentText(dkmsContentItemBean.getCommentText());
dkmsContentItem.setPublicAccess(dkmsContentItemBean.getPublicAccess());
dkmsContentItem.setDkmsContentItemTextList(dkmsContentItemBean.getDkmsContentItemTextList());
dkmsContentItem.setTrashState(dkmsContentItemBean.getTrashState());
dkmsContentItem.setAuthorName(dkmsContentItemBean.getAuthorName());
dkmsContentItem.setExerciseSheetContent(dkmsContentItemBean.getExerciseSheetContent());
dkmsContentItem.setTaskContent(dkmsContentItemBean.getTaskContent());
dkmsContentItem.setTaskTitle(dkmsContentItemBean.getTaskTitle());
dkmsContentItem.setActiveTask(dkmsContentItemBean.getActiveTask());
dkmsContentItem.setSeqTaskState(dkmsContentItemBean.getSeqTaskState());
dkmsContentItem.setContentItemState(dkmsContentItemBean.getContentItemState());
dkmsContentItem.setLatitude(dkmsContentItemBean.getLatitude());
dkmsContentItem.setLongitude(dkmsContentItemBean.getLongitude());
dkmsContentItem.setDkmsContentItemType(dkmsContentItemBean.getDkmsContentItemType());
dkmsContentItem.setTmpContentItem(dkmsContentItemBean.getTmpContentItem());
dkmsContentItem.setContentItemStateBuffer(dkmsContentItemBean.getContentItemStateBuffer());
dkmsContentItem.setContentItemBuffer(dkmsContentItemBean.getContentItemBuffer());
dkmsContentItem.setContentItemIdentifier(dkmsContentItem.getKiwiIdentifier());
dkmsContentItem.setLastUpdate(new Date().toString());
LinkedList<DkmsFileManager> mTmp = dkmsContentItemBean.getDkmsMediaList();
LinkedList<DkmsMultimediaFacade> aml = new LinkedList<DkmsMultimediaFacade>();
if(mTmp != null){
for (DkmsFileManager mediaTmp : mTmp) {
//create all contentItems according to the values of mTmp
final ContentItem DkmsFileManager = contentItemService.createContentItem();
DkmsMultimediaFacade dkmsMedia = kiwiEntityManager.createFacade(DkmsFileManager, DkmsMultimediaFacade.class);
dkmsMedia.setFilename(mediaTmp.getFileName());
dkmsMedia.setMimeType(mediaTmp.getMimeType());
aml.add(dkmsMedia);
}
//Add MultimediaFacase to DkmsContentItemFacade
dkmsContentItem.setDkmsMediaList(aml);
}
LinkedList<DkmsWikiManager> wTmp = dkmsContentItemBean.getDkmsWikiList();
LinkedList<DkmsWikiFacade> wml = new LinkedList<DkmsWikiFacade>();
if(wTmp != null){
for (DkmsWikiManager wikiTmp : wTmp) {
//create all contentItems according to the values of wTmp
final ContentItem DkmsWikiManager = contentItemService.createContentItem();
DkmsWikiFacade dkmsWiki = kiwiEntityManager.createFacade(DkmsWikiManager, DkmsWikiFacade.class);
dkmsWiki.setWikiContent(wikiTmp.getWikiContent());
dkmsWiki.setVersion(wikiTmp.getVersion());
dkmsWiki.setWikiAuthor(wikiTmp.getWikiAuthor());
wml.add(dkmsWiki);
}
//Add WikiFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsWikiList(wml);
}
LinkedList<DkmsBlogManager> bTmp = dkmsContentItemBean.getDkmsCommentList();
LinkedList<DkmsBlogFacade> bml = new LinkedList<DkmsBlogFacade>();
if(bTmp != null){
for (DkmsBlogManager blogTmp : bTmp) {
//create all contentItems according to the values of wTmp
final ContentItem DkmsBlogManager = contentItemService.createContentItem();
DkmsBlogFacade dkmsBlog = kiwiEntityManager.createFacade(DkmsBlogManager, DkmsBlogFacade.class);
dkmsBlog.setCommentContent(blogTmp.getCommentContent());
dkmsBlog.setVersion(blogTmp.getVersion());
dkmsBlog.setCommentAuthor(blogTmp.getCommentAuthor());
bml.add(dkmsBlog);
}
//Add BlogFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsCommentList(bml);
}
LinkedList<DkmsSlideManager> slTmp = dkmsContentItemBean.getDkmsSlideList();
LinkedList<DkmsSlideFacade> slml = new LinkedList<DkmsSlideFacade>();
if(slTmp != null){
for (DkmsSlideManager slideTmp : slTmp) {
//create all contentItems according to the values of slTmp
final ContentItem DkmsSlideManager = contentItemService.createContentItem();
DkmsSlideFacade dkmsSlide = kiwiEntityManager.createFacade(DkmsSlideManager, DkmsSlideFacade.class);
dkmsSlide.setFilename(slideTmp.getFileName());
dkmsSlide.setMimeType(slideTmp.getMimeType());
slml.add(dkmsSlide);
}
//Add SlideFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsSlideList(slml);
}
LinkedList<DkmsMovieManager> mvTmp = dkmsContentItemBean.getDkmsMovieList();
LinkedList<DkmsMovieFacade> mvml = new LinkedList<DkmsMovieFacade>();
if(mvTmp != null){
for (DkmsMovieManager movieTmp : mvTmp) {
//create all contentItems according to the values of mTmp
final ContentItem DkmsMovieManager = contentItemService.createContentItem();
DkmsMovieFacade dkmsMovie = kiwiEntityManager.createFacade(DkmsMovieManager, DkmsMovieFacade.class);
dkmsMovie.setFilename(movieTmp.getFileName());
dkmsMovie.setMimeType(movieTmp.getMimeType());
mvml.add(dkmsMovie);
}
//Add MovieFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsMovieList(mvml);
}
LinkedList<DkmsSequenceComponentManager> scTmp = dkmsContentItemBean.getDkmsSequenceComponentList();
LinkedList<DkmsSequenceComponentFacade> scml = new LinkedList<DkmsSequenceComponentFacade>();
if(scTmp != null){
for (DkmsSequenceComponentManager sequenceComponentTmp : scTmp) {
//create all contentItems according to the values of scTmp
final ContentItem DkmsSequenceComponentManager = contentItemService.createContentItem();
DkmsSequenceComponentFacade dkmsSequenceComponent = kiwiEntityManager.createFacade(DkmsSequenceComponentManager, DkmsSequenceComponentFacade.class);
dkmsSequenceComponent.setTaskId(sequenceComponentTmp.getTaskId());
dkmsSequenceComponent.setTaskTitle(sequenceComponentTmp.getTaskTitle());
dkmsSequenceComponent.setSequenceContent(sequenceComponentTmp.getSequenceContent());
dkmsSequenceComponent.setVersion(sequenceComponentTmp.getVersion());
dkmsSequenceComponent.setViewStatus(sequenceComponentTmp.getViewStatus());
scml.add(dkmsSequenceComponent);
}
//Add SequenceComponentFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsSequenceComponentList(scml);
}
LinkedList<DkmsCombinedComponentManager> combTmp = dkmsContentItemBean.getDkmsCombinedComponentList();
LinkedList<DkmsCombinedComponentFacade> combml = new LinkedList<DkmsCombinedComponentFacade>();
if(combTmp != null){
for (DkmsCombinedComponentManager combinedComponentTmp : combTmp) {
//create all contentItems according to the values of combTmp
final ContentItem DkmsCombinedComponentManager = contentItemService.createContentItem();
DkmsCombinedComponentFacade dkmsCombinedComponent = kiwiEntityManager.createFacade(DkmsCombinedComponentManager, DkmsCombinedComponentFacade.class);
//dkmsCombinedComponent.setCombinedItem(combinedComponentTmp.getCombinedItem());
dkmsCombinedComponent.setCombinedItemId(combinedComponentTmp.getCombinedItemId());
dkmsCombinedComponent.setCombinedItemTitle(combinedComponentTmp.getCombinedItemTitle());
dkmsCombinedComponent.setCombinedItemType(combinedComponentTmp.getCombinedItemType());
combml.add(dkmsCombinedComponent);
}
//Add SequenceComponentFacade to DkmsContentItemFacade
dkmsContentItem.setDkmsCombinedComponentList(combml);
}
kiwiEntityManager.persist(dkmsContentItem);
return dkmsContentItem;
}
public void deleteMultimediaFromDkmsContentItem(DkmsContentItemFacade dkmsContentItem, DkmsFileManager pic){
LinkedList<DkmsMultimediaFacade> mf = dkmsContentItem.getDkmsMediaList();
for (DkmsMultimediaFacade dkmsMultimediaFacade : mf) {
if(dkmsMultimediaFacade.getFilename().equals(pic.getFileName())){
mf.remove(dkmsMultimediaFacade);
dkmsContentItem.setDkmsMediaList(mf);
kiwiEntityManager.remove(dkmsMultimediaFacade.getDelegate());
return;
}
}
}
public void deleteWikiContentFromDkmsContentItem(DkmsContentItemFacade dkmsContentItem, DkmsWikiManager wiki){
LinkedList<DkmsWikiFacade> wf = dkmsContentItem.getDkmsWikiList();
for (DkmsWikiFacade dkmsWikiFacade : wf) {
if(dkmsWikiFacade.getWikiContent().equals(wiki.getWikiContent())){
wf.remove(dkmsWikiFacade);
dkmsContentItem.setDkmsWikiList(wf);
kiwiEntityManager.remove(dkmsWikiFacade.getDelegate());
return;
}
}
}
public void deleteSlideFromDkmsContentItem(DkmsContentItemFacade dkmsContentItem, DkmsSlideManager slide){
LinkedList<DkmsSlideFacade> sf = dkmsContentItem.getDkmsSlideList();
for (DkmsSlideFacade dkmsSlideFacade : sf) {
if(dkmsSlideFacade.getFilename().equals(slide.getFileName())){
sf.remove(dkmsSlideFacade);
dkmsContentItem.setDkmsSlideList(sf);
kiwiEntityManager.remove(dkmsSlideFacade.getDelegate());
return;
}
}
}
public void deleteItemFromDkmsSequenceContentItem(DkmsContentItemFacade dkmsContentItem, DkmsSequenceComponentManager sequenceItem){
LinkedList<DkmsSequenceComponentFacade> seq = dkmsContentItem.getDkmsSequenceComponentList();
for (DkmsSequenceComponentFacade dkmsSequenceComponentFacade : seq) {
if(dkmsSequenceComponentFacade.getSequenceItem().equals(sequenceItem.getSequenceItem())){
seq.remove(dkmsSequenceComponentFacade);
dkmsContentItem.setDkmsSequenceComponentList(seq);
kiwiEntityManager.remove(dkmsSequenceComponentFacade.getDelegate());
return;
}
}
}
}
| fregaham/KiWi | extensions/edukms/src/dkms/service/DkmsContentItemService.java | Java | bsd-3-clause | 20,835 |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/speech/v1beta1/cloud_speech.proto
package com.google.cloud.speech.v1beta1;
/**
* <pre>
* Describes the progress of a long-running `AsyncRecognize` call. It is
* included in the `metadata` field of the `Operation` returned by the
* `GetOperation` call of the `google::longrunning::Operations` service.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1beta1.AsyncRecognizeMetadata}
*/
public final class AsyncRecognizeMetadata extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.cloud.speech.v1beta1.AsyncRecognizeMetadata)
AsyncRecognizeMetadataOrBuilder {
// Use AsyncRecognizeMetadata.newBuilder() to construct.
private AsyncRecognizeMetadata(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private AsyncRecognizeMetadata() {
progressPercent_ = 0;
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return com.google.protobuf.UnknownFieldSet.getDefaultInstance();
}
private AsyncRecognizeMetadata(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
int mutable_bitField0_ = 0;
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
default: {
if (!input.skipField(tag)) {
done = true;
}
break;
}
case 8: {
progressPercent_ = input.readInt32();
break;
}
case 18: {
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (startTime_ != null) {
subBuilder = startTime_.toBuilder();
}
startTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(startTime_);
startTime_ = subBuilder.buildPartial();
}
break;
}
case 26: {
com.google.protobuf.Timestamp.Builder subBuilder = null;
if (lastUpdateTime_ != null) {
subBuilder = lastUpdateTime_.toBuilder();
}
lastUpdateTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(lastUpdateTime_);
lastUpdateTime_ = subBuilder.buildPartial();
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.speech.v1beta1.SpeechProto.internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1beta1.SpeechProto.internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.class, com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.Builder.class);
}
public static final int PROGRESS_PERCENT_FIELD_NUMBER = 1;
private int progressPercent_;
/**
* <pre>
* Approximate percentage of audio processed thus far. Guaranteed to be 100
* when the audio is fully processed and the results are available.
* </pre>
*
* <code>optional int32 progress_percent = 1;</code>
*/
public int getProgressPercent() {
return progressPercent_;
}
public static final int START_TIME_FIELD_NUMBER = 2;
private com.google.protobuf.Timestamp startTime_;
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public boolean hasStartTime() {
return startTime_ != null;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.Timestamp getStartTime() {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
return getStartTime();
}
public static final int LAST_UPDATE_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp lastUpdateTime_;
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public boolean hasLastUpdateTime() {
return lastUpdateTime_ != null;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public com.google.protobuf.Timestamp getLastUpdateTime() {
return lastUpdateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdateTime_;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getLastUpdateTimeOrBuilder() {
return getLastUpdateTime();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (progressPercent_ != 0) {
output.writeInt32(1, progressPercent_);
}
if (startTime_ != null) {
output.writeMessage(2, getStartTime());
}
if (lastUpdateTime_ != null) {
output.writeMessage(3, getLastUpdateTime());
}
}
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (progressPercent_ != 0) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(1, progressPercent_);
}
if (startTime_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(2, getStartTime());
}
if (lastUpdateTime_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(3, getLastUpdateTime());
}
memoizedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata)) {
return super.equals(obj);
}
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata other = (com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata) obj;
boolean result = true;
result = result && (getProgressPercent()
== other.getProgressPercent());
result = result && (hasStartTime() == other.hasStartTime());
if (hasStartTime()) {
result = result && getStartTime()
.equals(other.getStartTime());
}
result = result && (hasLastUpdateTime() == other.hasLastUpdateTime());
if (hasLastUpdateTime()) {
result = result && getLastUpdateTime()
.equals(other.getLastUpdateTime());
}
return result;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
hash = (37 * hash) + PROGRESS_PERCENT_FIELD_NUMBER;
hash = (53 * hash) + getProgressPercent();
if (hasStartTime()) {
hash = (37 * hash) + START_TIME_FIELD_NUMBER;
hash = (53 * hash) + getStartTime().hashCode();
}
if (hasLastUpdateTime()) {
hash = (37 * hash) + LAST_UPDATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getLastUpdateTime().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Describes the progress of a long-running `AsyncRecognize` call. It is
* included in the `metadata` field of the `Operation` returned by the
* `GetOperation` call of the `google::longrunning::Operations` service.
* </pre>
*
* Protobuf type {@code google.cloud.speech.v1beta1.AsyncRecognizeMetadata}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.cloud.speech.v1beta1.AsyncRecognizeMetadata)
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadataOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.cloud.speech.v1beta1.SpeechProto.internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor;
}
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.speech.v1beta1.SpeechProto.internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.class, com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.Builder.class);
}
// Construct using com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
public Builder clear() {
super.clear();
progressPercent_ = 0;
if (startTimeBuilder_ == null) {
startTime_ = null;
} else {
startTime_ = null;
startTimeBuilder_ = null;
}
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = null;
} else {
lastUpdateTime_ = null;
lastUpdateTimeBuilder_ = null;
}
return this;
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.cloud.speech.v1beta1.SpeechProto.internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor;
}
public com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata getDefaultInstanceForType() {
return com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.getDefaultInstance();
}
public com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata build() {
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata buildPartial() {
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata result = new com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata(this);
result.progressPercent_ = progressPercent_;
if (startTimeBuilder_ == null) {
result.startTime_ = startTime_;
} else {
result.startTime_ = startTimeBuilder_.build();
}
if (lastUpdateTimeBuilder_ == null) {
result.lastUpdateTime_ = lastUpdateTime_;
} else {
result.lastUpdateTime_ = lastUpdateTimeBuilder_.build();
}
onBuilt();
return result;
}
public Builder clone() {
return (Builder) super.clone();
}
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.setField(field, value);
}
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return (Builder) super.clearField(field);
}
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return (Builder) super.clearOneof(oneof);
}
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, Object value) {
return (Builder) super.setRepeatedField(field, index, value);
}
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
Object value) {
return (Builder) super.addRepeatedField(field, value);
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata) {
return mergeFrom((com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata other) {
if (other == com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata.getDefaultInstance()) return this;
if (other.getProgressPercent() != 0) {
setProgressPercent(other.getProgressPercent());
}
if (other.hasStartTime()) {
mergeStartTime(other.getStartTime());
}
if (other.hasLastUpdateTime()) {
mergeLastUpdateTime(other.getLastUpdateTime());
}
onChanged();
return this;
}
public final boolean isInitialized() {
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int progressPercent_ ;
/**
* <pre>
* Approximate percentage of audio processed thus far. Guaranteed to be 100
* when the audio is fully processed and the results are available.
* </pre>
*
* <code>optional int32 progress_percent = 1;</code>
*/
public int getProgressPercent() {
return progressPercent_;
}
/**
* <pre>
* Approximate percentage of audio processed thus far. Guaranteed to be 100
* when the audio is fully processed and the results are available.
* </pre>
*
* <code>optional int32 progress_percent = 1;</code>
*/
public Builder setProgressPercent(int value) {
progressPercent_ = value;
onChanged();
return this;
}
/**
* <pre>
* Approximate percentage of audio processed thus far. Guaranteed to be 100
* when the audio is fully processed and the results are available.
* </pre>
*
* <code>optional int32 progress_percent = 1;</code>
*/
public Builder clearProgressPercent() {
progressPercent_ = 0;
onChanged();
return this;
}
private com.google.protobuf.Timestamp startTime_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> startTimeBuilder_;
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public boolean hasStartTime() {
return startTimeBuilder_ != null || startTime_ != null;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.Timestamp getStartTime() {
if (startTimeBuilder_ == null) {
return startTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
} else {
return startTimeBuilder_.getMessage();
}
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
startTime_ = value;
onChanged();
} else {
startTimeBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder setStartTime(
com.google.protobuf.Timestamp.Builder builderForValue) {
if (startTimeBuilder_ == null) {
startTime_ = builderForValue.build();
onChanged();
} else {
startTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder mergeStartTime(com.google.protobuf.Timestamp value) {
if (startTimeBuilder_ == null) {
if (startTime_ != null) {
startTime_ =
com.google.protobuf.Timestamp.newBuilder(startTime_).mergeFrom(value).buildPartial();
} else {
startTime_ = value;
}
onChanged();
} else {
startTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public Builder clearStartTime() {
if (startTimeBuilder_ == null) {
startTime_ = null;
onChanged();
} else {
startTime_ = null;
startTimeBuilder_ = null;
}
return this;
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.Timestamp.Builder getStartTimeBuilder() {
onChanged();
return getStartTimeFieldBuilder().getBuilder();
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
public com.google.protobuf.TimestampOrBuilder getStartTimeOrBuilder() {
if (startTimeBuilder_ != null) {
return startTimeBuilder_.getMessageOrBuilder();
} else {
return startTime_ == null ?
com.google.protobuf.Timestamp.getDefaultInstance() : startTime_;
}
}
/**
* <pre>
* Time when the request was received.
* </pre>
*
* <code>optional .google.protobuf.Timestamp start_time = 2;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>
getStartTimeFieldBuilder() {
if (startTimeBuilder_ == null) {
startTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>(
getStartTime(),
getParentForChildren(),
isClean());
startTime_ = null;
}
return startTimeBuilder_;
}
private com.google.protobuf.Timestamp lastUpdateTime_ = null;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> lastUpdateTimeBuilder_;
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public boolean hasLastUpdateTime() {
return lastUpdateTimeBuilder_ != null || lastUpdateTime_ != null;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public com.google.protobuf.Timestamp getLastUpdateTime() {
if (lastUpdateTimeBuilder_ == null) {
return lastUpdateTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdateTime_;
} else {
return lastUpdateTimeBuilder_.getMessage();
}
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public Builder setLastUpdateTime(com.google.protobuf.Timestamp value) {
if (lastUpdateTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
lastUpdateTime_ = value;
onChanged();
} else {
lastUpdateTimeBuilder_.setMessage(value);
}
return this;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public Builder setLastUpdateTime(
com.google.protobuf.Timestamp.Builder builderForValue) {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = builderForValue.build();
onChanged();
} else {
lastUpdateTimeBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public Builder mergeLastUpdateTime(com.google.protobuf.Timestamp value) {
if (lastUpdateTimeBuilder_ == null) {
if (lastUpdateTime_ != null) {
lastUpdateTime_ =
com.google.protobuf.Timestamp.newBuilder(lastUpdateTime_).mergeFrom(value).buildPartial();
} else {
lastUpdateTime_ = value;
}
onChanged();
} else {
lastUpdateTimeBuilder_.mergeFrom(value);
}
return this;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public Builder clearLastUpdateTime() {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTime_ = null;
onChanged();
} else {
lastUpdateTime_ = null;
lastUpdateTimeBuilder_ = null;
}
return this;
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getLastUpdateTimeBuilder() {
onChanged();
return getLastUpdateTimeFieldBuilder().getBuilder();
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getLastUpdateTimeOrBuilder() {
if (lastUpdateTimeBuilder_ != null) {
return lastUpdateTimeBuilder_.getMessageOrBuilder();
} else {
return lastUpdateTime_ == null ?
com.google.protobuf.Timestamp.getDefaultInstance() : lastUpdateTime_;
}
}
/**
* <pre>
* Time of the most recent processing update.
* </pre>
*
* <code>optional .google.protobuf.Timestamp last_update_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>
getLastUpdateTimeFieldBuilder() {
if (lastUpdateTimeBuilder_ == null) {
lastUpdateTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>(
getLastUpdateTime(),
getParentForChildren(),
isClean());
lastUpdateTime_ = null;
}
return lastUpdateTimeBuilder_;
}
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return this;
}
// @@protoc_insertion_point(builder_scope:google.cloud.speech.v1beta1.AsyncRecognizeMetadata)
}
// @@protoc_insertion_point(class_scope:google.cloud.speech.v1beta1.AsyncRecognizeMetadata)
private static final com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata();
}
public static com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<AsyncRecognizeMetadata>
PARSER = new com.google.protobuf.AbstractParser<AsyncRecognizeMetadata>() {
public AsyncRecognizeMetadata parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new AsyncRecognizeMetadata(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<AsyncRecognizeMetadata> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<AsyncRecognizeMetadata> getParserForType() {
return PARSER;
}
public com.google.cloud.speech.v1beta1.AsyncRecognizeMetadata getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| landrito/api-client-staging | generated/java/proto-google-cloud-speech-v1beta1/src/main/java/com/google/cloud/speech/v1beta1/AsyncRecognizeMetadata.java | Java | bsd-3-clause | 30,821 |
package frege.runtime;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class Javac {
final static String fregeJavac = System.getProperty("frege.javac");
final static JavaCompiler compiler =
fregeJavac == null || fregeJavac.startsWith("internal") ?
ToolProvider.getSystemJavaCompiler() : null;
final static StandardJavaFileManager fileManager =
compiler == null ? null : compiler.getStandardFileManager(null, null, null);
public static int runJavac(final String[] cmd) {
StringBuilder sb = new StringBuilder();
for (String s : cmd) { sb.append(s); sb.append(" "); }
if (compiler != null && fileManager != null) {
// use the internal compiler
File[] files = new File[] { new File(cmd[cmd.length-1]) };
String[] options = new String[cmd.length-2];
for (int i=0; i<options.length; i++) options[i] = cmd[i+1];
Iterable<? extends JavaFileObject> compilationUnits1 =
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files));
System.err.println("calling: " + sb.toString());
CompilationTask task = compiler.getTask(null,
fileManager, null,
Arrays.asList(options),
null, compilationUnits1);
boolean success = task.call();
try {
fileManager.flush();
} catch (IOException e) {
// what can we do here?
System.err.println(e.getMessage() + " while flushing javac file manager.");
return 1;
}
return success ? 0 : 1;
}
try {
// String cmd = "javac -cp " + cp + " -d " + d + " " + src;
int cex = 0;
System.err.println("running: " + sb.toString());
Process jp = java.lang.Runtime.getRuntime().exec(cmd);
// if (Common.verbose)
java.io.InputStream is = jp.getErrorStream();
while ((cex = is.read()) >= 0) {
System.err.write(cex);
}
if ((cex = jp.waitFor()) != 0) {
System.err.println("javac terminated with exit code " + cex);
}
return cex;
} catch (java.io.IOException e) {
System.err.println("Can't javac (" + e.getMessage() + ")");
} catch (InterruptedException e) {
System.err.println("Can't javac (" + e.getMessage() + ")");
}
return 1;
}
}
| mmhelloworld/frege | frege/runtime/Javac.java | Java | bsd-3-clause | 2,390 |
package br.odb.moonshot.parameterdefinitions;
import br.odb.gameapp.command.ApplicationData;
import br.odb.gameapp.command.CommandParameterDefinition;
import br.odb.gameapp.command.UserCommandLineAction;
/**
* Created by monty on 12/03/16.
*/
public class CommandNameParameterDefinition extends CommandParameterDefinition<UserCommandLineAction> {
public CommandNameParameterDefinition() {
super("command-name", "The short name for command needing explanation");
}
@Override
public UserCommandLineAction obtainFromArguments(String s, ApplicationData applicationData) {
return null;
}
}
| TheFakeMontyOnTheRun/level-editor-3d | level-editor-core-java/src/main/java/br/odb/moonshot/parameterdefinitions/CommandNameParameterDefinition.java | Java | bsd-3-clause | 599 |
/**
* BSD 3-Clause License
*
* Copyright (c) 2017, GOMOOB All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials provided with
* the distribution.
*
* * Neither the name of the copyright holder nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.gomoob.model;
/**
* Interface used to manage getter and setter of a `defaultLanguageCode` attribute on an entity.
*
* @author Simon BAUDRY ([email protected])
*/
public interface IDefaultLanguageCode {
/**
* Gets the language code which was used when the entity was created. In most cases this is the
* language which was used by the user who created the entity.
*
* <p>
* WARNING: The language code returned by this function is always expressed in uppercase even if
* you provided a language code to the entity using a lower case syntax. Internally translatable
* entities always store language codes in upper case.
* </p>
*
* @return The default language code, the returned string is compliant with the ISO639-1 standard.
*/
public String getDefaultLanguageCode();
/**
* Sets the language code which was used when the entity was created. In most cases this is the
* language which was used by the user who created the entity.
*
* <p>
* WARNING: The provided language code is not case sensitive, but, internally the language code
* which is used and stored is ALWAYS converted in uppercase.
* </p>
*
* @param defaultLanguageCode The default language code to set, this string must be compliant with
* the ISO639-1 standard.
*/
public void setDefaultLanguageCode(final String defaultLanguageCode);
}
| gomoob/java-model | src/main/java/org/gomoob/model/IDefaultLanguageCode.java | Java | bsd-3-clause | 2,980 |
package main.astraeus.net.channel.events;
import java.io.IOException;
import main.astraeus.net.channel.ChannelEvent;
import main.astraeus.net.channel.PlayerChannel;
import main.astraeus.net.packet.PacketHeader;
import main.astraeus.net.packet.PacketWriter;
public final class PrepareChannelEvent extends ChannelEvent {
/**
* The header for this message.
*/
private final PacketHeader header;
/**
* The buffer for this message.
*/
private final PacketWriter buffer;
/**
* The opcode for this message.
*/
private final int opcode;
/**
* Creates a new {@link PrepareChannelEvent} with a default {@code PacketHeader} of
* {@code EMPTY}.
*
* @param opcode The opcode for this message.
*
* @param header The header for this message.
*
* @param reader The buffer for this message.
*/
public PrepareChannelEvent(int opcode, PacketWriter reader) {
this(opcode, PacketHeader.EMPTY, reader);
}
/**
* Creates a new {@link PrepareChannelEvent}.
*
* @param opcode The opcode for this message.
*
* @param header The header for this message.
*
* @param buffer The buffer for this message.
*/
public PrepareChannelEvent(int opcode, PacketHeader header, PacketWriter buffer) {
this.opcode = opcode;
this.header = header;
this.buffer = buffer;
}
@Override
public void execute(PlayerChannel context) throws IOException {
/*
* If a packet does not have an empty heading then the opcode must be encrypted with a
* cryptographic cipher. After the encryption if the packet's heading is defined as a
* byte or a short the length must be indicated by that primitive.
*/
if (!header.equals(PacketHeader.EMPTY)) {
buffer.write(opcode + context.getPlayer().getIsaacRandomPair().getDecoder()
.getNextValue());
if (header.equals(PacketHeader.VARIABLE_BYTE)) {
buffer.setLength(buffer.getBuffer().position());
buffer.write(0);
} else if (header.equals(PacketHeader.VARIABLE_SHORT)) {
buffer.setLength(buffer.getBuffer().position());
buffer.writeShort(0);
}
}
}
}
| 7winds/Astraeus-Framework | src/main/astraeus/net/channel/events/PrepareChannelEvent.java | Java | isc | 2,610 |
package Game.ComputerFunctions;
import Game.*;
import Assignments.*;
/**
A function that is run within Computer.java.
Changes the port that a watch is pointing at.
*/
import java.util.*;
import Assignments.*;
import Hackscript.Model.*;
public class changeWatchPort extends function{
public changeWatchPort(Computer MyComputer){
super(MyComputer);
}
public void execute(ApplicationData MyApplicationData){
int target_watch=(Integer)((Integer[])MyApplicationData.getParameters())[0];
int new_port=(Integer)((Integer[])MyApplicationData.getParameters())[1];
WatchHandler MyWatchHandler=super.getComputer().getWatchHandler();
if(target_watch<MyWatchHandler.getWatches().size()){
Watch MyWatch=(Watch)MyWatchHandler.getWatch(target_watch);
MyWatch.setPort(new_port);
super.getComputer().getComputerHandler().addData(new ApplicationData("fetchwatches",null,0,super.getComputer().getIP()),super.getComputer().getIP());
}
}
}
| Demannu/hackwars-classic | src/classes/Game/ComputerFunctions/changeWatchPort.java | Java | isc | 952 |
package net.scapeemulator.game.msg.impl;
import net.scapeemulator.game.msg.Message;
public final class SequenceNumberMessage extends Message {
private final int sequenceNumber;
public SequenceNumberMessage(int sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
public int getSequenceNumber() {
return sequenceNumber;
}
}
| davidi2/mopar | src/net/scapeemulator/game/msg/impl/SequenceNumberMessage.java | Java | isc | 343 |
package com.raizlabs.android.dbflow.test.structure.join;
import com.raizlabs.android.dbflow.annotation.Column;
import com.raizlabs.android.dbflow.annotation.PrimaryKey;
import com.raizlabs.android.dbflow.annotation.Table;
import com.raizlabs.android.dbflow.structure.BaseModel;
import com.raizlabs.android.dbflow.test.TestDatabase;
/**
* Description: Taken from http://www.tutorialspoint.com/sqlite/sqlite_using_joins.htm
*/
@Table(database = TestDatabase.class)
public class Company extends BaseModel {
@Column
@PrimaryKey
long id;
@Column
String name;
@Column
int age;
@Column
String address;
@Column
double salary;
}
| janzoner/DBFlow | dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/structure/join/Company.java | Java | mit | 673 |
package org.andengine.engine.handler.collision;
import java.util.ArrayList;
import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.shape.IShape;
import org.andengine.util.adt.list.ListUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:19:35 - 11.03.2010
*/
public class CollisionHandler implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final ICollisionCallback mCollisionCallback;
private final IShape mCheckShape;
private final ArrayList<? extends IShape> mTargetStaticEntities;
// ===========================================================
// Constructors
// ===========================================================
public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final IShape pTargetShape) throws IllegalArgumentException {
this(pCollisionCallback, pCheckShape, ListUtils.toList(pTargetShape));
}
public CollisionHandler(final ICollisionCallback pCollisionCallback, final IShape pCheckShape, final ArrayList<? extends IShape> pTargetStaticEntities) throws IllegalArgumentException {
if (pCollisionCallback == null) {
throw new IllegalArgumentException( "pCollisionCallback must not be null!");
}
if (pCheckShape == null) {
throw new IllegalArgumentException( "pCheckShape must not be null!");
}
if (pTargetStaticEntities == null) {
throw new IllegalArgumentException( "pTargetStaticEntities must not be null!");
}
this.mCollisionCallback = pCollisionCallback;
this.mCheckShape = pCheckShape;
this.mTargetStaticEntities = pTargetStaticEntities;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
final IShape checkShape = this.mCheckShape;
final ArrayList<? extends IShape> staticEntities = this.mTargetStaticEntities;
final int staticEntityCount = staticEntities.size();
for(int i = 0; i < staticEntityCount; i++){
if(checkShape.collidesWith(staticEntities.get(i))){
final boolean proceed = this.mCollisionCallback.onCollision(checkShape, staticEntities.get(i));
if(!proceed) {
return;
}
}
}
}
@Override
public void reset() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| alexbuicescu/AndEngine-Android-Studio-Template | andEngine/src/main/java/org/andengine/engine/handler/collision/CollisionHandler.java | Java | mit | 3,152 |
/**
* Logback: the reliable, generic, fast and flexible logging framework.
* Copyright (C) 1999-2015, QOS.ch. All rights reserved.
*
* This program and the accompanying materials are dual-licensed under
* either the terms of the Eclipse Public License v1.0 as published by
* the Eclipse Foundation
*
* or (per the licensee's choosing)
*
* under the terms of the GNU Lesser General Public License version 2.1
* as published by the Free Software Foundation.
*/
package ch.qos.logback.core.recovery;
import java.io.*;
import java.nio.channels.FileChannel;
public class ResilientFileOutputStream extends ResilientOutputStreamBase {
private File file;
private FileOutputStream fos;
public ResilientFileOutputStream(File file, boolean append, long bufferSize) throws FileNotFoundException {
this.file = file;
fos = new FileOutputStream(file, append);
this.os = new BufferedOutputStream(fos, (int) bufferSize);
this.presumedClean = true;
}
public FileChannel getChannel() {
if (os == null) {
return null;
}
return fos.getChannel();
}
public File getFile() {
return file;
}
@Override
String getDescription() {
return "file [" + file + "]";
}
@Override
OutputStream openNewOutputStream() throws IOException {
// see LOGBACK-765
fos = new FileOutputStream(file, true);
return new BufferedOutputStream(fos);
}
@Override
public String toString() {
return "c.q.l.c.recovery.ResilientFileOutputStream@" + System.identityHashCode(this);
}
}
| JPAT-ROSEMARY/SCUBA | org.jpat.scuba.external.slf4j/logback-1.2.3/logback-core/src/main/java/ch/qos/logback/core/recovery/ResilientFileOutputStream.java | Java | mit | 1,693 |
/*
* Copyright (c) 2009 QOS.ch All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package ch.qos.cal10n.util;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.concurrent.ConcurrentHashMap;
/**
*
* @author Ceki Gülcü
*
*/
public class CAL10NBundle extends ResourceBundle {
static long CHECK_DELAY = 10 * 60 * 1000; // 10 minutes delay
Map<String, String> map = new ConcurrentHashMap<String, String>();
File hostFile;
volatile long nextCheck;
long lastModified;
CAL10NBundle parent;
public CAL10NBundle(Reader r, File file)
throws IOException {
read(r);
this.hostFile = file;
nextCheck = System.currentTimeMillis() + CHECK_DELAY;
}
void read(Reader r) throws IOException {
Parser p = new Parser(r, map);
p.parseAndPopulate();
}
public void setParent(CAL10NBundle parent) {
this.parent = (parent);
}
public boolean hasChanged() {
// if the host file is unknown, no point in a check
if (hostFile == null) {
return false;
}
long now = System.currentTimeMillis();
if (now < nextCheck) {
return false;
} else {
nextCheck = now + CHECK_DELAY;
if (lastModified != hostFile.lastModified()) {
lastModified = hostFile.lastModified();
return true;
} else {
return false;
}
}
}
/**
* WARNING: Used for testing purposes. Do not invoke directly in user code.
*/
public void resetCheckTimes() {
nextCheck = 0;
lastModified = 0;
}
@Override
public Enumeration<String> getKeys() {
Hashtable<String, String> ht = new Hashtable<String, String>(map);
if(parent != null) {
ht.putAll(parent.map);
}
return ht.keys();
}
@Override
protected Object handleGetObject(String key) {
if (key == null) {
throw new NullPointerException();
}
Object o = map.get(key);
if(o == null && parent != null) {
o = parent.handleGetObject(key);
}
return o;
}
}
| qos-ch/cal10n | cal10n-api/src/main/java/ch/qos/cal10n/util/CAL10NBundle.java | Java | mit | 3,189 |
package com.microsoft.bingads.reporting;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ProductTargetPerformanceReportColumn.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ProductTargetPerformanceReportColumn">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="AccountName"/>
* <enumeration value="AccountNumber"/>
* <enumeration value="AccountId"/>
* <enumeration value="TimePeriod"/>
* <enumeration value="CampaignName"/>
* <enumeration value="CampaignId"/>
* <enumeration value="AdGroupName"/>
* <enumeration value="AdGroupId"/>
* <enumeration value="ProductTarget"/>
* <enumeration value="AdGroupCriterionId"/>
* <enumeration value="AdId"/>
* <enumeration value="CurrentMaxCpc"/>
* <enumeration value="CurrencyCode"/>
* <enumeration value="Impressions"/>
* <enumeration value="Clicks"/>
* <enumeration value="Ctr"/>
* <enumeration value="AverageCpc"/>
* <enumeration value="Spend"/>
* <enumeration value="Conversions"/>
* <enumeration value="ConversionRate"/>
* <enumeration value="CostPerConversion"/>
* <enumeration value="DeviceType"/>
* <enumeration value="Language"/>
* <enumeration value="CampaignStatus"/>
* <enumeration value="AccountStatus"/>
* <enumeration value="AdGroupStatus"/>
* <enumeration value="KeywordStatus"/>
* <enumeration value="DestinationUrl"/>
* <enumeration value="BidMatchType"/>
* <enumeration value="DeliveredMatchType"/>
* <enumeration value="Network"/>
* <enumeration value="TopVsOther"/>
* <enumeration value="DeviceOS"/>
* <enumeration value="Assists"/>
* <enumeration value="ExtendedCost"/>
* <enumeration value="Revenue"/>
* <enumeration value="ReturnOnAdSpend"/>
* <enumeration value="CostPerAssist"/>
* <enumeration value="RevenuePerConversion"/>
* <enumeration value="RevenuePerAssist"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ProductTargetPerformanceReportColumn")
@XmlEnum
public enum ProductTargetPerformanceReportColumn {
@XmlEnumValue("AccountName")
ACCOUNT_NAME("AccountName"),
@XmlEnumValue("AccountNumber")
ACCOUNT_NUMBER("AccountNumber"),
@XmlEnumValue("AccountId")
ACCOUNT_ID("AccountId"),
@XmlEnumValue("TimePeriod")
TIME_PERIOD("TimePeriod"),
@XmlEnumValue("CampaignName")
CAMPAIGN_NAME("CampaignName"),
@XmlEnumValue("CampaignId")
CAMPAIGN_ID("CampaignId"),
@XmlEnumValue("AdGroupName")
AD_GROUP_NAME("AdGroupName"),
@XmlEnumValue("AdGroupId")
AD_GROUP_ID("AdGroupId"),
@XmlEnumValue("ProductTarget")
PRODUCT_TARGET("ProductTarget"),
@XmlEnumValue("AdGroupCriterionId")
AD_GROUP_CRITERION_ID("AdGroupCriterionId"),
@XmlEnumValue("AdId")
AD_ID("AdId"),
@XmlEnumValue("CurrentMaxCpc")
CURRENT_MAX_CPC("CurrentMaxCpc"),
@XmlEnumValue("CurrencyCode")
CURRENCY_CODE("CurrencyCode"),
@XmlEnumValue("Impressions")
IMPRESSIONS("Impressions"),
@XmlEnumValue("Clicks")
CLICKS("Clicks"),
@XmlEnumValue("Ctr")
CTR("Ctr"),
@XmlEnumValue("AverageCpc")
AVERAGE_CPC("AverageCpc"),
@XmlEnumValue("Spend")
SPEND("Spend"),
@XmlEnumValue("Conversions")
CONVERSIONS("Conversions"),
@XmlEnumValue("ConversionRate")
CONVERSION_RATE("ConversionRate"),
@XmlEnumValue("CostPerConversion")
COST_PER_CONVERSION("CostPerConversion"),
@XmlEnumValue("DeviceType")
DEVICE_TYPE("DeviceType"),
@XmlEnumValue("Language")
LANGUAGE("Language"),
@XmlEnumValue("CampaignStatus")
CAMPAIGN_STATUS("CampaignStatus"),
@XmlEnumValue("AccountStatus")
ACCOUNT_STATUS("AccountStatus"),
@XmlEnumValue("AdGroupStatus")
AD_GROUP_STATUS("AdGroupStatus"),
@XmlEnumValue("KeywordStatus")
KEYWORD_STATUS("KeywordStatus"),
@XmlEnumValue("DestinationUrl")
DESTINATION_URL("DestinationUrl"),
@XmlEnumValue("BidMatchType")
BID_MATCH_TYPE("BidMatchType"),
@XmlEnumValue("DeliveredMatchType")
DELIVERED_MATCH_TYPE("DeliveredMatchType"),
@XmlEnumValue("Network")
NETWORK("Network"),
@XmlEnumValue("TopVsOther")
TOP_VS_OTHER("TopVsOther"),
@XmlEnumValue("DeviceOS")
DEVICE_OS("DeviceOS"),
@XmlEnumValue("Assists")
ASSISTS("Assists"),
@XmlEnumValue("ExtendedCost")
EXTENDED_COST("ExtendedCost"),
@XmlEnumValue("Revenue")
REVENUE("Revenue"),
@XmlEnumValue("ReturnOnAdSpend")
RETURN_ON_AD_SPEND("ReturnOnAdSpend"),
@XmlEnumValue("CostPerAssist")
COST_PER_ASSIST("CostPerAssist"),
@XmlEnumValue("RevenuePerConversion")
REVENUE_PER_CONVERSION("RevenuePerConversion"),
@XmlEnumValue("RevenuePerAssist")
REVENUE_PER_ASSIST("RevenuePerAssist");
private final String value;
ProductTargetPerformanceReportColumn(String v) {
value = v;
}
public String value() {
return value;
}
public static ProductTargetPerformanceReportColumn fromValue(String v) {
for (ProductTargetPerformanceReportColumn c: ProductTargetPerformanceReportColumn.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| JeffRisberg/BING01 | proxies/com/microsoft/bingads/reporting/ProductTargetPerformanceReportColumn.java | Java | mit | 5,651 |
/**
*/
package gluemodel.CIM.IEC61970.Informative.InfCore;
import gluemodel.CIM.IEC61970.Core.IdentifiedObject;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Modeling Authority Set</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link gluemodel.CIM.IEC61970.Informative.InfCore.ModelingAuthoritySet#getIdentifiedObjects <em>Identified Objects</em>}</li>
* <li>{@link gluemodel.CIM.IEC61970.Informative.InfCore.ModelingAuthoritySet#getModelingAuthority <em>Modeling Authority</em>}</li>
* </ul>
*
* @see gluemodel.CIM.IEC61970.Informative.InfCore.InfCorePackage#getModelingAuthoritySet()
* @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A Modeling Authority Set is a group of objects in a network model where the data is supplied and maintained by the same Modeling Authority.'"
* annotation="http://langdale.com.au/2005/UML Profile\040documentation='A Modeling Authority Set is a group of objects in a network model where the data is supplied and maintained by the same Modeling Authority.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A Modeling Authority Set is a group of objects in a network model where the data is supplied and maintained by the same Modeling Authority.' Profile\040documentation='A Modeling Authority Set is a group of objects in a network model where the data is supplied and maintained by the same Modeling Authority.'"
* @generated
*/
public interface ModelingAuthoritySet extends IdentifiedObject {
/**
* Returns the value of the '<em><b>Identified Objects</b></em>' reference list.
* The list contents are of type {@link gluemodel.CIM.IEC61970.Core.IdentifiedObject}.
* It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Core.IdentifiedObject#getModelingAuthoritySet <em>Modeling Authority Set</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Identified Objects</em>' reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Identified Objects</em>' reference list.
* @see gluemodel.CIM.IEC61970.Informative.InfCore.InfCorePackage#getModelingAuthoritySet_IdentifiedObjects()
* @see gluemodel.CIM.IEC61970.Core.IdentifiedObject#getModelingAuthoritySet
* @model opposite="ModelingAuthoritySet"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='An IdentifiedObject belongs to a Modeling Authority Set for purposes of defining a group of data maintained by the same Modeling Authority.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='An IdentifiedObject belongs to a Modeling Authority Set for purposes of defining a group of data maintained by the same Modeling Authority.'"
* @generated
*/
EList<IdentifiedObject> getIdentifiedObjects();
/**
* Returns the value of the '<em><b>Modeling Authority</b></em>' reference.
* It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.InfCore.ModelingAuthority#getModelingAuthoritySets <em>Modeling Authority Sets</em>}'.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Modeling Authority</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Modeling Authority</em>' reference.
* @see #setModelingAuthority(ModelingAuthority)
* @see gluemodel.CIM.IEC61970.Informative.InfCore.InfCorePackage#getModelingAuthoritySet_ModelingAuthority()
* @see gluemodel.CIM.IEC61970.Informative.InfCore.ModelingAuthority#getModelingAuthoritySets
* @model opposite="ModelingAuthoritySets"
* annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A Modeling Authority set supplies and maintains the data for the objects in a Modeling Authority Set.'"
* annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A Modeling Authority set supplies and maintains the data for the objects in a Modeling Authority Set.'"
* @generated
*/
ModelingAuthority getModelingAuthority();
/**
* Sets the value of the '{@link gluemodel.CIM.IEC61970.Informative.InfCore.ModelingAuthoritySet#getModelingAuthority <em>Modeling Authority</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Modeling Authority</em>' reference.
* @see #getModelingAuthority()
* @generated
*/
void setModelingAuthority(ModelingAuthority value);
} // ModelingAuthoritySet
| georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/InfCore/ModelingAuthoritySet.java | Java | mit | 4,705 |
/*
* 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.commons.codec.binary;
import java.io.OutputStream;
/**
* Provides Base32 encoding and decoding in a streaming fashion (unlimited size). When encoding the default lineLength
* is 76 characters and the default lineEnding is CRLF, but these can be overridden by using the appropriate
* constructor.
* <p>
* The default behaviour of the Base32OutputStream is to ENCODE, whereas the default behaviour of the Base32InputStream
* is to DECODE. But this behaviour can be overridden by using a different constructor.
* </p>
* <p>
* Since this class operates directly on byte streams, and not character streams, it is hard-coded to only encode/decode
* character encodings which are compatible with the lower 127 ASCII chart (ISO-8859-1, Windows-1252, UTF-8, etc).
* </p>
*
* @version $Revision: 1157192 $
* @see <a href="http://www.ietf.org/rfc/rfc4648.txt">RFC 4648</a>
* @since 1.5
*/
public class Base32OutputStream extends BaseNCodecOutputStream {
/**
* Creates a Base32OutputStream such that all data written is Base32-encoded to the original provided OutputStream.
*
* @param out
* OutputStream to wrap.
*/
public Base32OutputStream(OutputStream out) {
this(out, true);
}
/**
* Creates a Base32OutputStream such that all data written is either Base32-encoded or Base32-decoded to the
* original provided OutputStream.
*
* @param out
* OutputStream to wrap.
* @param doEncode
* true if we should encode all data written to us, false if we should decode.
*/
public Base32OutputStream(OutputStream out, boolean doEncode) {
super(out, new Base32(false), doEncode);
}
/**
* Creates a Base32OutputStream such that all data written is either Base32-encoded or Base32-decoded to the
* original provided OutputStream.
*
* @param out
* OutputStream to wrap.
* @param doEncode
* true if we should encode all data written to us, false if we should decode.
* @param lineLength
* If doEncode is true, each line of encoded data will contain lineLength characters (rounded down to
* nearest multiple of 4). If lineLength <=0, the encoded data is not divided into lines. If doEncode is
* false, lineLength is ignored.
* @param lineSeparator
* If doEncode is true, each line of encoded data will be terminated with this byte sequence (e.g. \r\n).
* If lineLength <= 0, the lineSeparator is not used. If doEncode is false lineSeparator is ignored.
*/
public Base32OutputStream(OutputStream out, boolean doEncode, int lineLength, byte[] lineSeparator) {
super(out, new Base32(lineLength, lineSeparator), doEncode);
}
}
| renepreuss/P2P-Client | src/org/apache/commons/codec/binary/Base32OutputStream.java | Java | mit | 3,741 |
package net.oschina.app.bean;
import java.io.Serializable;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
/**
* 帖子实体类
*
* @author FireAnt(http://my.oschina.net/LittleDY)
* @created 2014年10月9日 下午6:02:47
*
*/
@SuppressWarnings("serial")
@XStreamAlias("post")
public class Post extends Entity {
public final static int CATALOG_ASK = 1;
public final static int CATALOG_SHARE = 2;
public final static int CATALOG_OTHER = 3;
public final static int CATALOG_JOB = 4;
public final static int CATALOG_SITE = 5;
@XStreamAlias("title")
private String title;
@XStreamAlias("portrait")
private String portrait;
@XStreamAlias("url")
private String url;
@XStreamAlias("body")
private String body;
@XStreamAlias("author")
private String author;
@XStreamAlias("authorid")
private int authorId;
@XStreamAlias("answerCount")
private int answerCount;
@XStreamAlias("viewCount")
private int viewCount;
@XStreamAlias("pubDate")
private String pubDate;
@XStreamAlias("catalog")
private int catalog;
@XStreamAlias("isnoticeme")
private int isNoticeMe;
@XStreamAlias("favorite")
private int favorite;
@XStreamAlias("tags")
private Tags tags;
@XStreamAlias("answer")
private Answer answer;
@XStreamAlias("event")
private Event event;
public Event getEvent() {
return event;
}
public void setEvent(Event event) {
this.event = event;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPortrait() {
return portrait;
}
public void setPortrait(String portrait) {
this.portrait = portrait;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getAuthorId() {
return authorId;
}
public void setAuthorId(int authorId) {
this.authorId = authorId;
}
public int getAnswerCount() {
return answerCount;
}
public void setAnswerCount(int answerCount) {
this.answerCount = answerCount;
}
public int getViewCount() {
return viewCount;
}
public void setViewCount(int viewCount) {
this.viewCount = viewCount;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public int getCatalog() {
return catalog;
}
public void setCatalog(int catalog) {
this.catalog = catalog;
}
public int getIsNoticeMe() {
return isNoticeMe;
}
public void setIsNoticeMe(int isNoticeMe) {
this.isNoticeMe = isNoticeMe;
}
public int getFavorite() {
return favorite;
}
public void setFavorite(int favorite) {
this.favorite = favorite;
}
public Post.Tags getTags() {
return tags;
}
public void setTags(Tags tags) {
this.tags = tags;
}
public Answer getAnswer() {
return answer;
}
public void setAnswer(Answer answer) {
this.answer = answer;
}
@XStreamAlias("answer")
public class Answer implements Serializable {
@XStreamAlias("name")
private String name;
@XStreamAlias("time")
private String time;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public class Tags implements Serializable {
@XStreamImplicit(itemFieldName="tag")
private List<String> tags;
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
}
}
| vito-kong/oschina | android-app/app/src/main/java/net/oschina/app/bean/Post.java | Java | mit | 3,839 |
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Alan Harder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.mapper.AnnotationMapper;
import com.thoughtworks.xstream.mapper.Mapper;
import com.thoughtworks.xstream.mapper.MapperWrapper;
import com.thoughtworks.xstream.converters.ConversionException;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.ConverterMatcher;
import com.thoughtworks.xstream.converters.DataHolder;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.SingleValueConverterWrapper;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.converters.extended.DynamicProxyConverter;
import com.thoughtworks.xstream.core.JVM;
import com.thoughtworks.xstream.io.HierarchicalStreamDriver;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.mapper.CannotResolveClassException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.PluginManager;
import hudson.PluginWrapper;
import hudson.diagnosis.OldDataMonitor;
import hudson.remoting.ClassFilter;
import hudson.util.xstream.ImmutableSetConverter;
import hudson.util.xstream.ImmutableSortedSetConverter;
import jenkins.model.Jenkins;
import hudson.model.Label;
import hudson.model.Result;
import hudson.model.Saveable;
import hudson.util.xstream.ImmutableListConverter;
import hudson.util.xstream.ImmutableMapConverter;
import hudson.util.xstream.MapperDelegate;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.CheckForNull;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
/**
* {@link XStream} enhanced for additional Java5 support and improved robustness.
* @author Kohsuke Kawaguchi
*/
public class XStream2 extends XStream {
private RobustReflectionConverter reflectionConverter;
private final ThreadLocal<Boolean> oldData = new ThreadLocal<Boolean>();
private final @CheckForNull ClassOwnership classOwnership;
private final Map<String,Class<?>> compatibilityAliases = new ConcurrentHashMap<String, Class<?>>();
/**
* Hook to insert {@link Mapper}s after they are created.
*/
private MapperInjectionPoint mapperInjectionPoint;
public XStream2() {
init();
classOwnership = null;
}
public XStream2(HierarchicalStreamDriver hierarchicalStreamDriver) {
super(hierarchicalStreamDriver);
init();
classOwnership = null;
}
XStream2(ClassOwnership classOwnership) {
init();
this.classOwnership = classOwnership;
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, Object root, DataHolder dataHolder) {
// init() is too early to do this
// defensive because some use of XStream happens before plugins are initialized.
Jenkins h = Jenkins.getInstanceOrNull();
if(h!=null && h.pluginManager!=null && h.pluginManager.uberClassLoader!=null) {
setClassLoader(h.pluginManager.uberClassLoader);
}
Object o = super.unmarshal(reader,root,dataHolder);
if (oldData.get()!=null) {
oldData.remove();
if (o instanceof Saveable) OldDataMonitor.report((Saveable)o, "1.106");
}
return o;
}
@Override
protected Converter createDefaultConverter() {
// replace default reflection converter
reflectionConverter = new RobustReflectionConverter(getMapper(),new JVM().bestReflectionProvider(), new PluginClassOwnership());
return reflectionConverter;
}
/**
* Specifies that a given field of a given class should not be treated with laxity by {@link RobustCollectionConverter}.
* @param clazz a class which we expect to hold a non-{@code transient} field
* @param field a field name in that class
* @since TODO
*/
public void addCriticalField(Class<?> clazz, String field) {
reflectionConverter.addCriticalField(clazz, field);
}
static String trimVersion(String version) {
// TODO seems like there should be some trick with VersionNumber to do this
return version.replaceFirst(" .+$", "");
}
private void init() {
// list up types that should be marshalled out like a value, without referential integrity tracking.
addImmutableType(Result.class);
// http://www.openwall.com/lists/oss-security/2017/04/03/4
denyTypes(new Class[] { void.class, Void.class });
registerConverter(new RobustCollectionConverter(getMapper(),getReflectionProvider()),10);
registerConverter(new RobustMapConverter(getMapper()), 10);
registerConverter(new ImmutableMapConverter(getMapper(),getReflectionProvider()),10);
registerConverter(new ImmutableSortedSetConverter(getMapper(),getReflectionProvider()),10);
registerConverter(new ImmutableSetConverter(getMapper(),getReflectionProvider()),10);
registerConverter(new ImmutableListConverter(getMapper(),getReflectionProvider()),10);
registerConverter(new CopyOnWriteMap.Tree.ConverterImpl(getMapper()),10); // needs to override MapConverter
registerConverter(new DescribableList.ConverterImpl(getMapper()),10); // explicitly added to handle subtypes
registerConverter(new Label.ConverterImpl(),10);
// this should come after all the XStream's default simpler converters,
// but before reflection-based one kicks in.
registerConverter(new AssociatedConverterImpl(this), -10);
registerConverter(new BlacklistedTypesConverter(), PRIORITY_VERY_HIGH); // SECURITY-247 defense
registerConverter(new DynamicProxyConverter(getMapper()) { // SECURITY-105 defense
@Override public boolean canConvert(Class type) {
return /* this precedes NullConverter */ type != null && super.canConvert(type);
}
@Override public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
throw new ConversionException("<dynamic-proxy> not supported");
}
}, PRIORITY_VERY_HIGH);
}
@Override
protected MapperWrapper wrapMapper(MapperWrapper next) {
Mapper m = new CompatibilityMapper(new MapperWrapper(next) {
@Override
public String serializedClass(Class type) {
if (type != null && ImmutableMap.class.isAssignableFrom(type))
return super.serializedClass(ImmutableMap.class);
else if (type != null && ImmutableList.class.isAssignableFrom(type))
return super.serializedClass(ImmutableList.class);
else
return super.serializedClass(type);
}
});
AnnotationMapper a = new AnnotationMapper(m, getConverterRegistry(), getConverterLookup(), getClassLoader(), getReflectionProvider(), getJvm());
// TODO JENKINS-19561 this is unsafe:
a.autodetectAnnotations(true);
mapperInjectionPoint = new MapperInjectionPoint(a);
return mapperInjectionPoint;
}
public Mapper getMapperInjectionPoint() {
return mapperInjectionPoint.getDelegate();
}
/**
* @deprecated Uses default encoding yet fails to write an encoding header. Prefer {@link #toXMLUTF8}.
*/
@Deprecated
@Override public void toXML(Object obj, OutputStream out) {
super.toXML(obj, out);
}
/**
* Serializes to a byte stream.
* Uses UTF-8 encoding and specifies that in the XML encoding declaration.
* @since 1.504
*/
public void toXMLUTF8(Object obj, OutputStream out) throws IOException {
Writer w = new OutputStreamWriter(out, Charset.forName("UTF-8"));
w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
toXML(obj, w);
}
/**
* This method allows one to insert additional mappers after {@link XStream2} was created,
* but because of the way XStream works internally, this needs to be done carefully.
* Namely,
*
* <ol>
* <li>You need to {@link #getMapperInjectionPoint()} wrap it, then put that back into {@link #setMapper(Mapper)}.
* <li>The whole sequence needs to be synchronized against this object to avoid a concurrency issue.
* </ol>
*/
public void setMapper(Mapper m) {
mapperInjectionPoint.setDelegate(m);
}
final class MapperInjectionPoint extends MapperDelegate {
public MapperInjectionPoint(Mapper wrapped) {
super(wrapped);
}
public Mapper getDelegate() {
return delegate;
}
public void setDelegate(Mapper m) {
delegate = m;
}
}
/**
* Adds an alias in case class names change.
*
* Unlike {@link #alias(String, Class)}, which uses the registered alias name for writing XML,
* this method registers an alias to be used only for the sake of reading from XML. This makes
* this method usable for the situation when class names change.
*
* @param oldClassName
* Fully qualified name of the old class name.
* @param newClass
* New class that's field-compatible with the given old class name.
* @since 1.416
*/
public void addCompatibilityAlias(String oldClassName, Class newClass) {
compatibilityAliases.put(oldClassName,newClass);
}
/**
* Prior to Hudson 1.106, XStream 1.1.x was used which encoded "$" in class names
* as "-" instead of "_-" that is used now. Up through Hudson 1.348 compatibility
* for old serialized data was maintained via {@code XStream11XmlFriendlyMapper}.
* However, it was found (HUDSON-5768) that this caused fields with "__" to fail
* deserialization due to double decoding. Now this class is used for compatibility.
*/
private class CompatibilityMapper extends MapperWrapper {
private CompatibilityMapper(Mapper wrapped) {
super(wrapped);
}
@Override
public Class realClass(String elementName) {
Class s = compatibilityAliases.get(elementName);
if (s!=null) return s;
try {
return super.realClass(elementName);
} catch (CannotResolveClassException e) {
// If a "-" is found, retry with mapping this to "$"
if (elementName.indexOf('-') >= 0) try {
Class c = super.realClass(elementName.replace('-', '$'));
oldData.set(Boolean.TRUE);
return c;
} catch (CannotResolveClassException e2) { }
// Throw original exception
throw e;
}
}
}
/**
* If a class defines a nested {@code ConverterImpl} subclass, use that as a {@link Converter}.
* Its constructor may have XStream/XStream2 and/or Mapper parameters (or no params).
*/
private static final class AssociatedConverterImpl implements Converter {
private final XStream xstream;
private final ConcurrentHashMap<Class<?>,Converter> cache =
new ConcurrentHashMap<Class<?>,Converter>();
private AssociatedConverterImpl(XStream xstream) {
this.xstream = xstream;
}
@CheckForNull
private Converter findConverter(@CheckForNull Class<?> t) {
if (t == null) {
return null;
}
Converter result = cache.get(t);
if (result != null)
// ConcurrentHashMap does not allow null, so use this object to represent null
return result == this ? null : result;
try {
final ClassLoader classLoader = t.getClassLoader();
if(classLoader == null) {
return null;
}
Class<?> cl = classLoader.loadClass(t.getName() + "$ConverterImpl");
Constructor<?> c = cl.getConstructors()[0];
Class<?>[] p = c.getParameterTypes();
Object[] args = new Object[p.length];
for (int i = 0; i < p.length; i++) {
if(p[i]==XStream.class || p[i]==XStream2.class)
args[i] = xstream;
else if(p[i]== Mapper.class)
args[i] = xstream.getMapper();
else
throw new InstantiationError("Unrecognized constructor parameter: "+p[i]);
}
ConverterMatcher cm = (ConverterMatcher)c.newInstance(args);
result = cm instanceof SingleValueConverter
? new SingleValueConverterWrapper((SingleValueConverter)cm)
: (Converter)cm;
cache.put(t, result);
return result;
} catch (ClassNotFoundException e) {
cache.put(t, this); // See above.. this object in cache represents null
return null;
} catch (IllegalAccessException e) {
IllegalAccessError x = new IllegalAccessError();
x.initCause(e);
throw x;
} catch (InstantiationException e) {
InstantiationError x = new InstantiationError();
x.initCause(e);
throw x;
} catch (InvocationTargetException e) {
InstantiationError x = new InstantiationError();
x.initCause(e);
throw x;
}
}
public boolean canConvert(Class type) {
return findConverter(type)!=null;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
findConverter(source.getClass()).marshal(source,writer,context);
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
return findConverter(context.getRequiredType()).unmarshal(reader,context);
}
}
/**
* Create a nested {@code ConverterImpl} subclass that extends this class to run some
* callback code just after a type is unmarshalled by RobustReflectionConverter.
* Example: <pre> public static class ConverterImpl extends XStream2.PassthruConverter<MyType> {
* public ConverterImpl(XStream2 xstream) { super(xstream); }
* {@literal @}Override protected void callback(MyType obj, UnmarshallingContext context) {
* ...
* </pre>
*/
public static abstract class PassthruConverter<T> implements Converter {
private Converter converter;
public PassthruConverter(XStream2 xstream) {
converter = xstream.reflectionConverter;
}
public boolean canConvert(Class type) {
// marshal/unmarshal called directly from AssociatedConverterImpl
return false;
}
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
converter.marshal(source, writer, context);
}
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
Object obj = converter.unmarshal(reader, context);
callback((T)obj, context);
return obj;
}
protected abstract void callback(T obj, UnmarshallingContext context);
}
/**
* Marks serialized classes as being owned by particular components.
*/
interface ClassOwnership {
/**
* Looks up the owner of a class, if any.
* @param clazz a class which might be from a plugin
* @return an identifier such as plugin name, or null
*/
@CheckForNull String ownerOf(Class<?> clazz);
}
class PluginClassOwnership implements ClassOwnership {
private PluginManager pm;
@SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") // classOwnership checked for null so why does FB complain?
@Override public String ownerOf(Class<?> clazz) {
if (classOwnership != null) {
return classOwnership.ownerOf(clazz);
}
if (pm == null) {
Jenkins j = Jenkins.getInstanceOrNull();
if (j != null) {
pm = j.getPluginManager();
}
}
if (pm == null) {
return null;
}
// TODO: possibly recursively scan super class to discover dependencies
PluginWrapper p = pm.whichPlugin(clazz);
return p != null ? p.getShortName() + '@' + trimVersion(p.getVersion()) : null;
}
}
private static class BlacklistedTypesConverter implements Converter {
@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
throw new UnsupportedOperationException("Refusing to marshal " + source.getClass().getName() + " for security reasons");
}
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
throw new ConversionException("Refusing to unmarshal " + reader.getNodeName() + " for security reasons");
}
@Override
public boolean canConvert(Class type) {
if (type == null) {
return false;
}
try {
ClassFilter.DEFAULT.check(type);
ClassFilter.DEFAULT.check(type.getName());
} catch (SecurityException se) {
// claim we can convert all the scary stuff so we can throw exceptions when attempting to do so
return true;
}
return false;
}
}
}
| escoem/jenkins | core/src/main/java/hudson/util/XStream2.java | Java | mit | 19,633 |
/*
* Copyright (c) 2015 EXILANT Technologies Private Limited (www.exilant.com)
* Copyright (c) 2016 simplity.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.simplity.kernel.db;
import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Struct;
import java.sql.Types;
import java.util.HashMap;
import java.util.Map;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.simplity.kernel.ApplicationError;
import org.simplity.kernel.Tracer;
import org.simplity.kernel.data.DataSheet;
import org.simplity.kernel.data.DynamicSheet;
import org.simplity.kernel.data.FieldsInterface;
import org.simplity.kernel.data.MultiRowsSheet;
import org.simplity.kernel.value.IntegerValue;
import org.simplity.kernel.value.Value;
import org.simplity.kernel.value.ValueType;
import org.simplity.service.ServiceContext;
import oracle.jdbc.driver.OracleConnection;
import oracle.sql.ARRAY;
import oracle.sql.ArrayDescriptor;
import oracle.sql.STRUCT;
import oracle.sql.StructDescriptor;
/**
* We use DbDriver as a wrapper on JDBC to restrict the features to a smaller
* subset that is easy to maintain.
*
* @author simplity.org
*
*/
public class DbDriver {
// static final int[] TEXT_TYPES = {Types.CHAR, Types.LONGNVARCHAR,
// Types.LONGVARCHAR, Types.NCHAR, Types.NVARCHAR, Types.VARCHAR};
/*
* for sql escaping
*/
private static final String OUR_ESCAPE_CHAR = "!";
private static final String OUR_ESCAPE_STR = "!!";
private static final String CONTEXT_PREFIX = "java:/comp/env/";
/*
* we store sql types with corresponding value types
*/
private static final int[] LONG_TYPES = { Types.BIGINT, Types.INTEGER,
Types.SMALLINT };
private static final int[] DATE_TYPES = { Types.DATE, Types.TIME,
Types.TIMESTAMP };
private static final int[] DOUBLE_TYPES = { Types.DECIMAL, Types.DOUBLE,
Types.FLOAT, Types.REAL };
private static final int[] BOOLEAN_TYPES = { Types.BIT, Types.BOOLEAN };
private static final Map<Integer, ValueType> SQL_TYPES = new HashMap<Integer, ValueType>();
/**
* character used in like operator to match any characters
*/
public static final char LIKE_ANY = '%';
/*
* meta 0-table columns, 1-primary keys, 2-procedure parameters. refer to
* meta.getColumnNames(), getPrimarykeys() and getProcedureColumns() of JDBC
*/
/*
* we are going to use value types s many time, it is ugly to use full name.
* Let us have some short and sweet names
*/
private static final ValueType INT = ValueType.INTEGER;
private static final ValueType TXT = ValueType.TEXT;
private static final ValueType BOOL = ValueType.BOOLEAN;
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int TABLE_IDX = 0;
private static final String[] TABLE_NAMES = { "schema", "tableName",
"tableType", "remarks" };
private static final ValueType[] TABLE_TYPES = { TXT, TXT, TXT, TXT };
private static final int[] TABLE_POSNS = { 2, 3, 4, 5 };
private static final String[] TABLE_TYPES_TO_EXTRACT = { "TABLE", "VIEW" };
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int COL_IDX = 1;
private static final String[] COL_NAMES = { "schema", "tableName",
"columnName", "sqlType", "sqlTypeName", "size", "nbrDecimals",
"remarks", "nullable" };
private static final ValueType[] COL_TYPES = { TXT, TXT, TXT, INT, TXT, INT,
INT, TXT, BOOL };
private static final int[] COL_POSNS = { 2, 3, 4, 5, 6, 7, 9, 12, 18 };
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int KEY_IDX = 2;
private static final String[] KEY_NAMES = { "columnName", "sequence" };
private static final ValueType[] KEY_TYPES = { TXT, INT };
private static final int[] KEY_POSNS = { 4, 5 };
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int PROC_IDX = 3;
private static final String[] PROC_NAMES = { "schema", "procedureName",
"procedureType", "remarks" };
private static final ValueType[] PROC_TYPES = { TXT, TXT, INT, TXT };
private static final int[] PROC_POSNS = { 2, 3, 8, 7 };
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int PARAM_IDX = 4;
private static final String[] PARAM_NAMES = { "schema", "procedureName",
"paramName", "columnType", "sqlType", "sqlTypeName", "size",
"precision", "scale", "remarks", "nullable", "position" };
private static final ValueType[] PARAM_TYPES = { TXT, TXT, TXT, INT, INT,
TXT, INT, INT, INT, TXT, BOOL, INT };
private static final int[] PARAM_POSNS = { 2, 3, 4, 5, 6, 7, 9, 8, 10, 13,
19, 18 };
/*
* names, types and positions as per result set for meta.getUDTs()
*/
private static final int STRUCT_IDX = 5;
private static final String[] STRUCT_NAMES = { "schema", "structName",
"structType", "remarks" };
private static final ValueType[] STRUCT_TYPES = { TXT, TXT, TXT, TXT };
private static final int[] STRUCT_POSNS = { 2, 3, 5, 6 };
private static final int[] STRUCT_TYPES_TO_EXTRACT = { Types.STRUCT };
/*
* names, types and positions as per result set for meta.getTables()
*/
private static final int ATTR_IDX = 6;
private static final String[] ATTR_NAMES = { "schema", "structName",
"attributeName", "sqlType", "sqlTypeName", "size", "nbrDecimals",
"remarks", "nullable", "position" };
private static final ValueType[] ATTR_TYPES = { TXT, TXT, TXT, INT, TXT,
INT, INT, TXT, BOOL, INT };
private static final int[] ATTR_POSNS = { 2, 3, 4, 5, 6, 7, 8, 11, 17, 16 };
/*
* put them into array for modularity
*/
private static final String[][] META_COLUMNS = { TABLE_NAMES, COL_NAMES,
KEY_NAMES, PROC_NAMES, PARAM_NAMES, STRUCT_NAMES, ATTR_NAMES };
private static final ValueType[][] META_TYPES = { TABLE_TYPES, COL_TYPES,
KEY_TYPES, PROC_TYPES, PARAM_TYPES, STRUCT_TYPES, ATTR_TYPES };
private static final int[][] META_POSNS = { TABLE_POSNS, COL_POSNS,
KEY_POSNS, PROC_POSNS, PARAM_POSNS, STRUCT_POSNS, ATTR_POSNS };
static {
for (int i : LONG_TYPES) {
SQL_TYPES.put(new Integer(i), ValueType.INTEGER);
}
for (int i : DATE_TYPES) {
SQL_TYPES.put(new Integer(i), ValueType.DATE);
}
for (int i : DOUBLE_TYPES) {
SQL_TYPES.put(new Integer(i), ValueType.DECIMAL);
}
for (int i : BOOLEAN_TYPES) {
SQL_TYPES.put(new Integer(i), ValueType.BOOLEAN);
}
}
// private static int numberOfKeysToGenerateAtATime = 100;
/**
* are we to trace all sqls? Used during development/debugging
*/
private static boolean traceSqls;
/**
* We use either DataSource, or connection string to connect to the data
* base. DataSource is preferred
*/
private static DbVendor dbVendor;
private static DataSource dataSource;
private static String connectionString;
/*
* this is set ONLY if the app is set for multi-schema. Stored at the time
* of setting the db driver
*/
private static String defaultSchema = null;
private static Map<String, DataSource> otherDataSources = null;
private static Map<String, String> otherConStrings = null;
/*
* RDBMS brand dependent settings. set based on db vendor
*/
private static String timeStampFn;
private static String[] charsToEscapeForLike;
/**
* an open connection is maintained during execution of call back
*/
private Connection connection;
/**
* stated access type that is checked for consistency during subsequent
* calls
*/
private DbAccessType accessType;
/**
* set up to be called before any db operation can be done
*
* @param vendor
* @param dataSourceName
* @param driverClassName
* @param conString
* @param logSqls
* @param schemaDetails
*/
public static synchronized void initialSetup(DbVendor vendor,
String dataSourceName, String driverClassName, String conString,
boolean logSqls, SchemaDetail[] schemaDetails) {
if (vendor == null) {
Tracer.trace(
"This Application has not set dbVendor. We assume that the application does not require any db connection.");
if (dataSourceName != null || driverClassName != null
|| conString != null || schemaDetails != null) {
Tracer.trace(
"WARNING: Since dbVendor is not set, we ignore other db related settings.");
}
return;
}
setVendorParams(vendor);
traceSqls = logSqls;
/*
* use data source if specified
*/
if (dataSourceName != null) {
if (driverClassName != null || conString != null) {
Tracer.trace(
"WARNING: Since dataSourceName is specified, we ignore driverClassName and connectionString attributes");
}
setDataSource(null, dataSourceName);
if (schemaDetails != null) {
otherDataSources = new HashMap<String, DataSource>();
for (SchemaDetail sd : schemaDetails) {
if (sd.schemaName == null || sd.dataSourceName == null) {
throw new ApplicationError(
"schemaName and dataSourceName are required for mutli-schema operation");
}
if (sd.connectionString != null) {
Tracer.trace(
"Warning : This application uses data source, and hence connection string for schema "
+ sd.schemaName + " ignored");
}
setDataSource(sd.schemaName.toUpperCase(),
sd.dataSourceName);
}
}
return;
}
/*
* connection string
*/
if (driverClassName == null) {
throw new ApplicationError("dbVendor is set to " + vendor
+ " but no dataSource or driverClassName specified. If you do not need db connection, do not set dbVendor attribute.");
}
if (conString == null) {
throw new ApplicationError(
"driveClassName is specified but connection string is missing in your application set up.");
}
try {
Class.forName(driverClassName);
} catch (Exception e) {
throw new ApplicationError(e, "Could not use class "
+ driverClassName + " as driver class name.");
}
Tracer.trace("Driver class name " + driverClassName
+ " invoked successfully");
setConnection(null, conString);
if (schemaDetails != null) {
Tracer.trace("Checking connection string for additional schemas");
otherConStrings = new HashMap<String, String>();
for (SchemaDetail sd : schemaDetails) {
if (sd.schemaName == null || sd.connectionString == null) {
throw new ApplicationError(
"schemaName and connectionString are required for mutli-schema operation");
}
if (sd.dataSourceName != null) {
Tracer.trace(
"Warning: This application uses connection string, and hence dataSource for schema "
+ sd.schemaName + " ignored");
}
setConnection(sd.schemaName.toUpperCase(), sd.connectionString);
}
}
}
/**
*/
private static void setDataSource(String schema, String dataSourceName) {
Object obj = null;
String msg = null;
try {
obj = new InitialContext().lookup(dataSourceName);
} catch (Exception e) {
if (dataSourceName.startsWith(CONTEXT_PREFIX)) {
msg = e.getMessage();
} else {
try {
obj = new InitialContext()
.lookup(CONTEXT_PREFIX + dataSourceName);
} catch (Exception e1) {
msg = e1.getMessage();
}
}
}
if (obj == null) {
throw new ApplicationError("Error while using data source name "
+ dataSourceName + "\n" + msg);
}
if (obj instanceof DataSource == false) {
throw new ApplicationError("We got an object instance of "
+ obj.getClass().getName() + " as data source for name "
+ dataSourceName + " while we were expecting a "
+ DataSource.class.getName());
}
DataSource ds = (DataSource) obj;
Connection con = null;
ApplicationError err = null;
try {
con = ds.getConnection();
if (schema == null) {
defaultSchema = extractDefaultSchema(con);
}
if (schema == null) {
dataSource = ds;
Tracer.trace("Database connection for " + dbVendor
+ " established successfully using dataSource. Default schema is "
+ defaultSchema);
} else {
otherDataSources.put(schema.toUpperCase(), ds);
Tracer.trace("DataSource added for schema " + schema);
}
} catch (SQLException e) {
err = new ApplicationError(e,
"Data source is initialized but error while opening connection.");
} finally {
try {
if (con != null) {
con.close();
}
} catch (Exception ignore) {
//
}
}
if (err != null) {
throw err;
}
}
/**
* set connection string for a schema after testing it
*
* @param schema
* @param conString
*/
private static void setConnection(String schema, String conString) {
Connection con = null;
Exception err = null;
try {
con = DriverManager.getConnection(conString);
if (schema == null) {
defaultSchema = extractDefaultSchema(con);
connectionString = conString;
Tracer.trace("Database connection for " + dbVendor
+ " established successfully using a valid connection string. Default schema is "
+ defaultSchema);
} else {
otherConStrings.put(schema.toUpperCase(), conString);
Tracer.trace(
"Additional connection string validated for schema "
+ schema);
}
} catch (Exception e) {
err = e;
} finally {
try {
if (con != null) {
con.close();
}
} catch (Exception ignore) {
//
}
}
if (err != null) {
throw new ApplicationError(err,
" Database set up using connection string failed after successfully setting the driver for "
+ (schema == null ? " default schema"
: (" schema " + schema)));
}
}
/**
* set parameters that depend on the selected vendor
*
* @param vendor
*/
private static void setVendorParams(DbVendor vendor) {
Tracer.trace("dbVendor is set to " + vendor);
dbVendor = vendor;
char[] chars = vendor.getEscapesForLike();
charsToEscapeForLike = new String[chars.length];
for (int i = 0; i < chars.length; i++) {
charsToEscapeForLike[i] = chars[i] + "";
}
timeStampFn = vendor.getTimeStamp();
}
/**
* only way to get an instance of RdbDriver to do rdbms operations.
* Necessary resources are allotted, and the passed object is called back
* with workWithDriver(instance)
*
* @param callBackObject
* @param accessType
*/
public static void workWithDriver(DbClientInterface callBackObject,
DbAccessType accessType) {
workWithDriver(callBackObject, accessType, null);
}
/**
* only way to get an instance of RdbDriver to do rdbms operations.
* Necessary resources are allotted, and the passed object is called back
* with workWithDriver(instance)
*
* @param callBackObject
* @param accType
* @param schema
* optional. Use Only if your application is designed to work with
* multiple schemas, AND this session transaction need to use a
* schema different from the default one
*/
public static void workWithDriver(DbClientInterface callBackObject,
DbAccessType accType, String schema) {
Connection con = null;
if (accType != DbAccessType.NONE) {
con = getConnection(accType, schema);
}
DbDriver driver = new DbDriver(con, accType);
boolean allOk = false;
Exception exception = null;
try {
allOk = callBackObject.workWithDriver(driver);
} catch (Exception e) {
Tracer.trace(e,
"Callback object threw an exception while working with the driver");
exception = e;
}
if (con != null) {
closeConnection(con, accType, allOk);
}
if (exception != null) {
String msg = "Error while executing a service. "
+ exception.getMessage();
throw new ApplicationError(exception, msg);
}
}
/**
* get a connection to the db
*
* @param acType
* @param schema
* @return connection
*/
static Connection getConnection(DbAccessType acType, String schema) {
/*
* set sch to an upper-cased schema, but only if it is non-null and
* different from default schema
*/
String sch = null;
if (schema != null) {
sch = schema.toUpperCase();
if (sch.equals(defaultSchema)) {
Tracer.trace("service is asking for schema " + schema
+ " but that is the default. default connection used");
sch = null;
} else {
Tracer.trace("Going to open a non-default connection for schema "
+ schema);
}
}
Connection con = null;
Exception err = null;
try {
con = createConnection(schema);
if (acType != null) {
if (acType == DbAccessType.READ_ONLY) {
con.setReadOnly(true);
} else {
con.setTransactionIsolation(
Connection.TRANSACTION_READ_COMMITTED);
con.setAutoCommit(acType == DbAccessType.AUTO_COMMIT);
}
}
} catch (Exception e) {
if (con != null) {
try {
con.close();
} catch (Exception e1) {
//
}
con = null;
}
err = e;
}
if (con == null) {
if (err == null) {
throw new ApplicationError("Unable to connect to DataBase");
}
throw new ApplicationError(err, "Unable to connect to DataBase");
}
return con;
}
/**
* get a connection to the db
*
* @param acType
* @param schema
* @return connection
* @throws SQLException
*/
private static Connection createConnection(String schema)
throws SQLException {
/*
* set sch to an upper-cased schema, but only if it is non-null and
* different from default schema
*/
String sch = null;
if (schema != null) {
sch = schema.toUpperCase();
if (sch.equals(defaultSchema)) {
Tracer.trace("service is asking for schema " + schema
+ " but that is the default. default connection used");
sch = null;
} else {
Tracer.trace("Going to open a non-default connection for schema "
+ schema);
}
}
if (dataSource != null) {
/*
* this application uses dataSource
*/
if (sch == null) {
return dataSource.getConnection();
}
/*
* this service is using a different schema
*/
DataSource ds = otherDataSources.get(sch);
if (ds == null) {
throw new ApplicationError(
"No dataSource configured for schema " + sch);
}
return ds.getConnection();
}
if (connectionString == null) {
throw new ApplicationError(
"Database should be initialized properly before any operation can be done.");
}
/*
* old-fashioned application :-(
*/
if (sch == null) {
return DriverManager.getConnection(connectionString);
}
/*
* service uses a non-default schema
*/
String conString = otherConStrings.get(sch);
if (conString == null) {
throw new ApplicationError(
"No connection string configured for schema " + sch);
}
return DriverManager.getConnection(conString);
}
/**
* private constructor to ensure that we control its instantiation
*
* @param con
* @param dbAccessType
*/
private DbDriver(Connection con, DbAccessType dbAccessType) {
this.connection = con;
this.accessType = dbAccessType;
}
/**
* extract output from sql into data sheet
*
* @param sql
* must be a single prepared sql, with no semicolon at the end.
* @param values
* to be put into the prepared sql
* @param outSheet
* data sheet that has the expected columns defined in it.
* @param oneRowOnly
* true if (at most) one row is to be extracted. false to extract
* all rows
* @return number of rows extracted
*/
public int extractFromSql(String sql, Value[] values, DataSheet outSheet,
boolean oneRowOnly) {
if (traceSqls) {
this.traceSql(sql, values);
if (this.connection == null) {
return 0;
}
}
PreparedStatement stmt = null;
int result = 0;
try {
stmt = this.connection.prepareStatement(sql);
this.setParams(stmt, values);
if (oneRowOnly) {
return this.extractOne(stmt, outSheet);
}
result = this.extractAll(stmt, outSheet);
} catch (SQLException e) {
throw new ApplicationError(e, "Sql Error while extracting data ");
} finally {
this.closeStatment(stmt);
}
return result;
}
/**
* check if this sql result sin at least one row
*
* @param sql
* @param values
* @return true if there is at least one row
*/
public boolean hasResult(String sql, Value[] values) {
if (traceSqls) {
this.traceSql(sql, values);
if (this.connection == null) {
return false;
}
}
PreparedStatement stmt = null;
boolean result = false;
try {
stmt = this.connection.prepareStatement(sql);
this.setParams(stmt, values);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
result = true;
}
rs.close();
} catch (SQLException e) {
throw new ApplicationError(e, "Sql Error while extracting data ");
} finally {
this.closeStatment(stmt);
}
return result;
}
/**
* extract output from sql with different sets of input values into data
* sheet
*
* @param sql
* must be a single prepared sql, with no semicolon at the end.
* @param values
* to be put into the prepared sql, one row per batch
* @param outSheet
* data sheet that has the expected columns defined in it.
* @return number of rows extracted
*/
public int extractFromSql(String sql, Value[][] values,
DataSheet outSheet) {
if (traceSqls) {
this.traceBatchSql(sql, values);
if (this.connection == null) {
return 0;
}
}
PreparedStatement stmt = null;
int total = 0;
try {
stmt = this.connection.prepareStatement(sql);
for (Value[] vals : values) {
this.setParams(stmt, vals);
total += this.extractAll(stmt, outSheet);
}
} catch (SQLException e) {
throw new ApplicationError(e, "Sql Error while extracting data ");
} finally {
this.closeStatment(stmt);
}
return total;
}
/**
* extract output from sql that the caller has o idea about the output
* columns
*
* @param sql
* must be a single prepared sql, with no semicolon at the end.
* @param values
* to be put into the prepared sql
* @param oneRowOnly
* true if (at most) one row is to be extracted. false to extract
* all rows
* @return a data sheet with has 0 or more rows of extracted data
*/
public DataSheet extractFromDynamicSql(String sql, Value[] values,
boolean oneRowOnly) {
if (traceSqls) {
this.traceSql(sql, values);
if (this.connection == null) {
return null;
}
}
PreparedStatement stmt = null;
DataSheet result = null;
try {
stmt = this.connection.prepareStatement(sql);
this.setParams(stmt, values);
if (oneRowOnly) {
return this.extractMetaOne(stmt);
}
result = this.extractMetaAll(stmt);
} catch (SQLException e) {
throw new ApplicationError(e, "Sql Error while extracting data ");
} finally {
this.closeStatment(stmt);
}
return result;
}
/**
* execute a sql as a prepared statement
*
* @param sql
* to be executed
* @param values
* in the right order for the prepared statement
* @param treatSqlErrorAsNoAction
* if true, sql error is treated as if rows affected is zero.
* This is helpful when constraints are added in the db, and we
* would treat failure as validation issue.
* @return number of affected rows
*/
public int executeSql(String sql, Value[] values,
boolean treatSqlErrorAsNoAction) {
PreparedStatement stmt = null;
if (traceSqls) {
this.traceSql(sql, values);
if (this.connection == null) {
return 0;
}
}
this.checkWritable();
int result = 0;
try {
stmt = this.connection.prepareStatement(sql);
this.setParams(stmt, values);
result = stmt.executeUpdate();
} catch (SQLException e) {
if (treatSqlErrorAsNoAction) {
Tracer.trace("SQLException code:" + e.getErrorCode()
+ " message :" + e.getMessage()
+ " is treated as zero rows affected.");
} else {
throw new ApplicationError(e, "Sql Error while executing sql ");
}
} finally {
this.closeStatment(stmt);
}
if (result < 0) {
Tracer.trace(
"Number of affected rows is not reliable as we got it as "
+ result);
} else {
Tracer.trace(result + " rows affected.");
}
return result;
}
/**
* execute an insert statement as a prepared statement
*
* @param sql
* to be executed
* @param values
* in the right order for the prepared statement
* @param generatedKeys
* array in which generated keys are returned
* @param keyNames
* array of names of columns that have generated keys. This is
* typically just one, primary key
* @param treatSqlErrorAsNoAction
* if true, sql error is treated as if rows affected is zero.
* This is helpful when constraints are added in the db, and we
* would treat failure as validation issue.
* @return number of affected rows
*/
public int insertAndGetKeys(String sql, Value[] values,
long[] generatedKeys, String[] keyNames,
boolean treatSqlErrorAsNoAction) {
PreparedStatement stmt = null;
if (traceSqls) {
this.traceSql(sql, values);
if (this.connection == null) {
return 0;
}
}
this.checkWritable();
int result = 0;
try {
stmt = this.connection.prepareStatement(sql, keyNames);
this.setParams(stmt, values);
result = stmt.executeUpdate();
if (result > 0) {
this.getGeneratedKeys(stmt, generatedKeys);
}
} catch (SQLException e) {
if (treatSqlErrorAsNoAction) {
Tracer.trace("SQLException code:" + e.getErrorCode()
+ " message :" + e.getMessage()
+ " is treated as zero rows affected.");
} else {
throw new ApplicationError(e, "Sql Error while executing sql ");
}
} finally {
this.closeStatment(stmt);
}
if (result < 0) {
Tracer.trace(
"Number of affected rows is not reliable as we got it as "
+ result);
} else {
Tracer.trace(result + " rows affected.");
}
return result;
}
/**
* extract generated keys into the array
*
* @param stmt
* @param generatedKeys
* @throws SQLException
*/
private void getGeneratedKeys(Statement stmt, long[] generatedKeys)
throws SQLException {
ResultSet rs = stmt.getGeneratedKeys();
for (int i = 0; i < generatedKeys.length && rs.next(); i++) {
generatedKeys[i] = rs.getLong(1);
}
rs.close();
}
/**
* for each row in the result set of the sql, call back the iterator.
*
* @param sql
* @param values
* for the sql
* @param outputTypes
* value types of output parameters. null if you want us to
* discover it, but it will cost you a few grands :-)
* @param iterator
* to be called back with workWithARow(row) method. iteration
* stops if this method returns false;
* @return number of rows iterated
*/
public int workWithRows(String sql, Value[] values, ValueType[] outputTypes,
RowIterator iterator) {
PreparedStatement stmt = null;
try {
stmt = this.connection.prepareStatement(sql);
this.setParams(stmt, values);
return this.iterate(stmt, outputTypes, iterator);
} catch (SQLException e) {
throw new ApplicationError(e, "Sql Error executing service ");
} finally {
this.closeStatment(stmt);
}
}
/**
* execute a prepared statement, with different sets of values
*
* @param sql
* @param values
* each row should have the same number of values, in the right
* order for the sql
* @param treatSqlErrorAsNoAction
* if true, sql error is treated as if rows affected is zero.
* This is helpful when constraints are added in the db, and we
* would treat failure as validation issue.
* @return affected rows for each set of values
*/
public int[] executeBatch(String sql, Value[][] values,
boolean treatSqlErrorAsNoAction) {
if (traceSqls) {
this.traceBatchSql(sql, values);
if (this.connection == null) {
return new int[0];
}
}
this.checkWritable();
PreparedStatement stmt = null;
int[] result = new int[0];
try {
stmt = this.connection.prepareStatement(sql);
for (Value[] row : values) {
this.setParams(stmt, row);
stmt.addBatch();
}
result = stmt.executeBatch();
} catch (SQLException e) {
if (treatSqlErrorAsNoAction) {
Tracer.trace("SQLException code:" + e.getErrorCode()
+ " message :" + e.getMessage()
+ " is treated as zero rows affected.");
} else {
throw new ApplicationError(e,
"Sql Error while executing batch ");
}
} finally {
this.closeStatment(stmt);
}
int rows = 0;
for (int j : result) {
if (j < 0) {
rows = j;
} else if (rows >= 0) {
rows += j;
}
}
if (rows < 0) {
Tracer.trace(
"Number of affected rows is not reliable as we got it as "
+ rows);
} else {
Tracer.trace(rows + " rows affected.");
}
return result;
}
/**
* extract output from stored procedure into data sheet
*
* @param sql
* must be in the standard jdbc format {call
* procedureName(?,?,...)}
* @param inputFields
* @param outputFields
* @param params
* @param outputSheets
* @param ctx
* @return number of rows extracted
*/
public int executeSp(String sql, FieldsInterface inputFields,
FieldsInterface outputFields, ProcedureParameter[] params,
DataSheet[] outputSheets, ServiceContext ctx) {
if (traceSqls) {
this.traceSql(sql, null);
if (this.connection == null) {
return 0;
}
}
CallableStatement stmt = null;
int result = 0;
SQLException err = null;
try {
stmt = this.connection.prepareCall(sql);
if (params != null) {
for (ProcedureParameter param : params) {
/*
* programmers often make mistakes while defining
* parameters. Better to pin-point such errors
*/
try {
if (param.setParameter(stmt, inputFields,
ctx) == false) {
Tracer.trace("Error while setting " + param.name
+ " You will get an error.");
// issue in setting parameter. May be a mandatory
// field is not set
return 0;
}
} catch (Exception e) {
Tracer.trace("Unable to set param " + param.name
+ " error : " + e.getMessage());
param.reportError(e);
}
}
}
boolean hasResult = stmt.execute();
int i = 0;
if (outputSheets != null && hasResult) {
int nbrSheets = outputSheets.length;
while (hasResult) {
if (i >= nbrSheets) {
Tracer.trace(
"Stored procedure is ready to give more results, but the requester has supplied only "
+ nbrSheets
+ " data sheets to read data into. Other data ignored.");
break;
}
DataSheet outputSheet = outputSheets[i];
ValueType[] outputTypes = outputSheet.getValueTypes();
ResultSet rs = stmt.getResultSet();
while (rs.next()) {
outputSheet.addRow(getParams(rs, outputTypes));
result++;
}
rs.close();
i++;
hasResult = stmt.getMoreResults();
}
}
if (params != null) {
for (ProcedureParameter param : params) {
/*
* programmers often make mistakes while defining
* parameters. Better to pin-point such errors
*/
try {
param.extractOutput(stmt, outputFields, ctx);
} catch (Exception e) {
param.reportError(e);
}
}
}
} catch (SQLException e) {
err = e;
} finally {
this.closeStatment(stmt);
}
if (err != null) {
throw new ApplicationError(err,
"Sql Error while extracting data using stored procedure");
}
Tracer.trace(result + " rows extracted.");
if (result > 0) {
return result;
}
if (outputFields != null) {
return 1;
}
return 0;
}
/**
* close connection after commit/roll-back
*
* @param allOk
* if we are managing transaction, true implies commit, and false
* implies roll-back
*/
static void closeConnection(Connection con, DbAccessType accType,
boolean allOk) {
try {
Tracer.trace("Going to close a connection of type " + accType
+ " with allOK = " + allOk);
if (accType == DbAccessType.READ_WRITE) {
if (allOk) {
con.commit();
} else {
con.rollback();
}
}
} catch (SQLException e) {
// throw new ApplicationError(e,
Tracer.trace(e, "Sql Error while closing database connection. ");
} finally {
try {
con.close();
} catch (Exception e) {
//
}
}
}
/**
* sets parameters to prepared statement
*
* @param stmt
* @param values
* First occurrence of null implies logical end of array. This
* feature is added to avoid use of List
* @throws SQLException
*/
private void setParams(PreparedStatement stmt, Value[] values)
throws SQLException {
if (values == null) {
return;
}
int i = 1;
for (Value value : values) {
value.setToStatement(stmt, i);
i++;
}
}
/**
* extract rows from a statement into a sheet
*
* @param stmt
* @param outSheet
* @return number rows extracted
* @throws SQLException
*/
private int extractAll(PreparedStatement stmt, DataSheet outSheet)
throws SQLException {
ValueType[] outputTypes = outSheet.getValueTypes();
ResultSet rs = stmt.executeQuery();
int result = 0;
while (rs.next()) {
outSheet.addRow(getParams(rs, outputTypes));
result++;
}
rs.close();
Tracer.trace(result + " rows extracted.");
return result;
}
/**
* extract at most one row from a statement into a sheet
*
* @param stmt
* @param outSheet
* @return number rows extracted
* @throws SQLException
*/
private int extractOne(PreparedStatement stmt, DataSheet outSheet)
throws SQLException {
ResultSet rs = stmt.executeQuery();
int result = 0;
if (rs.next()) {
outSheet.addRow(getParams(rs, outSheet.getValueTypes()));
result = 1;
}
rs.close();
Tracer.trace(result + " rows extracted.");
return result;
}
/**
* @param stmt
* @return
* @throws SQLException
*/
private DataSheet extractMetaAll(PreparedStatement stmt)
throws SQLException {
ResultSet rs = stmt.executeQuery();
DataSheet outSheet = this.createOutSheet(rs);
this.extractAll(stmt, outSheet);
rs.close();
return outSheet;
}
/**
* @param stmt
* @return
* @throws SQLException
*/
private DataSheet extractMetaOne(PreparedStatement stmt)
throws SQLException {
ResultSet rs = stmt.executeQuery();
DataSheet outSheet = new DynamicSheet();
if (rs.next()) {
ResultSetMetaData md = rs.getMetaData();
int n = md.getColumnCount();
for (int i = 1; i <= n; i++) {
String colName = md.getColumnName(i);
ValueType type = this.getValueType(md.getColumnType(i));
Value value = type.extractFromRs(rs, i);
outSheet.setValue(colName, value);
}
}
rs.close();
return outSheet;
}
/**
* extract rows from a statement
*
* @param stmt
* @param outputTypes
* @return number of rows iterated
* @throws SQLException
*/
private int iterate(PreparedStatement stmt, ValueType[] outputTypes,
RowIterator iterator) throws SQLException {
ResultSet rs = stmt.executeQuery();
ValueType[] types = outputTypes == null ? this.getOutputTypes(rs)
: outputTypes;
int nbr = 0;
while (rs.next()) {
iterator.workWithARow(getParams(rs, types));
nbr++;
}
rs.close();
return nbr;
}
/**
* @param rs
* @return
* @throws SQLException
*/
private ValueType[] getOutputTypes(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int n = md.getColumnCount();
ValueType[] types = new ValueType[n];
for (int i = 0; i < types.length; i++) {
int j = i + 1;
ValueType type = SQL_TYPES.get(new Integer(md.getColumnType(j)));
if (type == null) {
type = ValueType.TEXT;
}
types[i] = type;
}
return types;
}
/**
* @param rs
* @return data sheet
* @throws SQLException
*/
private DataSheet createOutSheet(ResultSet rs) throws SQLException {
ResultSetMetaData md = rs.getMetaData();
int n = md.getColumnCount();
ValueType[] types = new ValueType[n];
String[] columnNames = new String[n];
for (int i = 0; i < types.length; i++) {
int j = i + 1;
columnNames[i] = md.getColumnName(j);
types[i] = this.getValueType(md.getColumnType(j));
}
return new MultiRowsSheet(columnNames, types);
}
private ValueType getValueType(int sqlType) {
ValueType type = SQL_TYPES.get(new Integer(sqlType));
if (type == null) {
return ValueType.TEXT;
}
return type;
}
/**
* gets output parameters from a stored procedure
*
* @param stmt
* @param values
* @throws SQLException
*/
private static Value[] getParams(ResultSet rs, ValueType[] types)
throws SQLException {
Value[] values = new Value[types.length];
for (int i = 0; i < types.length; i++) {
values[i] = types[i].extractFromRs(rs, i + 1);
}
return values;
}
/**
* method to be used when the parameters to be extracted are not in the
* right order, or we are not extracting each of them, and the caller would
* like to specify the position.
*
* @param stmt
* @param values
* @throws SQLException
*/
private static Value[] getParams(ResultSet rs, ValueType[] types,
int[] positions) throws SQLException {
Value[] values = new Value[types.length];
for (int i = 0; i < types.length; i++) {
values[i] = types[i].extractFromRs(rs, positions[i]);
}
return values;
}
/**
* @param statement
*/
private void closeStatment(Statement statement) {
if (statement == null) {
return;
}
try {
statement.close();
} catch (Exception e) {
//
}
}
/**
* @return sql function to get time stamp
*/
public static String getTimeStamp() {
return timeStampFn;
}
/**
* put % and escape the text suitable for a LIKE operation as per brand of
* RDBMS. we have standardized on ! as escape character
*
* @param text
* to be escaped
* @return go ahead and send this as value of prepared statement for LIKE
*/
public static String escapeForLike(String text) {
String result = text.replaceAll(OUR_ESCAPE_CHAR, OUR_ESCAPE_STR);
for (String s : charsToEscapeForLike) {
result = result.replace(s, OUR_ESCAPE_CHAR + s);
}
return result;
}
private void traceSql(String sql, Value[] values) {
if (values == null || values.length == 0) {
Tracer.trace(sql);
return;
}
StringBuilder sbf = new StringBuilder(sql);
sbf.append("\n Parameters");
int i = 0;
for (Value value : values) {
if (value == null) {
break;
}
i++;
sbf.append('\n').append(i).append(" : ").append(value.toString());
if (i > 12) {
sbf.append("..like wise up to ").append(values.length)
.append(" : ").append(values[values.length - 1]);
break;
}
}
Tracer.trace(sbf.toString());
}
private void traceBatchSql(String sql, Value[][] values) {
StringBuilder sbf = new StringBuilder(sql);
int i = 0;
for (Value[] row : values) {
if (row == null) {
break;
}
i++;
sbf.append("\n SET ").append(i);
int j = 0;
for (Value value : row) {
if (value == null) {
break;
}
j++;
sbf.append('\n').append(j).append(" : ").append(value);
}
}
// Tracer.trace(sbf.toString());
}
/**
* get tables/views defined in the database
*
* @param schemaName
* null, pattern or name
* @param tableName
* null, pattern or name
* @return data sheet that has attributes for tables/views. Null if no
* output
*/
public static DataSheet getTables(String schemaName, String tableName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, tableName, TABLE_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get column names of a table
*
* @param schemaName
* schema to which this table belongs to. leave it null to get
* the table from default schema
* @param tableName
* can be null to get all tables or pattern, or actual name
* @return sheet with one row per column. Null if no columns.
*/
public static DataSheet getTableColumns(String schemaName,
String tableName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, tableName, COL_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get key columns for all tables in the schema
*
* @param schemaName
* @return sheet with one row per column. Null if this table does not exist,
* or something went wrong!!
*/
public static DataSheet getPrimaryKeys(String schemaName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, null, KEY_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get key columns names of a table
*
* @param schemaName
* possibly null
* @param tableName
* non-null
* @return key column names
*/
public static String[] getPrimaryKeysForTable(String schemaName,
String tableName) {
if (tableName == null) {
Tracer.trace(
"getPrimaryKeysForTable() is for a specific table. If you want for all tables, use the getPrimaryKeys()");
return null;
}
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
DataSheet sheet = getMetaSheet(con, schemaName, tableName, KEY_IDX);
if (sheet == null) {
return null;
}
int n = sheet.length();
String[] result = new String[n];
for (int i = 0; i < n; i++) {
Value[] row = sheet.getRow(i);
int idx = (int) ((IntegerValue) row[1]).getLong() - 1;
result[idx] = row[0].toString();
}
return result;
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get stored procedures
*
* @param schemaName
* null, pattern or name
* @param procedureName
* null, pattern or name
* @return data sheet that has attributes of procedures. Null if no output
*/
public static DataSheet getProcedures(String schemaName,
String procedureName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, procedureName, PROC_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get parameters of procedure
*
* @param schemaName
* null, pattern or name
* @param procedureName
* null, pattern or name
* @return sheet with one row per column. Null if this table does not exist,
* or something went wrong!!
*/
public DataSheet getProcedureParams(String schemaName,
String procedureName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, procedureName, PARAM_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get structures/user defined types
*
* @param schemaName
* null, pattern, or name
* @param structName
* null or pattern.
* @return data sheet containing attributes of structures. Null of no output
*/
public DataSheet getStructs(String schemaName, String structName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, structName, STRUCT_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
/**
* get attributes of structure (user defined data type)
*
* @param schemaName
* null for all or pattern/name
* @param structName
* null for all or pattern/name
* @return sheet with one row per column. Null if no output
*/
public DataSheet getStructAttributes(String schemaName, String structName) {
Connection con = getConnection(DbAccessType.READ_ONLY, schemaName);
try {
return getMetaSheet(con, schemaName, structName, ATTR_IDX);
} finally {
closeConnection(con, DbAccessType.READ_ONLY, true);
}
}
private static DataSheet getMetaSheet(Connection con, String schema,
String metaName, int metaIdx) {
ResultSet rs = null;
String schemaName = schema;
if (schema == null) {
schemaName = defaultSchema;
}
try {
DatabaseMetaData meta = con.getMetaData();
switch (metaIdx) {
case TABLE_IDX:
rs = meta.getTables(null, schemaName, metaName,
TABLE_TYPES_TO_EXTRACT);
break;
case COL_IDX:
rs = meta.getColumns(null, schemaName, metaName, null);
break;
case KEY_IDX:
rs = meta.getPrimaryKeys(null, schemaName, metaName);
break;
case PROC_IDX:
rs = meta.getProcedures(null, schemaName, metaName);
break;
case PARAM_IDX:
rs = meta.getProcedureColumns(null, schemaName, metaName, null);
break;
case STRUCT_IDX:
rs = meta.getUDTs(null, schemaName, metaName,
STRUCT_TYPES_TO_EXTRACT);
break;
case ATTR_IDX:
rs = meta.getAttributes(null, schemaName, metaName, null);
break;
default:
throw new ApplicationError(
"Meta data " + metaIdx + " is not defined yet.");
}
if (rs.next()) {
DataSheet sheet = new MultiRowsSheet(META_COLUMNS[metaIdx],
META_TYPES[metaIdx]);
do {
sheet.addRow(getParams(rs, META_TYPES[metaIdx],
META_POSNS[metaIdx]));
} while (rs.next());
return sheet;
}
} catch (Exception e) {
Tracer.trace(e, "Unable to get meta data for " + metaName);
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
//
}
}
}
return null;
}
/**
* @return db vendor from whom the driver is used
*/
public static DbVendor getDbVendor() {
return dbVendor;
}
/**
*
* @param con
* @param schema
*/
private static String extractDefaultSchema(Connection con) {
String schema = null;
try {
Statement stmt = con.createStatement();
stmt.executeQuery(dbVendor.getGetSchemaSql());
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
schema = rs.getString(1);
if (rs.wasNull()) {
throw new ApplicationError(
"data base returned null as default schema.");
}
} else {
throw new ApplicationError(
"data base returned no result for sql "
+ dbVendor.getGetSchemaSql());
}
} catch (SQLException e) {
throw new ApplicationError(e,
"Error while getting default schema for this db connection.");
}
return schema.toUpperCase();
}
/**
* @return default schema or null
*/
public static Object getDefaultSchema() {
return defaultSchema;
}
/**
* @return true if the db vendor needs a key generator , like oracle
*/
public static boolean generatorNameRequired() {
return dbVendor == DbVendor.ORACLE;
}
private void checkWritable() {
if (this.accessType == DbAccessType.READ_ONLY) {
throw new ApplicationError(
"Service is set for read-only access to database, but an attempt is made to manipulate data");
}
}
/**
* @param schema
* name of schema to check for
* @return true is this schema is defined as additional schema. False
* otherwise
*/
public static boolean isSchmeaDefined(String schema) {
if (schema == null) {
return false;
}
String sn = schema.toUpperCase();
if (sn.equals(defaultSchema)) {
return true;
}
if (dataSource != null) {
if (otherDataSources != null && otherDataSources.containsKey(sn)) {
return true;
}
return false;
}
if (otherConStrings != null && otherConStrings.containsKey(sn)) {
return true;
}
return false;
}
/*
* methods related to data structure/object in db,
*/
/**
* delegated back to DBDriver to take care of driver related issues between
* Oracle and standard SQL
*
* @param con
* @param values
* @param dbArrayType
* as defined in the RDBMS
* @return object that is suitable to be assigned to an array parameter
* @throws SQLException
*/
public static Array createArray(Connection con, Value[] values,
String dbArrayType) throws SQLException {
Object[] data = new Object[values.length];
for (int i = 0; i < values.length; i++) {
Value val = values[i];
if (val != null) {
data[i] = val.toObject();
}
}
if (dbVendor == DbVendor.ORACLE) {
OracleConnection ocon = toOracleConnection(con);
ArrayDescriptor ad = ArrayDescriptor.createDescriptor(dbArrayType,
ocon);
return new ARRAY(ad, ocon, data);
}
return con.createArrayOf(dbArrayType, data);
}
/**
* This is delegated back to DbDriver because oracle driver does not support
* standard SQL way of doing this. Let DbDriver class be the repository of
* all Driver related issues
*
* @param con
* @param data
* @param dbObjectType
* as defined in RDBMS
* @return object that can be assigned to a struct parameter
* @throws SQLException
*/
public static Struct createStruct(Connection con, Object[] data,
String dbObjectType) throws SQLException {
if (dbVendor == DbVendor.ORACLE) {
OracleConnection ocon = toOracleConnection(con);
StructDescriptor sd = StructDescriptor
.createDescriptor(dbObjectType, ocon);
return new STRUCT(sd, ocon, data);
}
return con.createStruct(dbObjectType, data);
}
/**
* This is delegated back to DbDriver because oracle driver does not support
* standard SQL way of doing this. Let DbDriver class be the repository of
* all Driver related issues
*
* @param con
* @param values
* @param dbObjectType
* as defined in RDBMS
* @return object that can be assigned to a struct parameter
* @throws SQLException
*/
public static Struct createStruct(Connection con, Value[] values,
String dbObjectType) throws SQLException {
Object[] data = new Object[values.length];
for (int i = 0; i < values.length; i++) {
Value value = values[i];
if (value != null) {
data[i] = value.toObject();
}
}
return createStruct(con, data, dbObjectType);
}
/**
* Create a struct array that can be assigned to procedure parameter. This
* is delegated to DBDriver because of issues with Oracle driver
*
* @param con
* @param structs
* @param dbArrayType
* as defined in the rdbms
* @return object that is suitable to be assigned to stored procedure
* parameter
* @throws SQLException
*/
public static Array createStructArray(Connection con, Struct[] structs,
String dbArrayType) throws SQLException {
if (dbVendor == DbVendor.ORACLE) {
OracleConnection ocon = toOracleConnection(con);
ArrayDescriptor ad = ArrayDescriptor.createDescriptor(dbArrayType,
ocon);
return new ARRAY(ad, ocon, structs);
}
return con.createArrayOf(dbArrayType, structs);
}
private static OracleConnection toOracleConnection(Connection con) {
if (con instanceof OracleConnection) {
return (OracleConnection) con;
}
try {
return con.unwrap(OracleConnection.class);
} catch (Exception e) {
throw new ApplicationError(
"Error while unwrapping to Oracle connection. This is a set-up issue with your server. It is probably using a pooled-connection with a flag not to allow access to underlying connection object "
+ e.getMessage());
}
}
/**
* not recommended for use. Use only under strict parental supervision.
* ensure that you close it properly
*
* @return connection object that MUST be closed by you at any cost!!
*/
public static Connection getConnection() {
return getConnection(null, null);
}
} | raghu-bhandi/simplity-kernel | java/org/simplity/kernel/db/DbDriver.java | Java | mit | 52,656 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.compute;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Fluent;
import com.microsoft.azure.management.apigeneration.Beta.SinceVersion;
import com.microsoft.azure.management.compute.implementation.ComputeManager;
import com.microsoft.azure.management.compute.implementation.ContainerServiceInner;
import com.microsoft.azure.management.resources.fluentcore.arm.models.GroupableResource;
import com.microsoft.azure.management.resources.fluentcore.arm.models.Resource;
import com.microsoft.azure.management.resources.fluentcore.model.Appliable;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.azure.management.resources.fluentcore.model.Refreshable;
import com.microsoft.azure.management.resources.fluentcore.model.Updatable;
/**
* An client-side representation for a container service.
*/
@Fluent
@Beta(SinceVersion.V1_1_0)
public interface ContainerService extends
GroupableResource<ComputeManager, ContainerServiceInner>,
Refreshable<ContainerService>,
Updatable<ContainerService.Update> {
/**
* @return the master node count
*/
int masterNodeCount();
/**
* @return the type of the orchestrator
*/
ContainerServiceOchestratorTypes orchestratorType();
/**
* @return the master leaf domain label
*/
String masterLeafDomainLabel();
/**
* @return the master FQDN
*/
String masterFqdn();
/**
* @return the agent pool name
*/
String agentPoolName();
/**
* @return the agent pool count
*/
int agentPoolCount();
/**
* @return the agent pool leaf domain label
*/
String agentPoolLeafDomainLabel();
/**
* @return the agent pool VM size
*/
ContainerServiceVMSizeTypes agentPoolVMSize();
/**
* @return the agent pool FQDN
*/
String agentPoolFqdn();
/**
* @return the linux root username
*/
String linuxRootUsername();
/**
* @return the linux ssh key
*/
String sshKey();
/**
* @return diagnostics enabled
*/
boolean isDiagnosticsEnabled();
/**
* @return the service principal clientId
*/
String servicePrincipalClientId();
/**
* @return the service principal secret
*/
String servicePrincipalSecret();
// Fluent interfaces
/**
* Container interface for all the definitions related to a container service.
*/
interface Definition extends
ContainerService.DefinitionStages.Blank,
ContainerService.DefinitionStages.WithGroup,
ContainerService.DefinitionStages.WithOrchestrator,
DefinitionStages.WithMasterNodeCount,
DefinitionStages.WithMasterLeafDomainLabel,
DefinitionStages.WithLinux,
DefinitionStages.WithLinuxRootUsername,
DefinitionStages.WithLinuxSshKey,
DefinitionStages.WithAgentPool,
DefinitionStages.WithServicePrincipalProfile,
DefinitionStages.WithDiagnostics,
ContainerService.DefinitionStages.WithCreate {
}
/**
* Grouping of container service definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a container service definition.
*/
interface Blank extends
GroupableResource.DefinitionWithRegion<WithGroup> {
}
/**
* The stage of the container service definition allowing to specify the resource group.
*/
interface WithGroup extends
GroupableResource.DefinitionStages.WithGroup<WithOrchestrator> {
}
/**
* The stage of the container service definition allowing to specify orchestration type.
*/
interface WithOrchestrator {
/**
* Specifies the Swarm orchestration type for the container service.
* @return the next stage of the definition
*/
WithDiagnostics withSwarmOrchestration();
/**
* Specifies the DCOS orchestration type for the container service.
* @return the next stage of the definition
*/
WithDiagnostics withDcosOrchestration();
/**
* Specifies the Kubernetes orchestration type for the container service.
* @return the next stage of the definition
*/
WithServicePrincipalProfile withKubernetesOrchestration();
}
/**
* The stage allowing properties for cluster service principals.
*/
interface WithServicePrincipalProfile {
/**
* Properties for cluster service principals.
* @param clientId The ID for the service principal.
* @param secret The secret password associated with the service principal.
* @return the next stage
*/
WithLinux withServicePrincipal(String clientId, String secret);
}
/**
* The stage of the container service definition allowing to specify the master node count.
*/
interface WithMasterNodeCount {
/**
* Specifies the master node count.
* @param count master profile count (1, 3, 5)
* @return the next stage of the definition
*/
WithMasterLeafDomainLabel withMasterNodeCount(ContainerServiceMasterProfileCount count);
}
/**
* The stage of the container service definition allowing to specify the master Dns label.
*/
interface WithMasterLeafDomainLabel {
/**
* Specifies the master node Dns label.
* @param dnsLabel the Dns prefix
* @return the next stage of the definition
*/
WithAgentPool withMasterLeafDomainLabel(String dnsLabel);
}
/**
* The stage of the container service definition allowing to specify an agent pool profile.
*/
interface WithAgentPool {
/**
* Begins the definition of a agent pool profile to be attached to the container service.
*
* @param name the name for the agent pool profile
* @return the stage representing configuration for the agent pool profile
*/
ContainerServiceAgentPool.DefinitionStages.Blank<WithCreate> defineAgentPool(String name);
}
/**
* The stage of the container service definition allowing the start of defining Linux specific settings.
*/
interface WithLinux {
/**
* Begins the definition to specify Linux settings.
* @return the stage representing configuration of Linux specific settings
*/
WithLinuxRootUsername withLinux();
}
/**
* The stage of the container service definition allowing to specific the Linux root username.
*/
interface WithLinuxRootUsername {
/**
* Begins the definition to specify Linux root username.
* @param rootUserName the root username
* @return the next stage of the definition
*/
WithLinuxSshKey withRootUsername(String rootUserName);
}
/**
* The stage of the container service definition allowing to specific the Linux SSH key.
*/
interface WithLinuxSshKey {
/**
* Begins the definition to specify Linux ssh key.
* @param sshKeyData the SSH key data
* @return the next stage of the definition
*/
WithMasterNodeCount withSshKey(String sshKeyData);
}
/**
* The stage of the container service definition allowing to specific diagnostic settings.
*/
interface WithDiagnostics extends
WithLinux {
/**
* Enable diagnostics.
* @return the create stage of the definition
*/
WithLinux withDiagnostics();
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created, but also allows for any other optional settings to
* be specified.
*/
interface WithCreate extends
Creatable<ContainerService>,
Resource.DefinitionWithTags<WithCreate> {
}
}
/**
* The template for an update operation, containing all the settings that
* can be modified.
*/
interface Update extends
Resource.UpdateWithTags<Update>,
Appliable<ContainerService>,
ContainerService.UpdateStages.WithUpdateAgentPoolCount {
}
/**
* Grouping of container service update stages.
*/
interface UpdateStages {
/**
* The stage of the container service definition allowing to specific diagnostic settings.
*/
interface WithUpdateAgentPoolCount {
/**
* Enables diagnostics.
* @param agentCount the number of agents (VMs) to host docker containers.
* Allowed values must be in the range of 1 to 100 (inclusive).
* The default value is 1.
* @return the next stage of the update
*/
Update withAgentVMCount(int agentCount);
}
}
}
| jianghaolu/azure-sdk-for-java | azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/ContainerService.java | Java | mit | 10,155 |
/*
* Copyright (c) Citrix Systems, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation, with the additional linking exception as
* follows:
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend this exception to your version of
* the library, but you are not obligated to do so. If you do not wish to do
* so, delete this exception statement from your version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.beyondsphere.deprecated;
public enum APIVersion
{
API_1_1, API_1_2, API_1_3, API_1_4, API_1_5, API_1_6, API_1_7, UNKNOWN;
public static APIVersion latest()
{
return API_1_7;
}
public static APIVersion fromMajorMinor(long major, long minor)
{
if (major == 1 && minor == 7)
{
return API_1_7;
}
else if (major == 1 && minor == 6)
{
return API_1_6;
}
else if (major == 1 && minor == 5)
{
return API_1_5;
}
else if (major == 1 && minor == 4)
{
return API_1_4;
}
else if (major == 1 && minor == 3)
{
return API_1_3;
}
else if (major == 1 && minor == 2)
{
return API_1_2;
}
else if (major == 1 && minor == 1)
{
return API_1_1;
}
else
{
return UNKNOWN;
}
}
@Override
public String toString()
{
switch (this)
{
case API_1_1:
return "1.1";
case API_1_2:
return "1.2";
case API_1_3:
return "1.3";
case API_1_4:
return "1.4";
case API_1_5:
return "1.5";
case API_1_6:
return "1.6";
case API_1_7:
return "1.7";
default:
return "Unknown";
}
}
}
| Hearen/OnceServer | pool_management/bn-xend-core/src/main/java/com/beyondsphere/deprecated/APIVersion.java | Java | mit | 3,325 |
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.aws.context.config.annotation.EnableContextInstanceData;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableContextInstanceData
public class WeatherServiceApplication {
public static void main(String[] args) {
SpringApplication.run(WeatherServiceApplication.class, args);
}
}
| vincentortajada/microservices-playground | weather-service/src/main/java/com/example/WeatherServiceApplication.java | Java | mit | 536 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.rx;
import com.azure.cosmos.CosmosAsyncClient;
import com.azure.cosmos.CosmosAsyncContainer;
import com.azure.cosmos.models.CosmosTriggerResponse;
import com.azure.cosmos.CosmosClientBuilder;
import com.azure.cosmos.CosmosResponseValidator;
import com.azure.cosmos.models.CosmosTriggerProperties;
import com.azure.cosmos.models.TriggerOperation;
import com.azure.cosmos.models.TriggerType;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Factory;
import org.testng.annotations.Test;
import reactor.core.publisher.Mono;
import java.util.UUID;
public class TriggerUpsertReplaceTest extends TestSuiteBase {
private CosmosAsyncContainer createdCollection;
private CosmosAsyncClient client;
@Factory(dataProvider = "clientBuildersWithDirect")
public TriggerUpsertReplaceTest(CosmosClientBuilder clientBuilder) {
super(clientBuilder);
}
@Test(groups = { "simple" }, timeOut = TIMEOUT)
public void replaceTrigger() throws Exception {
// create a trigger
CosmosTriggerProperties trigger = new CosmosTriggerProperties(
UUID.randomUUID().toString(),
"function() {var x = 10;}"
);
trigger.setTriggerOperation(TriggerOperation.CREATE);
trigger.setTriggerType(TriggerType.PRE);
CosmosTriggerProperties readBackTrigger = createdCollection.getScripts().createTrigger(trigger).block().getProperties();
// read trigger to validate creation
waitIfNeededForReplicasToCatchUp(getClientBuilder());
Mono<CosmosTriggerResponse> readObservable = createdCollection.getScripts().getTrigger(readBackTrigger.getId()).read();
// validate trigger creation
CosmosResponseValidator<CosmosTriggerResponse> validatorForRead = new CosmosResponseValidator.Builder<CosmosTriggerResponse>()
.withId(readBackTrigger.getId())
.withTriggerBody("function() {var x = 10;}")
.withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE)
.notNullEtag()
.build();
validateSuccess(readObservable, validatorForRead);
//update getTrigger
readBackTrigger.setBody("function() {var x = 11;}");
Mono<CosmosTriggerResponse> updateObservable = createdCollection.getScripts().getTrigger(readBackTrigger.getId()).replace(readBackTrigger);
// validate getTrigger replace
CosmosResponseValidator<CosmosTriggerResponse> validatorForUpdate = new CosmosResponseValidator.Builder<CosmosTriggerResponse>()
.withId(readBackTrigger.getId())
.withTriggerBody("function() {var x = 11;}")
.withTriggerInternals(TriggerType.PRE, TriggerOperation.CREATE)
.notNullEtag()
.build();
validateSuccess(updateObservable, validatorForUpdate);
}
@BeforeClass(groups = { "simple" }, timeOut = SETUP_TIMEOUT)
public void before_TriggerUpsertReplaceTest() {
client = getClientBuilder().buildAsyncClient();
createdCollection = getSharedMultiPartitionCosmosContainer(client);
truncateCollection(createdCollection);
}
@AfterClass(groups = { "simple" }, timeOut = SHUTDOWN_TIMEOUT, alwaysRun = true)
public void afterClass() {
safeClose(client);
}
}
| selvasingh/azure-sdk-for-java | sdk/cosmos/azure-cosmos/src/test/java/com/azure/cosmos/rx/TriggerUpsertReplaceTest.java | Java | mit | 3,492 |
/*
* Copyright (c) 2016 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* sisane-server: Helps you to develop easily AJAX web applications
* by copying and modifying this Java Server.
*
* Sources at https://github.com/rafaelaznar/sisane-server
*
* sisane-server is distributed under the MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.daw.dao.implementation;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.implementation.PusuarioBean;
import net.daw.bean.implementation.ZonaBean;
import net.daw.dao.publicinterface.TableDaoInterface;
import net.daw.dao.publicinterface.ViewDaoInterface;
import net.daw.data.implementation.MysqlData;
import net.daw.helper.statics.AppConfigurationHelper;
import net.daw.helper.statics.EncodingUtilHelper;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.SqlBuilder;
public class ZonaDao implements ViewDaoInterface<ZonaBean>, TableDaoInterface<ZonaBean> {
private String strTable = "zona";
private String strSQL = "select * from zona where 1=1 ";
private MysqlData oMysql = null;
private Connection oConnection = null;
private PusuarioBean oPuserSecurity = null;
public ZonaDao(Connection oPooledConnection, PusuarioBean oPuserBean_security) throws Exception {
try {
oConnection = oPooledConnection;
oMysql = new MysqlData(oConnection);
oPuserSecurity = oPuserBean_security;
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
}
}
@Override
public Long getCount(ArrayList<FilterBeanHelper> hmFilter) throws Exception {
strSQL += SqlBuilder.buildSqlWhere(hmFilter);
Long pages = 0L;
try {
pages = oMysql.getCount(strSQL);
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
}
return pages;
}
@Override
public ArrayList<ZonaBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
strSQL += SqlBuilder.buildSqlWhere(alFilter);
strSQL += SqlBuilder.buildSqlOrder(hmOrder);
strSQL += SqlBuilder.buildSqlLimit(oMysql.getCount(strSQL), intRegsPerPag, intPage);
ArrayList<ZonaBean> arrZona = new ArrayList<>();
ResultSet oResultSet = null;
try {
oResultSet = oMysql.getAllSQL(strSQL);
while (oResultSet.next()) {
ZonaBean oZonaBean = new ZonaBean();
arrZona.add((ZonaBean) oZonaBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
}
if (oResultSet != null) {
oResultSet.close();
}
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oResultSet != null) {
oResultSet.close();
}
}
return arrZona;
}
@Override
public ArrayList<ZonaBean> getAll(ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
strSQL += SqlBuilder.buildSqlWhere(alFilter);
strSQL += SqlBuilder.buildSqlOrder(hmOrder);
ArrayList<ZonaBean> arrZona = new ArrayList<>();
ResultSet oResultSet = null;
try {
oResultSet = oMysql.getAllSQL(strSQL);
while (oResultSet.next()) {
ZonaBean oZonaBean = new ZonaBean();
arrZona.add((ZonaBean) oZonaBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
}
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oResultSet != null) {
oResultSet.close();
}
}
return arrZona;
}
@Override
public ZonaBean get(ZonaBean oZonaBean, Integer expand) throws Exception {
if (oZonaBean.getId() > 0) {
ResultSet oResultSet = null;
try {
oResultSet = oMysql.getAllSQL(strSQL + " And id= " + oZonaBean.getId() + " ");
Boolean empty = true;
while (oResultSet.next()) {
oZonaBean = (ZonaBean) oZonaBean.fill(oResultSet, oConnection, oPuserSecurity, expand);
empty = false;
}
if (empty) {
oZonaBean.setId(0);
}
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
} finally {
if (oResultSet != null) {
oResultSet.close();
}
}
} else {
oZonaBean.setId(0);
}
return oZonaBean;
}
@Override
public Integer set(ZonaBean oZonaBean) throws Exception {
Integer iResult = null;
try {
if (oZonaBean.getId() == 0) {
strSQL = "INSERT INTO " + strTable + " ";
strSQL += "(" + oZonaBean.getColumns() + ")";
strSQL += "VALUES(" + oZonaBean.getValues() + ")";
iResult = oMysql.executeInsertSQL(strSQL);
} else {
strSQL = "UPDATE " + strTable + " ";
strSQL += " SET " + oZonaBean.toPairs();
strSQL += " WHERE id=" + oZonaBean.getId();
iResult = oMysql.executeUpdateSQL(strSQL);
}
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
}
return iResult;
}
@Override
public Integer remove(Integer id) throws Exception {
int result = 0;
try {
result = oMysql.removeOne(id, strTable);
} catch (Exception ex) {
Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
throw new Exception();
}
return result;
}
}
| adrianRodriguez123/sisane-server | src/main/java/net/daw/dao/implementation/ZonaDao.java | Java | mit | 7,703 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.policy.v2018_05_01.implementation;
import java.util.List;
import com.microsoft.azure.management.policy.v2018_05_01.PolicySku;
import com.microsoft.azure.management.policy.v2018_05_01.Identity;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.ProxyResource;
/**
* The policy assignment.
*/
@JsonFlatten
public class PolicyAssignmentInner extends ProxyResource {
/**
* The display name of the policy assignment.
*/
@JsonProperty(value = "properties.displayName")
private String displayName;
/**
* The ID of the policy definition or policy set definition being assigned.
*/
@JsonProperty(value = "properties.policyDefinitionId")
private String policyDefinitionId;
/**
* The scope for the policy assignment.
*/
@JsonProperty(value = "properties.scope")
private String scopeProperty;
/**
* The policy's excluded scopes.
*/
@JsonProperty(value = "properties.notScopes")
private List<String> notScopes;
/**
* Required if a parameter is used in policy rule.
*/
@JsonProperty(value = "properties.parameters")
private Object parameters;
/**
* This message will be part of response in case of policy violation.
*/
@JsonProperty(value = "properties.description")
private String description;
/**
* The policy assignment metadata.
*/
@JsonProperty(value = "properties.metadata")
private Object metadata;
/**
* The policy sku. This property is optional, obsolete, and will be
* ignored.
*/
@JsonProperty(value = "sku")
private PolicySku sku;
/**
* The location of the policy assignment. Only required when utilizing
* managed identity.
*/
@JsonProperty(value = "location")
private String location;
/**
* The managed identity associated with the policy assignment.
*/
@JsonProperty(value = "identity")
private Identity identity;
/**
* Get the display name of the policy assignment.
*
* @return the displayName value
*/
public String displayName() {
return this.displayName;
}
/**
* Set the display name of the policy assignment.
*
* @param displayName the displayName value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withDisplayName(String displayName) {
this.displayName = displayName;
return this;
}
/**
* Get the ID of the policy definition or policy set definition being assigned.
*
* @return the policyDefinitionId value
*/
public String policyDefinitionId() {
return this.policyDefinitionId;
}
/**
* Set the ID of the policy definition or policy set definition being assigned.
*
* @param policyDefinitionId the policyDefinitionId value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withPolicyDefinitionId(String policyDefinitionId) {
this.policyDefinitionId = policyDefinitionId;
return this;
}
/**
* Get the scope for the policy assignment.
*
* @return the scopeProperty value
*/
public String scopeProperty() {
return this.scopeProperty;
}
/**
* Set the scope for the policy assignment.
*
* @param scopeProperty the scopeProperty value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withScopeProperty(String scopeProperty) {
this.scopeProperty = scopeProperty;
return this;
}
/**
* Get the policy's excluded scopes.
*
* @return the notScopes value
*/
public List<String> notScopes() {
return this.notScopes;
}
/**
* Set the policy's excluded scopes.
*
* @param notScopes the notScopes value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withNotScopes(List<String> notScopes) {
this.notScopes = notScopes;
return this;
}
/**
* Get required if a parameter is used in policy rule.
*
* @return the parameters value
*/
public Object parameters() {
return this.parameters;
}
/**
* Set required if a parameter is used in policy rule.
*
* @param parameters the parameters value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withParameters(Object parameters) {
this.parameters = parameters;
return this;
}
/**
* Get this message will be part of response in case of policy violation.
*
* @return the description value
*/
public String description() {
return this.description;
}
/**
* Set this message will be part of response in case of policy violation.
*
* @param description the description value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withDescription(String description) {
this.description = description;
return this;
}
/**
* Get the policy assignment metadata.
*
* @return the metadata value
*/
public Object metadata() {
return this.metadata;
}
/**
* Set the policy assignment metadata.
*
* @param metadata the metadata value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withMetadata(Object metadata) {
this.metadata = metadata;
return this;
}
/**
* Get the policy sku. This property is optional, obsolete, and will be ignored.
*
* @return the sku value
*/
public PolicySku sku() {
return this.sku;
}
/**
* Set the policy sku. This property is optional, obsolete, and will be ignored.
*
* @param sku the sku value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withSku(PolicySku sku) {
this.sku = sku;
return this;
}
/**
* Get the location of the policy assignment. Only required when utilizing managed identity.
*
* @return the location value
*/
public String location() {
return this.location;
}
/**
* Set the location of the policy assignment. Only required when utilizing managed identity.
*
* @param location the location value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withLocation(String location) {
this.location = location;
return this;
}
/**
* Get the managed identity associated with the policy assignment.
*
* @return the identity value
*/
public Identity identity() {
return this.identity;
}
/**
* Set the managed identity associated with the policy assignment.
*
* @param identity the identity value to set
* @return the PolicyAssignmentInner object itself.
*/
public PolicyAssignmentInner withIdentity(Identity identity) {
this.identity = identity;
return this;
}
}
| selvasingh/azure-sdk-for-java | sdk/policy/mgmt-v2018_05_01/src/main/java/com/microsoft/azure/management/policy/v2018_05_01/implementation/PolicyAssignmentInner.java | Java | mit | 7,625 |
package com.javaonlinecourse.b2lesson4.classwork.items;
/**
* @author emitrohin
* @version 1.0
* 19.11.2016
*/
public class IPad extends ShopItem {
public IPad(String name, String description, int price) {
super(name, description, price);
}
}
| javaonlinecourse/group07_ | src/main/java/com/javaonlinecourse/b2lesson4/classwork/items/IPad.java | Java | mit | 273 |
/* MACHINE GENERATED FILE, DO NOT EDIT */
package org.lwjgl.opencl;
import org.lwjgl.*;
import java.nio.*;
public final class AMDDeviceMemoryFlags {
/**
* Alloc from GPU's CPU visible heap.
*/
public static final int CL_MEM_USE_PERSISTENT_MEM_AMD = 0x40;
private AMDDeviceMemoryFlags() {}
}
| eriqadams/computer-graphics | lib/lwjgl-2.9.1/lwjgl-source-2.9.1/src/generated/org/lwjgl/opencl/AMDDeviceMemoryFlags.java | Java | mit | 304 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.kusto.v2019_09_07;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.kusto.v2019_09_07.implementation.KustoManager;
import com.microsoft.azure.management.kusto.v2019_09_07.implementation.FollowerDatabaseDefinitionInner;
/**
* Type representing FollowerDatabaseDefinition.
*/
public interface FollowerDatabaseDefinition extends HasInner<FollowerDatabaseDefinitionInner>, HasManager<KustoManager> {
/**
* @return the attachedDatabaseConfigurationName value.
*/
String attachedDatabaseConfigurationName();
/**
* @return the clusterResourceId value.
*/
String clusterResourceId();
/**
* @return the databaseName value.
*/
String databaseName();
}
| selvasingh/azure-sdk-for-java | sdk/kusto/mgmt-v2019_09_07/src/main/java/com/microsoft/azure/management/kusto/v2019_09_07/FollowerDatabaseDefinition.java | Java | mit | 1,070 |
package flounder.networking;
import java.net.*;
/**
* A class that can be extended to create packets that are sent between servers and clients.
*/
public abstract class Packet {
/**
* Writes the data from the client to the server.
*
* @param client The client to send the data from.
*/
public abstract void writeData(Client client);
/**
* Writes the data from the server to all connected clients.
*
* @param server The server to send the data from.
*/
public abstract void writeData(Server server);
/**
* Reads bytes of data to get the packets contents.
*
* @param data The data to read.
*
* @return The message read from the data.
*/
public String readData(byte[] data) {
String dataString = new String(data).trim();
return dataString.substring(1, dataString.length()).split("]:")[1];
}
/**
* This is update when the client receives the packet.
*
* @param client The client that is processing the packet.
* @param address The address where the data came from.
* @param port The port the data came from.
*/
public abstract void clientHandlePacket(Client client, InetAddress address, int port);
/**
* This is update when the server receives the packet.
*
* @param server The server that is processing the packet.
* @param address The address where the data came from.
* @param port The port the data came from.
*/
public abstract void serverHandlePacket(Server server, InetAddress address, int port);
/**
* Gets the data contained in the packet.
*
* @return The data contained.
*/
public abstract byte[] getData();
/**
* Gets the packet class prefix, should be appended to the packets message before {@link #getData()}.
*
* @return The packets class prefix.
*/
public String getDataPrefix() {
return "[" + this.getClass().getName() + "]:";
}
}
| mattparks/Flounder-Engine | src/flounder/networking/Packet.java | Java | mit | 1,845 |
package com.merakianalytics.orianna.types.core.match;
import java.util.Collections;
import java.util.List;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.merakianalytics.orianna.types.common.Platform;
import com.merakianalytics.orianna.types.core.OriannaObject;
import com.merakianalytics.orianna.types.core.searchable.Searchable;
import com.merakianalytics.orianna.types.core.staticdata.ReforgedRune;
import com.merakianalytics.orianna.types.core.staticdata.Versions;
public class RuneStats extends OriannaObject<com.merakianalytics.orianna.types.data.match.RuneStats> {
private static final long serialVersionUID = 3663530937677122757L;
private final Supplier<ReforgedRune> rune = Suppliers.memoize(new Supplier<ReforgedRune>() {
@Override
public ReforgedRune get() {
if(coreData.getId() == 0) {
return null;
}
final String version = Versions.withPlatform(Platform.withTag(coreData.getPlatform())).get().getBestMatch(coreData.getVersion());
return ReforgedRune.withId(coreData.getId()).withPlatform(Platform.withTag(coreData.getPlatform())).withVersion(version).get();
}
});
private final Supplier<List<Integer>> variables = Suppliers.memoize(new Supplier<List<Integer>>() {
@Override
public List<Integer> get() {
if(coreData.getVariables() == null) {
return null;
}
return Collections.unmodifiableList(coreData.getVariables());
}
});
public RuneStats(final com.merakianalytics.orianna.types.data.match.RuneStats coreData) {
super(coreData);
}
@Searchable({ReforgedRune.class, String.class, int.class})
public ReforgedRune getRune() {
return rune.get();
}
public List<Integer> getVariables() {
return variables.get();
}
}
| robrua/Orianna | orianna/src/main/java/com/merakianalytics/orianna/types/core/match/RuneStats.java | Java | mit | 1,913 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.