repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
orbeon/orbeon-forms | src/main/java/org/orbeon/oxf/processor/SchedulerProcessor.java | 11050 | /**
* Copyright (C) 2004 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later 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 Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.processor;
import org.orbeon.dom.Document;
import org.orbeon.dom.Element;
import org.orbeon.dom.QName;
import org.orbeon.oxf.common.OXFException;
import org.orbeon.oxf.externalcontext.ExternalContext;
import org.orbeon.oxf.externalcontext.WebAppExternalContext;
import org.orbeon.oxf.pipeline.InitUtils;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.pipeline.api.ProcessorDefinition;
import org.orbeon.oxf.util.DateUtilsUsingSaxon;
import org.orbeon.oxf.util.LoggerFactory;
import org.orbeon.oxf.util.task.Task;
import org.orbeon.oxf.util.task.TaskScheduler;
import org.orbeon.oxf.xml.XPathUtils;
import org.orbeon.oxf.xml.dom.Extensions;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class SchedulerProcessor extends ProcessorImpl {
private static final org.slf4j.Logger logger = LoggerFactory.createLoggerJava(SchedulerProcessor.class);
public static final String SCHEDULER_CONFIG_NAMESPACE_URI = "http://www.orbeon.com/oxf/scheduler";
public SchedulerProcessor() {
addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, SCHEDULER_CONFIG_NAMESPACE_URI));
}
public void start(PipelineContext context) {
try {
List configs = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader<List>() {
public List read(PipelineContext context, ProcessorInput input) {
List configs = new ArrayList();
Document document = readInputAsOrbeonDom(context, input);
for (Iterator i = XPathUtils.selectNodeIterator(document, "/config/start-task"); i.hasNext();) {
Element startTaskElement = (Element) i.next();
Config config = new Config(Config.START);
config.setName(XPathUtils.selectStringValueNormalize(startTaskElement, "name"));
// Create new processor definition
final ProcessorDefinition processorDefinition;
{
// Use processor QName
final Element processorNameElement = startTaskElement.element(QName.apply("processor-name"));
final QName processorQName = Extensions.resolveTextValueQNameJava(processorNameElement, true);
processorDefinition = new ProcessorDefinition(processorQName);
for (final Iterator j = XPathUtils.selectNodeIterator(startTaskElement, "input"); j.hasNext();) {
Element inputElement = (Element) j.next();
String name = inputElement.attributeValue("name");
String url = inputElement.attributeValue("url");
if (url != null) {
processorDefinition.addInput(name, url);
} else {
final Iterator it = inputElement.jElementIterator();
if (it.hasNext()) {
final Element srcElt = (Element) it.next();
final Element elt = (Element) srcElt.deepCopy();
processorDefinition.addInput(name, elt);
} else
throw new OXFException("Node not found input element");
}
}
}
config.setProcessorDefinition(processorDefinition);
String startTimeString = XPathUtils.selectStringValueNormalize(startTaskElement, "start-time");
long startTime = 0;
if ("now".equalsIgnoreCase(startTimeString)) {
startTime = System.currentTimeMillis();
} else {
startTime = DateUtilsUsingSaxon.parseISODateOrDateTime(startTimeString);
}
config.setStartTime(startTime);
String interval = XPathUtils.selectStringValueNormalize(startTaskElement, "interval");
try {
config.setInterval(Long.parseLong(interval));
} catch (NumberFormatException e) {
throw new OXFException("Unsupported long value", e);
}
String sync = XPathUtils.selectStringValueNormalize(startTaskElement, "synchronized");
config.setSynchro(Boolean.valueOf(sync).booleanValue());
configs.add(config);
}
for (Iterator i = XPathUtils.selectNodeIterator(document, "/config/stop-task"); i.hasNext();) {
Element el = (Element) i.next();
Config config = new Config(Config.STOP);
config.setName(XPathUtils.selectStringValueNormalize(el, "name"));
configs.add(config);
}
return configs;
}
});
ExternalContext externalContext = (ExternalContext) context.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
TaskScheduler scheduler = TaskScheduler.getInstance(externalContext.getWebAppContext());
//assert externalContext != null;
for (Iterator i = configs.iterator(); i.hasNext();) {
Config config = (Config) i.next();
switch (config.getAction()) {
case Config.START:
// Create processor and connect its inputs
Processor processor = InitUtils.createProcessor(config.getProcessorDefinition());
processor.setId(config.getName());
// Create and schedule a task
// NOTE: The ExternalContext passed:
// - has visibility on the application context only
// - doesn't keep references to the current context
ProcessorTask task = new ProcessorTask(config.getName(), processor, config.isSynchro(),
new WebAppExternalContext(externalContext.getWebAppContext(), scala.Option.apply((HttpSession) null)));
task.setSchedule(config.getStartTime(), config.getInterval());
scheduler.schedule(task);
break;
case Config.STOP:
// Find task and cancel it
Task[] tasks = scheduler.getRunningTasks();
for (int ti = 0; ti < tasks.length; ti++) {
if (tasks[ti] instanceof ProcessorTask && (tasks[ti]).getName().equals(config.getName()))
tasks[ti].cancel();
}
break;
}
}
} catch (Exception e) {
throw new OXFException(e);
}
}
private static class ProcessorTask extends Task {
private final static String RUNNING = "running";
private final static String WAITING = "waiting";
private Processor processor;
private ExternalContext externalContext;
private String name;
private String status = WAITING;
private boolean sync;
public ProcessorTask(String name, Processor processor, boolean sync, ExternalContext externalContext) {
this.name = name;
this.processor = processor;
this.sync = sync;
this.externalContext = externalContext;
}
public String getName() {
return name;
}
synchronized public String getStatus() {
return status;
}
synchronized public void setStatus(boolean running) {
if (running)
status = RUNNING;
else
status = WAITING;
}
public void run() {
try {
if (sync && getStatus().equals(RUNNING)) {
if (logger.isInfoEnabled())
logger.info("Task: " + getName() + " won't run since it is already running");
} else {
setStatus(true);
InitUtils.runProcessor(processor, externalContext, new PipelineContext(), logger);
setStatus(false);
}
} catch (Exception e) {
setStatus(false);
throw new OXFException(e);
}
}
}
private static class Config {
public static final int START = 0;
public static final int STOP = 1;
private int action;
private String name;
private ProcessorDefinition processorDefinition;
private long startTime;
private long interval;
private boolean synchro = true;
public Config(int action) {
this.action = action;
}
public int getAction() {
return action;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getInterval() {
return interval;
}
public void setInterval(long interval) {
this.interval = interval;
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public boolean isSynchro() {
return synchro;
}
public void setSynchro(boolean synchro) {
this.synchro = synchro;
}
public ProcessorDefinition getProcessorDefinition() {
return processorDefinition;
}
public void setProcessorDefinition(ProcessorDefinition processorDefinition) {
this.processorDefinition = processorDefinition;
}
}
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/extensions-toc/src/main/java/org/pentaho/reporting/engine/classic/extensions/toc/TocElementType.java | 1506 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2002-2013 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.extensions.toc;
import org.pentaho.reporting.engine.classic.core.ReportElement;
import org.pentaho.reporting.engine.classic.core.filter.types.bands.AbstractSectionType;
import org.pentaho.reporting.engine.classic.core.function.ExpressionRuntime;
public class TocElementType extends AbstractSectionType {
public static final TocElementType INSTANCE = new TocElementType();
public TocElementType() {
super( "toc", true );
}
public ReportElement create() {
return new TocElement();
}
public Object getDesignValue( final ExpressionRuntime runtime, final ReportElement element ) {
return "Table-Of-Contents";
}
}
| lgpl-2.1 |
varkhan/VCom4j | Data/VisualDiff/src/net/varkhan/data/diff/EugeneMyersDiff.java | 8182 | package net.varkhan.data.diff;
import net.varkhan.base.containers.Collection;
import net.varkhan.base.containers.Container;
import net.varkhan.base.containers.Iterable;
import net.varkhan.base.containers.Iterator;
import net.varkhan.base.containers.array.Arrays;
import net.varkhan.base.containers.list.List;
import net.varkhan.base.containers.list.ArrayList;
import java.util.Comparator;
/**
* <b></b>.
* <p/>
* Eugene Myers: "An O(ND) Difference Algorithm and its Variations", in Algorithmica Vol. 1 No. 2, 1986, p 251.
*
* @author varkhan
* @date 9/21/14
* @time 3:00 PM
*/
public class EugeneMyersDiff<T, S extends Container<T>, X> implements Diff<T,S,X> {
protected final Comparator<T> comp;
public EugeneMyersDiff(Comparator<T> comp) {
this.comp=comp;
}
@Override
@SuppressWarnings("unchecked")
public Iterable<Diff.Block<T>> invoke(S srcL, S srcR, X ctx) {
Object[] datL=getArray(srcL);
Object[] datR=getArray(srcR);
int max = datL.length + datR.length + 1;
// edits for the begin sequence
int[] begE=new int[2*max+2];
// edits for the end sequence
int[] endE=new int[2*max+2];
boolean[] edtR = new boolean[datL.length+2];
boolean[] edtL = new boolean[datR.length+2];
LCS(datL, edtL, 0, datL.length, datR, edtR, 0, datR.length, begE, endE);
return GDB(datL, edtL, datR, edtR);
}
protected Object[] getArray(S src) {
Object[] dat = new Object[(int)src.size()];
int i = 0;
for(Iterator<? extends T> it=src.iterator();it.hasNext();) {
dat[i++] = it.next();
}
return dat;
}
@SuppressWarnings("unchecked")
protected boolean equals(Object l, Object r) {
return comp.compare((T)l,(T)r)==0;
}
/**
* An implementation of the longest common-subsequence (LCS) that looks for
* optimal subsequences anchored at either end of the specified boundaries.
*
* @param datL the left-side data
* @param edtL the left-side edit flags
* @param begL the left-side start position
* @param endL the left-side end position
* @param datR the right-side data
* @param edtR the right-side edit flags
* @param begR the right-side start position
* @param endR the right-side end position
* @param begE start-side edit sequence
* @param endE end-side edit sequence
*/
protected void LCS(Object[] datL, boolean[] edtL, int begL, int endL, Object[] datR, boolean[] edtR, int begR, int endR, int[] begE, int[] endE) {
// skip identical beg sequences
while( begL<endL && begR<endR && equals(datL[begL],datR[begR]) ) {
begL++;
begR++;
}
// skip identical end sequences
while( begL<endL && begR<endR && equals(datL[endL-1],datR[endR-1]) ) {
--endL;
--endR;
}
// Insertions and deletions
if(begL==endL) {
while(begR<endR) edtR[begR++]=true;
}
else if(begR==endR) {
while(begL<endL) edtL[begL++]=true;
}
else {
// Compute the shortest middle snake (l,r), to get the optimal path
int[] sms=SMS(datL, begL, endL, datR, begR, endR, begE, endE);
// The path is from beg to (l,r) and from (l,r) to end
LCS(datL, edtL, begL, sms[0], datR, edtR, begR, sms[1], begE, endE);
LCS(datL, edtL, sms[0], endL, datR, edtR, sms[1], endR, begE, endE);
}
}
/**
* Look for the Shortest Middle Snake between the specified boundaries.
*
* @param datL the left-side data
* @param begL the left-side start position
* @param endL the left-side end position
* @param datR the right-side data
* @param begR the right-side start position
* @param endR the right-side end position
* @param begE start-side edit sequence
* @param endE end-side edit sequence
* @return the positions of the shortest middle snake
*/
protected int[] SMS(Object[] datL, int begL, int endL, Object[] datR, int begR, int endR, int[] begE, int[] endE) {
int max = datL.length+datR.length+1;
// Beg search starts at this Kline
int begK = begL-begR;
// End search starts at this K-line
int endK = endL-endR;
// The original algo uses arrays that accepts negative indices.
// We use 0-based arrays instead, and add respective offsets:
// beg0 for begE / end0 for endE
int beg0 = max-begK;
int end0 = max-endK;
int difD=(endL-begL)-(endR-begR);
boolean odd = (difD&1)!=0;
int maxD= ((endL-begL+endR-begR)/2) + 1;
// init vectors
begE[beg0+begK+1]=begL;
endE[end0+endK-1]=endL;
for(int d=0; d<=maxD; d++) {
// Extend the forward path.
for(int k=begK-d; k<=begK+d; k+=2) {
// Find the starting point
int x, y;
if(k==begK-d) x=begE[beg0+k+1]; // down
else {
x=begE[beg0+k-1]+1; // right
if(k<begK+d && begE[beg0+k+1]>=x) x=begE[beg0+k+1]; // down
}
y=x-k;
// Find the end of the furthest reaching forward d-path in diagonal k.
while( x<endL && y<endR && equals(datL[x],datR[y]) ) {
x++;
y++;
}
begE[beg0+k]=x;
// overlap ?
if(odd && endK-d<k && k<endK+d) {
if(endE[end0+k] <= begE[beg0+k]) {
return new int[] { begE[beg0+k], begE[beg0+k]-k };
}
}
}
// Extend the reverse path.
for(int k=endK-d; k<=endK+d; k+=2) {
// Find the starting point
int x, y;
if(k==endK+d) x=endE[end0+k-1]; // up
else {
x=endE[end0+k+1]-1; // left
if(k>endK-d && endE[end0+k-1]<x) x=endE[end0+k-1]; // up
}
y=x-k;
// Find the end of the furthest reaching backward d-path in diagonal k.
while( x>begL && y>begR && equals(datL[x-1],datR[y-1]) ) {
x--;
y--;
}
endE[end0+k]=x;
// overlap ?
if(!odd && begK-d<=k && k<=begK+d) {
if(endE[end0+k] <= begE[beg0+k]) {
return new int[] { begE[beg0+k], begE[beg0+k]-k };
}
}
}
}
// We should never get there
throw new RuntimeException("Ran out of possible edits!");
}
/**
* Scan the edit sequences on both sides, start to end, to generate the edit script.
*
* @param datL the left-side data
* @param edtL the left-side edit flags
* @param datR the right-side data
* @param edtR the right-side edit flags
* @return the sequence of diff blocks
*/
protected Collection<Diff.Block<T>> GDB(Object[] datL, boolean[] edtL, Object[] datR, boolean edtR[]) {
Collection<Diff.Block<T>> c = new ArrayList<Diff.Block<T>>();
final List datLa = Arrays.asList(datL);
final List datRa = Arrays.asList(datR);
int lenR=datR.length;
int lenL=datL.length;
int endL=0;
int endR=0;
while(endL<lenL||endR<lenR) {
// Unchanged
if(endL<lenL&& !edtL[endL]&&endR<lenR&& !edtR[endR]) {
endL++;
endR++;
}
// Edited
else {
int begL=endL;
int begR=endR;
while(endL<lenL&& (endR>=lenR||edtL[endL])) endL++;
while(endR<lenR&& (endL>=lenL||edtR[endR])) endR++;
if( begL<endL || begR<endR ) {
c.add(new DiffBlock<T>(datLa, begL, endL, datRa, begR, endR));
}
}
}
return c;
}
}
| lgpl-2.1 |
RapidProjectH2020/offloading-framework-linux | rapid-gvirtus4j/src/eu/project/rapid/gvirtus4j/Buffer.java | 3270 | package eu.project.rapid.gvirtus4j;
import java.io.IOException;
public final class Buffer {
static {
try {
// FIXME: check for OS type before loading the lib
Util.loadNativLibFromResources(Buffer.class.getClassLoader(), "libs/libnative-lib.jnilib");
// Util.loadNativLibFromResources(Buffer.class.getClassLoader(), "libs/libnative-lib.so");
} catch (UnsatisfiedLinkError e) {
System.err.println("JniTest - " + "UnsatisfiedLinkError, could not load native library: " + e);
e.printStackTrace();
} catch (IOException e) {
System.err.println("JniTest - " + "IOException, could not load native library: " + e);
}
}
private static String mpBuffer = "";
public Buffer() {
mpBuffer = "";
}
static void clear() {
mpBuffer = "";
}
public static void AddPointerNull() {
byte[] bites = {(byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0};
mpBuffer += Util.bytesToHex(bites);
}
static void Add(int item) {
byte[] bites = {(byte) item, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0};
mpBuffer += Util.bytesToHex(bites);
}
static void Add(long item) {
byte[] bites = {(byte) item, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0, (byte) 0};
mpBuffer += Util.bytesToHex(bites);
}
static void Add(String item) {
byte[] bites = Util.hexToBytes(item);
mpBuffer += Util.bytesToHex(bites);
}
static void Add(float[] item) {
String js = prepareFloat(item); // invoke the native method
mpBuffer += js;
}
static void Add(int[] item) {
Add(item.length * 4);
for (int i = 0; i < item.length; i++) {
AddInt(item[i]);
}
}
static void AddInt(int item) {
byte[] bits = Util.intToByteArray(item);
mpBuffer += Util.bytesToHex(bits);
}
static void AddPointer(int item) {
byte[] bites = {(byte) item, (byte) 0, (byte) 0, (byte) 0};
int size = (Util.Sizeof.INT);
Add(size);
mpBuffer += Util.bytesToHex(bites);
}
static String GetString() {
return mpBuffer;
}
static long Size() {
return mpBuffer.length();
}
static void AddStruct(CudaDeviceProp struct) {
byte[] bites = new byte[640];
bites[0] = (byte) 0x78;
bites[1] = (byte) 0x02;
for (int i = 2; i < 640; i++) {
bites[i] = (byte) 0;
}
mpBuffer += Util.bytesToHex(bites);
}
static void AddByte(int i) {
String jps = prepareSingleByte(i); // invoke the native method
mpBuffer += jps;
}
static void AddByte4Ptx(String ptxSource, long size) {
String jps = preparePtxSource(ptxSource, size); // invoke the native method
mpBuffer += jps;
}
public static void printMpBuffer() {
System.out.println("mpBUFFER : " + mpBuffer);
}
public static native String prepareFloat(float[] floats);
public static native String preparePtxSource(String ptxSource, long size);
public static native String prepareSingleByte(int i);
}
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/owscommon_new/Metadata.java | 2586 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.owscommon_new;
import java.net.URI;
import org.deegree.datatypes.xlink.SimpleLink;
/**
* <code>Metadata</code> encapsulates generic meta data according to the OWS common specification
* 1.0.0.
*
* @author <a href="mailto:schmitz@lat-lon.de">Andreas Schmitz</a>
* @author last edited by: $Author$
*
* @version 2.0, $Revision$, $Date$
*
* @since 2.0
*/
public class Metadata {
private SimpleLink link;
private URI about;
// not sure if this makes actual sense
private Object metadata;
/**
* Standard constructor that initializes all encapsulated data.
*
* @param link
* @param about
* @param metadata
*/
public Metadata( SimpleLink link, URI about, Object metadata ) {
this.link = link;
this.about = about;
this.metadata = metadata;
}
/**
* @return Returns the about.
*/
public URI getAbout() {
return about;
}
/**
* @return Returns the link.
*/
public SimpleLink getLink() {
return link;
}
/**
* @return Returns the metadata.
*/
public Object getMetadata() {
return metadata;
}
}
| lgpl-2.1 |
dirktrossen/AIRS | src/com/airs/helper/SelectCameraPathPreference.java | 3796 | /*
Copyright (C) 2013, TecVis LP, support@tecvis.co.uk
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation as version 2.1 of the License.
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 Lesser General Public
License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.airs.helper;
import java.io.File;
import com.airs.R;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.widget.Toast;
public class SelectCameraPathPreference extends Activity
{
// activity result code
private static final int SELECT_PHOTO = 100;
private SharedPreferences settings;
/** Called when the activity is first created.
* @param savedInstanceState a Bundle of the saved state, according to Android lifecycle model
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// get settings
settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
// start picture selector
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
// show toast for user
Toast.makeText(getApplicationContext(), getString(R.string.Camera_path_select), Toast.LENGTH_LONG).show();
}
/** Called when the configuration of the activity has changed.
* @param newConfig new configuration after change
*/
@Override
public void onConfigurationChanged(Configuration newConfig)
{
//ignore orientation change
super.onConfigurationChanged(newConfig);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode)
{
case SELECT_PHOTO:
if(resultCode == RESULT_OK)
{
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
if (filePath != null)
{
// get path of image now
File file = new File(filePath);
String path = file.getParent();
Editor edit = settings.edit();
edit.putString("MediaWatcherHandler::CameraDirectory", path);
}
else
Toast.makeText(getApplicationContext(), getString(R.string.Camera_path_select), Toast.LENGTH_LONG).show();
// now finish the activity
finish();
}
break;
}
}
} | lgpl-2.1 |
nybbs2003/jopenmetaverse | src/main/java/com/ngt/jopenmetaverse/shared/sim/events/asm/archive/TerrainLoadedCallbackArgs.java | 1687 | /**
* A library to interact with Virtual Worlds such as OpenSim
* Copyright (C) 2012 Jitendra Chauhan, Email: jitendra.chauhan@gmail.com
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License,
* or (at your option) any later version.
*
* This library 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.ngt.jopenmetaverse.shared.sim.events.asm.archive;
public class TerrainLoadedCallbackArgs {
float[][] terrain;
long bytesRead;
long totalBytes;
public TerrainLoadedCallbackArgs() {
super();
}
public TerrainLoadedCallbackArgs(float[][] terrain, long bytesRead,
long totalBytes) {
super();
this.terrain = terrain;
this.bytesRead = bytesRead;
this.totalBytes = totalBytes;
}
public float[][] getTerrain() {
return terrain;
}
public void setTerrain(float[][] terrain) {
this.terrain = terrain;
}
public long getBytesRead() {
return bytesRead;
}
public void setBytesRead(long bytesRead) {
this.bytesRead = bytesRead;
}
public long getTotalBytes() {
return totalBytes;
}
public void setTotalBytes(long totalBytes) {
this.totalBytes = totalBytes;
}
}
| lgpl-2.1 |
Tictim/TTMPMOD | libs_n/gregtech/common/GT_Network.java | 4432 | package gregtech.common;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteStreams;
import cpw.mods.fml.common.network.FMLEmbeddedChannel;
import cpw.mods.fml.common.network.FMLOutboundHandler;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.network.internal.FMLProxyPacket;
import cpw.mods.fml.relauncher.Side;
import gregtech.api.enums.GT_Values;
import gregtech.api.net.*;
import gregtech.common.blocks.GT_Packet_Ores;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.MessageToMessageCodec;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;
import java.util.EnumMap;
import java.util.List;
@ChannelHandler.Sharable
public class GT_Network
extends MessageToMessageCodec<FMLProxyPacket, GT_Packet>
implements IGT_NetworkHandler {
private final EnumMap<Side, FMLEmbeddedChannel> mChannel;
private final GT_Packet[] mSubChannels;
public GT_Network() {
this.mChannel = NetworkRegistry.INSTANCE.newChannel("GregTech", new ChannelHandler[]{this, new HandlerShared()});
this.mSubChannels = new GT_Packet[]{new GT_Packet_TileEntity(), new GT_Packet_Sound(), new GT_Packet_Block_Event(), new GT_Packet_Ores()};
}
protected void encode(ChannelHandlerContext aContext, GT_Packet aPacket, List<Object> aOutput)
throws Exception {
aOutput.add(new FMLProxyPacket(Unpooled.buffer().writeByte(aPacket.getPacketID()).writeBytes(aPacket.encode()).copy(), (String) aContext.channel().attr(NetworkRegistry.FML_CHANNEL).get()));
}
protected void decode(ChannelHandlerContext aContext, FMLProxyPacket aPacket, List<Object> aOutput)
throws Exception {
ByteArrayDataInput aData = ByteStreams.newDataInput(aPacket.payload().array());
aOutput.add(this.mSubChannels[aData.readByte()].decode(aData));
}
public void sendToPlayer(GT_Packet aPacket, EntityPlayerMP aPlayer) {
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(aPlayer);
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).writeAndFlush(aPacket);
}
public void sendToAllAround(GT_Packet aPacket, NetworkRegistry.TargetPoint aPosition) {
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(aPosition);
((FMLEmbeddedChannel) this.mChannel.get(Side.SERVER)).writeAndFlush(aPacket);
}
public void sendToServer(GT_Packet aPacket) {
((FMLEmbeddedChannel) this.mChannel.get(Side.CLIENT)).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);
((FMLEmbeddedChannel) this.mChannel.get(Side.CLIENT)).writeAndFlush(aPacket);
}
public void sendPacketToAllPlayersInRange(World aWorld, GT_Packet aPacket, int aX, int aZ) {
if (!aWorld.isRemote) {
for (Object tObject : aWorld.playerEntities) {
if (!(tObject instanceof EntityPlayerMP)) {
break;
}
EntityPlayerMP tPlayer = (EntityPlayerMP) tObject;
Chunk tChunk = aWorld.getChunkFromBlockCoords(aX, aZ);
if (tPlayer.getServerForPlayer().getPlayerManager().isPlayerWatchingChunk(tPlayer, tChunk.xPosition, tChunk.zPosition)) {
sendToPlayer(aPacket, tPlayer);
}
}
}
}
@ChannelHandler.Sharable
static final class HandlerShared
extends SimpleChannelInboundHandler<GT_Packet> {
protected void channelRead0(ChannelHandlerContext ctx, GT_Packet aPacket)
throws Exception {
EntityPlayer aPlayer = GT_Values.GT.getThePlayer();
aPacket.process(aPlayer == null ? null : GT_Values.GT.getThePlayer().worldObj);
}
}
}
| lgpl-2.1 |
xwiki/xwiki-platform | xwiki-platform-core/xwiki-platform-filter/xwiki-platform-filter-streams/xwiki-platform-filter-stream-xar/src/main/java/org/xwiki/filter/xar/internal/input/ClassPropertyReader.java | 3635 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.filter.xar.internal.input;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.inject.Singleton;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.xwiki.component.annotation.Component;
import org.xwiki.filter.FilterEventParameters;
import org.xwiki.filter.FilterException;
import org.xwiki.filter.xar.input.XARInputProperties;
import org.xwiki.filter.xar.internal.XARClassPropertyModel;
/**
* @version $Id$
* @since 6.2M1
*/
@Component
@Singleton
public class ClassPropertyReader extends AbstractReader implements XARXMLReader<ClassPropertyReader.WikiClassProperty>
{
public static class WikiClassProperty
{
public String name;
public String type;
public FilterEventParameters parameters = new FilterEventParameters();
public Map<String, String> fields = new LinkedHashMap<>();
public void send(XARInputFilter proxyFilter) throws FilterException
{
proxyFilter.beginWikiClassProperty(this.name, this.type, this.parameters);
for (Map.Entry<String, String> entry : this.fields.entrySet()) {
proxyFilter.onWikiClassPropertyField(entry.getKey(), entry.getValue(), FilterEventParameters.EMPTY);
}
proxyFilter.endWikiClassProperty(this.name, this.type, this.parameters);
}
}
@Override
public WikiClassProperty read(XMLStreamReader xmlReader, XARInputProperties properties)
throws XMLStreamException, FilterException
{
WikiClassProperty wikiClassProperty = new WikiClassProperty();
wikiClassProperty.name = xmlReader.getLocalName();
for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
String elementName = xmlReader.getLocalName();
String value = xmlReader.getElementText();
if (elementName.equals(XARClassPropertyModel.ELEMENT_CLASSTYPE)) {
wikiClassProperty.type = value;
} else {
wikiClassProperty.fields.put(elementName, value);
// If a <name> is defined it has priority over parent element local name
if (elementName.equals(XARClassPropertyModel.ELEMENT_NAME)) {
wikiClassProperty.name = value;
}
}
}
// Skip properties with no type (might be some unknown new class fields and not a property)
if (wikiClassProperty.type == null) {
this.logger.warn("Unknown element [{}] at line [{}]", xmlReader.getLocalName(),
xmlReader.getLocation().getLineNumber());
return null;
}
return wikiClassProperty;
}
}
| lgpl-2.1 |
drhee/toxoMine | intermine/web/main/src/org/intermine/webservice/server/query/CodeService.java | 9256 | package org.intermine.webservice.server.query;
/*
* Copyright (C) 2002-2014 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.Profile;
import org.intermine.api.profile.TagManager;
import org.intermine.api.query.codegen.WebserviceCodeGenInfo;
import org.intermine.api.query.codegen.WebserviceCodeGenerator;
import org.intermine.api.query.codegen.WebserviceJavaCodeGenerator;
import org.intermine.api.query.codegen.WebserviceJavaScriptCodeGenerator;
import org.intermine.api.query.codegen.WebservicePerlCodeGenerator;
import org.intermine.api.query.codegen.WebservicePythonCodeGenerator;
import org.intermine.api.query.codegen.WebserviceRubyCodeGenerator;
import org.intermine.api.tag.TagNames;
import org.intermine.api.tag.TagTypes;
import org.intermine.pathquery.PathQuery;
import org.intermine.web.logic.Constants;
import org.intermine.web.logic.export.ResponseUtil;
import org.intermine.web.util.URLGenerator;
import org.intermine.webservice.server.Format;
import org.intermine.webservice.server.exceptions.BadRequestException;
import org.intermine.webservice.server.output.JSONFormatter;
import org.intermine.webservice.server.query.result.PathQueryBuilder;
import org.json.JSONObject;
/**
* A service for generating code based on a query.
* @author Alex Kalderimis
*
*/
public class CodeService extends AbstractQueryService
{
protected static final Logger LOG = Logger.getLogger(CodeService.class);
private String perlModuleVersion;
private static final String PERL_MODULE_URI = "http://api.metacpan.org/v0/module/Webservice::InterMine";
/**
* Constructor.
* @param im The InterMine application object.
*/
public CodeService(InterMineAPI im) {
super(im);
}
@Override
protected Format getDefaultFormat() {
return Format.TEXT;
}
@Override
protected boolean canServe(Format format) {
switch (format) {
case JSON:
return true;
case TEXT:
return true;
default:
return false;
}
}
@Override
protected String getDefaultFileName() {
return "query";
}
@Override
protected String getExtension() {
String extension = super.getExtension();
String lang = request.getParameter("lang");
if ("perl".equals(lang) || "pl".equals(lang)) {
return ".pl" + extension;
} else if ("java".equals(lang)) {
return ".java" + extension;
} else if ("python".equals(lang) || "py".equals(lang)) {
return ".py" + extension;
} else if ("javascript".equals(lang) || "js".equals(lang)) {
return ".html" + extension;
} else if ("ruby".equals(lang) || "rb".equals(lang)) {
return ".rb" + extension;
} else {
throw new BadRequestException("Unknown code generation language: " + lang);
}
}
private WebserviceCodeGenerator getCodeGenerator(String lang) {
lang = StringUtils.lowerCase(lang);
// Ordered by expected popularity.
if ("js".equals(lang) || "javascript".equals(lang)) {
return new WebserviceJavaScriptCodeGenerator();
} else if ("py".equals(lang) || "python".equals(lang)) {
return new WebservicePythonCodeGenerator();
} else if ("java".equals(lang)) {
return new WebserviceJavaCodeGenerator();
} else if ("pl".equals(lang) || "perl".equals(lang)) {
return new WebservicePerlCodeGenerator();
} else if ("rb".equals(lang) || "ruby".equals(lang)) {
return new WebserviceRubyCodeGenerator();
} else {
throw new BadRequestException("Unknown code generation language: " + lang);
}
}
@Override
protected void execute() {
Profile profile = getPermission().getProfile();
// Ref to OrthologueLinkController and OrthologueLinkManager
String serviceBaseURL = new URLGenerator(request).getPermanentBaseURL();
// set in project properties
String projectTitle = webProperties.getProperty("project.title");
// set in global.web.properties
String perlWSModuleVer = getPerlModuleVersion();
String lang = request.getParameter("lang");
PathQuery pq = getPathQuery();
String name = pq.getTitle() != null ? pq.getTitle() : "query";
String fileName = name.replaceAll("[^a-zA-Z0-9_,.()-]", "_") + getExtension();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
WebserviceCodeGenInfo info = new WebserviceCodeGenInfo(
pq,
serviceBaseURL,
projectTitle,
perlWSModuleVer,
pathQueryIsPublic(pq, im, profile),
profile,
getLineBreak());
info.readWebProperties(webProperties);
WebserviceCodeGenerator codeGen = getCodeGenerator(lang);
String sc = codeGen.generate(info);
if (formatIsJSON()) {
ResponseUtil.setJSONHeader(response, "querycode.json");
Map<String, Object> attributes = new HashMap<String, Object>();
if (formatIsJSONP()) {
String callback = getCallback();
if (callback == null || "".equals(callback)) {
callback = DEFAULT_CALLBACK;
}
attributes.put(JSONFormatter.KEY_CALLBACK, callback);
}
attributes.put(JSONFormatter.KEY_INTRO, "\"code\":");
attributes.put(JSONFormatter.KEY_OUTRO, "");
output.setHeaderAttributes(attributes);
// Oddly, here escape Java is correct, not escapeJavaScript.
// This is due to syntax errors thrown by escaped single quotes.
sc = "\"" + StringEscapeUtils.escapeJava(sc) + "\"";
}
output.addResultItem(Arrays.asList(sc));
}
private String getPerlModuleVersion() {
if (perlModuleVersion == null) {
BufferedReader reader = null;
try {
URL url = new URL(PERL_MODULE_URI);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "InterMine-" + Constants.WEB_SERVICE_VERSION);
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
return null;
}
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuffer body = new StringBuffer();
while ((line = reader.readLine()) != null) {
body.append(line);
}
String json = body.toString();
JSONObject data = new JSONObject(json);
perlModuleVersion = data.getString("version");
} catch (Exception e) {
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore.
}
}
}
}
return perlModuleVersion;
}
/**
* Utility function to determine whether the PathQuery is publicly accessible.
* PathQueries are accessibly publicly as long as they do not reference
* private lists.
* @param pq The query to interrogate
* @param im A reference to the InterMine API
* @param p A user's profile
* @return whether the query is accessible publicly or not
*/
protected static boolean pathQueryIsPublic(PathQuery pq, InterMineAPI im, Profile p) {
Set<String> listNames = pq.getBagNames();
TagManager tm = im.getTagManager();
for (String name: listNames) {
Set<String> tags = tm.getObjectTagNames(name, TagTypes.BAG, p.getUsername());
if (!tags.contains(TagNames.IM_PUBLIC)) {
return false;
}
}
return true;
}
private PathQuery getPathQuery() {
String xml = new QueryRequestParser(im.getQueryStore(), request).getQueryXml();
PathQueryBuilder pqb = getQueryBuilder(xml);
PathQuery query = pqb.getQuery();
return query;
}
}
| lgpl-2.1 |
optivo-org/fingbugs-1.3.9-optivo | src/java/edu/umd/cs/findbugs/classfile/ReflectionDatabaseFactory.java | 4016 | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2006, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.classfile;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* A generic database factory that tries to create the database
* by (in order of preference)
*
* <ol>
* <li>Invoking a static <b>create</b> method </li>
* <li>Invoking a no-arg constructor
* </ol>
*
* @author David Hovemeyer
*/
public class ReflectionDatabaseFactory<E> implements IDatabaseFactory<E> {
private Class<E> databaseClass;
public ReflectionDatabaseFactory(Class<E> databaseClass) {
this.databaseClass = databaseClass;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IDatabaseFactory#createDatabase()
*/
public E createDatabase() throws CheckedAnalysisException {
E database;
database = createUsingStaticCreateMethod();
if (database != null) {
return database;
}
database = createUsingConstructor();
if (database != null) {
return database;
}
throw new CheckedAnalysisException(
"Could not find a way to create database " + databaseClass.getName());
}
/**
* Try to create the database using a static create() method.
*
* @return the database, or null if there is no static create() method
* @throws CheckedAnalysisException
*/
private E createUsingStaticCreateMethod() throws CheckedAnalysisException {
Method createMethod;
try {
createMethod = databaseClass.getMethod("create", new Class[0]);
} catch (NoSuchMethodException e) {
return null;
}
if (!Modifier.isStatic(createMethod.getModifiers())) {
return null;
}
if (createMethod.getReturnType() != databaseClass) {
return null;
}
try {
return databaseClass.cast(createMethod.invoke(null, new Object[0]));
} catch (InvocationTargetException e) {
throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
} catch (IllegalAccessException e) {
throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
}
}
/**
* Try to create the database using a no-arg constructor.
*
* @return the database, or null if there is no no-arg constructor
* @throws CheckedAnalysisException
*/
private E createUsingConstructor() throws CheckedAnalysisException {
Constructor<E> constructor;
try {
constructor = databaseClass.getConstructor(new Class[0]);
} catch (NoSuchMethodException e) {
return null;
}
try {
return constructor.newInstance(new Object[0]);
} catch (InstantiationException e) {
throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
} catch (IllegalAccessException e) {
throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
} catch (InvocationTargetException e) {
throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
}
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.IDatabaseFactory#registerWith(edu.umd.cs.findbugs.classfile.IAnalysisCache)
*/
public void registerWith(IAnalysisCache analysisCache) {
analysisCache.registerDatabaseFactory(databaseClass, this);
}
}
| lgpl-2.1 |
dianhu/Kettle-Research | src/org/pentaho/di/trans/step/RunThread.java | 3557 | /*
* Copyright (c) 2010 Pentaho Corporation. All rights reserved.
* This software was developed by Pentaho Corporation and is provided under the terms
* of the GNU Lesser General Public License, Version 2.1. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho
* Data Integration. The Initial Developer is Pentaho Corporation.
*
* Software distributed under the GNU Lesser Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
package org.pentaho.di.trans.step;
import org.pentaho.di.core.logging.LogChannelInterface;
import org.pentaho.di.i18n.BaseMessages;
public class RunThread implements Runnable {
private static Class<?> PKG = BaseStep.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private StepInterface step;
private StepMetaInterface meta;
private StepDataInterface data;
private LogChannelInterface log;
public RunThread(StepMetaDataCombi combi) {
this.step = combi.step;
this.meta = combi.meta;
this.data = combi.data;
this.log = step.getLogChannel();
}
public void run() {
try
{
step.setRunning(true);
if (log.isDetailed()) log.logDetailed(BaseMessages.getString(PKG, "System.Log.StartingToRun")); //$NON-NLS-1$
while (step.processRow(meta, data) && !step.isStopped());
}
catch(Throwable t)
{
try
{
//check for OOME
if(t instanceof OutOfMemoryError) {
// Handle this different with as less overhead as possible to get an error message in the log.
// Otherwise it crashes likely with another OOME in Me$$ages.getString() and does not log
// nor call the setErrors() and stopAll() below.
log.logError("UnexpectedError: ", t); //$NON-NLS-1$
} else {
log.logError(BaseMessages.getString(PKG, "System.Log.UnexpectedError")+" : ", t); //$NON-NLS-1$ //$NON-NLS-2$
}
// baseStep.logError(Const.getStackTracker(t));
}
catch(OutOfMemoryError e)
{
e.printStackTrace();
}
finally
{
step.setErrors(1);
step.stopAll();
}
}
finally
{
step.dispose(meta, data);
try {
long li = step.getLinesInput();
long lo = step.getLinesOutput();
long lr = step.getLinesRead();
long lw = step.getLinesWritten();
long lu = step.getLinesUpdated();
long lj = step.getLinesRejected();
long e = step.getErrors();
if (li > 0 || lo > 0 || lr > 0 || lw > 0 || lu > 0 || lj > 0 || e > 0)
log.logBasic(BaseMessages.getString(PKG, "BaseStep.Log.SummaryInfo", String.valueOf(li), String.valueOf(lo), String.valueOf(lr), String.valueOf(lw), String.valueOf(lu), String.valueOf(e+lj)));
else
log.logDetailed(BaseMessages.getString(PKG, "BaseStep.Log.SummaryInfo", String.valueOf(li), String.valueOf(lo), String.valueOf(lr), String.valueOf(lw), String.valueOf(lu), String.valueOf(e+lj)));
} catch(Throwable t) {
//
// it's likely an OOME, so we don't want to introduce overhead by using BaseMessages.getString(), see above
//
log.logError("UnexpectedError: " + t.toString()); //$NON-NLS-1$
} finally {
step.markStop();
}
}
}
}
| lgpl-2.1 |
MenoData/Time4J | base/src/main/java/net/time4j/calendar/StdCalendarElement.java | 4758 | /*
* -----------------------------------------------------------------------
* Copyright © 2013-2020 Meno Hochschild, <http://www.menodata.de/>
* -----------------------------------------------------------------------
* This file (StdCalendarElement.java) is part of project Time4J.
*
* Time4J is free software: You can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 2.1 of the License, or
* (at your option) any later version.
*
* Time4J 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Time4J. If not, see <http://www.gnu.org/licenses/>.
* -----------------------------------------------------------------------
*/
package net.time4j.calendar;
import net.time4j.engine.ChronoElement;
import net.time4j.engine.ChronoOperator;
/**
* <p>Extends a chronological element by some standard ways of
* manipulation. </p>
*
* @param <V> generic type of element values
* @param <T> generic type of target entity an operator is applied to
* @author Meno Hochschild
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Erweitert ein chronologisches Element um diverse
* Standardmanipulationen. </p>
*
* @param <V> generic type of element values
* @param <T> generic type of target entity an operator is applied to
* @author Meno Hochschild
* @since 3.5/4.3
*/
public interface StdCalendarElement<V, T>
extends ChronoElement<V> {
//~ Methoden ----------------------------------------------------------
/**
* <p>Sets any local entity to the minimum of this element. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Setzt eine beliebige Entität auf das Elementminimum. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> minimized();
/**
* <p>Sets any local entity to the maximum of this element. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Setzt eine beliebige Entität auf das Elementmaximum. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> maximized();
/**
* <p>Adjusts any local entity such that this element gets the previous value. </p>
*
* <p>The operator throws a {@code ChronoException} if there is no
* base unit available for this element. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Passt eine beliebige Entität so an, daß dieses Element
* den vorherigen Wert bekommt. </p>
*
* <p>Der Operator wirft eine {@code ChronoException}, wenn er auf einen
* Zeitpunkt angewandt wird, dessen Zeitachse keine Basiseinheit zu diesem
* Element kennt. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> decremented();
/**
* <p>Adjusts any local entity such that this element gets the next value. </p>
*
* <p>The operator throws a {@code ChronoException} if there is no
* base unit available for this element. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Passt eine beliebige Entität so an, daß dieses Element
* den nächsten Wert bekommt. </p>
*
* <p>Der Operator wirft eine {@code ChronoException}, wenn er auf einen
* Zeitpunkt angewandt wird, dessen Zeitachse keine Basiseinheit zu diesem
* Element kennt. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> incremented();
/**
* <p>Rounds down an entity by setting all child elements to minimum. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Rundet eine Entität ab, indem alle Kindselemente dieses
* Elements auf ihr Minimum gesetzt werden. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> atFloor();
/**
* <p>Rounds up an entity by setting all child elements to maximum. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
/*[deutsch]
* <p>Rundet eine Entität auf, indem alle Kindselemente dieses
* Elements auf ihr Maximum gesetzt werden. </p>
*
* @return ChronoOperator
* @since 3.5/4.3
*/
ChronoOperator<T> atCeiling();
}
| lgpl-2.1 |
GhostMonk3408/MidgarCrusade | src/main/java/fr/toss/FF7itemsl/iteml74.java | 156 | package fr.toss.FF7itemsl;
public class iteml74 extends FF7itemslbase {
public iteml74(int id) {
super(id);
setUnlocalizedName("iteml74");
}
}
| lgpl-2.1 |
nablex/glue | src/main/java/be/nabu/glue/core/impl/parsers/EmbeddedGlueParser.java | 3337 | package be.nabu.glue.core.impl.parsers;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.text.ParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import be.nabu.glue.api.ExecutionContext;
import be.nabu.glue.api.ExecutorGroup;
import be.nabu.glue.api.Parser;
import be.nabu.glue.api.ScriptRepository;
import be.nabu.libs.evaluator.api.OperationProvider;
import be.nabu.utils.io.IOUtils;
public class EmbeddedGlueParser extends GlueParser {
public EmbeddedGlueParser(ScriptRepository repository, OperationProvider<ExecutionContext> operationProvider) {
super(repository, operationProvider);
}
@Override
public ExecutorGroup parse(Reader reader) throws IOException, ParseException {
// we preprocess the content and basically invert it
// all embedded glue become actual glue commands
// all the text around it becomes a string to be outputted
String content = IOUtils.toString(IOUtils.wrap(reader)).replace("\r", "");
Pattern pattern = Pattern.compile("(?s)\\$\\{\\{.*?\\}\\}");
Matcher matcher = pattern.matcher(content);
StringBuilder result = new StringBuilder();
int lastIndex = -1;
// code depth is at which depth we are generating glue code (and embedded strings)
int codeDepth = 0;
while(matcher.find()) {
// if there is text between the last match and this one, output it as string
if (matcher.start() > lastIndex + 1) {
// no code yet, add an initial echo()
// if there is data after this block, add an echo
result.append("\necho(template(\"");
result.append(encodeString(content.substring(lastIndex + 1, matcher.start()), 1));
// end whatever echo was echoing this
result.append("\"))\n");
}
String code = matcher.group().replaceAll("^[\\s]+\n", "");
// skip start and end ${{}}
code = code.substring(3, code.length() - 2);
if (!code.trim().isEmpty()) {
// can be reset per block and within the block it can become less (never more)
codeDepth = getDepth(code);
for (String line : code.split("\n")) {
if (line.trim().isEmpty()) {
continue;
}
int startIndex = 0;
for (int i = 0; i <= Math.min(codeDepth, line.length()); i++) {
if (line.charAt(i) == '\t' || line.charAt(i) == ' ') {
startIndex++;
}
else {
codeDepth = startIndex;
break;
}
}
result.append(line.substring(codeDepth) + "\n");
}
}
lastIndex = matcher.end();
}
if (lastIndex + 1 < content.length()) {
String rest = content.substring(lastIndex + 1);
if (!rest.trim().isEmpty()) {
result.append("\necho(template(\"");
result.append(encodeString(rest, 1));
// end whatever echo was echoing this
result.append("\"))\n");
}
}
return super.parse(new StringReader(result.toString()));
}
private Object encodeString(String substring, int codeDepth) {
String buffer = "";
for (int i = 0; i < codeDepth; i++) {
buffer += "\t";
}
// the second replace makes sure if you had an escape ", it is properly done
return substring.replace("\"", "\\\"").replace("\\\\\"", "\" + \"\\\\\" + \"\\\"\" + \"").replace("#", "\\#").replace("\n", "\n" + buffer); // .
}
@Override
public Parser getSubstitutionParser() {
return new GlueParser(getRepository(), getOperationProvider());
}
}
| lgpl-2.1 |
opensagres/xdocreport.eclipse | commons/org.eclipse.nebula.widgets.pagination.example.springdata/src/org/eclipse/nebula/widgets/pagination/example/springdata/table/renderers/ComboPageableTableExample.java | 3348 | /*******************************************************************************
* Copyright (C) 2011 Angelo Zerr <angelo.zerr@gmail.com>, Pascal Leclercq <pascal.leclercq@gmail.com>
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Angelo ZERR - initial API and implementation
* Pascal Leclercq - initial API and implementation
*******************************************************************************/
package org.eclipse.nebula.widgets.pagination.example.springdata.table.renderers;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.pagination.renderers.navigation.NavigationPageComboRendererFactory;
import org.eclipse.nebula.widgets.pagination.springdata.SpringDataPageContentProvider;
import org.eclipse.nebula.widgets.pagination.springdata.SpringDataPageLoaderList;
import org.eclipse.nebula.widgets.pagination.table.PageableTable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
/**
* This sample display a list of String in a SWT Table with navigation page
* displayed with Combo (by using {@link NavigationPageComboRendererFactory}) on
* the top of the SWT Table.
*
*/
public class ComboPageableTableExample {
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
GridLayout layout = new GridLayout(1, false);
shell.setLayout(layout);
final List<String> items = createList();
// 1) Create pageable table with 10 items per page
// This SWT Component create internally a SWT Table+JFace TreeViewer
int pageSize = 10;
PageableTable pageableTable = new PageableTable(shell, SWT.BORDER,
SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL, pageSize,
SpringDataPageContentProvider.getInstance(),
NavigationPageComboRendererFactory.getFactory(), null);
pageableTable.setLayoutData(new GridData(GridData.FILL_BOTH));
// 2) Initialize the table viewer
TableViewer viewer = pageableTable.getViewer();
viewer.setContentProvider(ArrayContentProvider.getInstance());
viewer.setLabelProvider(new LabelProvider());
// 3) Set the page loader used to load a page (sublist of String)
// according the page index selected, the page size etc.
pageableTable.setPageLoader(new SpringDataPageLoaderList(items));
// 4) Set current page to 0 to display the first page
pageableTable.setCurrentPage(0);
shell.setSize(350, 250);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
/**
* Create a static list.
*
* @return
*/
private static List<String> createList() {
List<String> names = new ArrayList<String>();
for (int i = 1; i < 2012; i++) {
names.add("Name " + i);
}
return names;
}
}
| lgpl-2.1 |
MartijnDwars/spt | org.strategoxt.imp.testing/editor/java/org/strategoxt/imp/testing/strategies/ListenerWrapper.java | 5239 | /**
*
*/
package org.strategoxt.imp.testing.strategies;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.spi.RegistryContributor;
import org.eclipse.ui.PlatformUI;
import org.strategoxt.imp.testing.preferences.PreferenceConstants;
import org.strategoxt.imp.testing.preferences.PreferenceInitializer;
/**
*
* Provides wrapper methods for the client-end of the ITestListener extension point. The purpose of this class is to
* abstract the implementation details of discovering the client (and using reflexive calls) from the Strategies.
*
* This class is a singleton
*
* @author vladvergu
*
*/
public final class ListenerWrapper implements ITestListener {
private static ITestListener instance;
public static ITestListener instance() throws CoreException {
if (instance == null)
instance = new ListenerWrapper();
return instance;
}
private ListenerWrapper() {
}
private Object getWrapped() throws CoreException {
IConfigurationElement[] config = Platform.getExtensionRegistry().getConfigurationElementsFor(
ITestListener.EXTENSION_ID);
Object candidateListener = null;
String preferredView = PlatformUI.getPreferenceStore().getString(PreferenceConstants.P_LISTENER_ID);
if (preferredView.equals(""))
preferredView = PreferenceInitializer.DEFAULT_LISTENER_ID;
for (IConfigurationElement e : config) {
if (((RegistryContributor) e.getContributor()).getActualName().equals(preferredView)) {
candidateListener = e.createExecutableExtension("class");
break;
}
}
return candidateListener;
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#reset()
*/
public void reset() throws SecurityException, NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException, CoreException {
Object wrapped = getWrapped();
// Using reflection, because if I use a cast, I get a ClassCastException
// cannot cast type <x> to <x>. Probably because of some different classloader issue.
Method m = wrapped.getClass().getMethod("reset", new Class[] {});
if (!Modifier.isAbstract(m.getModifiers())) {
m.invoke(wrapped);
}
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#addTestcase(java.lang.String, java.lang.String, int)
*/
public void addTestcase(String testsuite, String description, int offset) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException, CoreException {
Object wrapped = getWrapped();
Method m = wrapped.getClass().getMethod("addTestcase", new Class[] { String.class, String.class, int.class });
if (!Modifier.isAbstract(m.getModifiers())) {
m.invoke(wrapped, testsuite, description, offset);
}
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#addTestsuite(java.lang.String, java.lang.String)
*/
public void addTestsuite(String name, String filename) throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, SecurityException, NoSuchMethodException, CoreException {
Object wrapped = getWrapped();
Method m = wrapped.getClass().getMethod("addTestsuite", new Class[] { String.class, String.class });
if (!Modifier.isAbstract(m.getModifiers())) {
m.invoke(wrapped, name, filename);
}
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#startTestcase(java.lang.String, java.lang.String)
*/
public void startTestcase(String testsuite, String description) throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException, InvocationTargetException, CoreException {
Object wrapped = getWrapped();
Method m = wrapped.getClass().getMethod("startTestcase", new Class[] { String.class, String.class });
if (!Modifier.isAbstract(m.getModifiers())) {
m.invoke(wrapped, testsuite, description);
}
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#finishTestcase(java.lang.String, java.lang.String,
* boolean)
*/
public void finishTestcase(String testsuite, String description, boolean succeeded)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException,
NoSuchMethodException, CoreException {
Object wrapped = getWrapped();
Method m = wrapped.getClass().getMethod("finishTestcase",
new Class[] { String.class, String.class, boolean.class });
if (!Modifier.isAbstract(m.getModifiers())) {
m.invoke(wrapped, testsuite, description, succeeded);
}
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#disableRefresh()
*/
public void disableRefresh() {
// the test provider doesn't use this hack
}
/*
* (non-Javadoc)
*
* @see org.strategoxt.imp.testing.listener.ITestListener#enableRefresh()
*/
public void enableRefresh() {
// the test provider doesn't use this hack
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | designer/report-designer/src/main/java/org/pentaho/reporting/designer/core/editor/drilldown/DrillDownParameterRefreshListener.java | 1136 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.reporting.designer.core.editor.drilldown;
import java.util.EventListener;
/**
* Todo: Document me!
*
* @author Thomas Morgner.
*/
public interface DrillDownParameterRefreshListener extends EventListener {
public void requestParameterRefresh( final DrillDownParameterRefreshEvent model );
}
| lgpl-2.1 |
shabanovd/exist | extensions/modules/src/org/exist/xquery/modules/cache/GetFunction.java | 3134 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-09 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
package org.exist.xquery.modules.cache;
import org.apache.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.Cardinality;
import org.exist.xquery.FunctionSignature;
import org.exist.xquery.XPathException;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.FunctionParameterSequenceType;
import org.exist.xquery.value.Item;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceType;
import org.exist.xquery.value.Type;
import org.xml.sax.SAXException;
/**
* Global cache module. Get function
*
* @author Evgeny Gazdovsky <gazdovsky@gmail.com>
* @version 1.0
*/
public class GetFunction extends CacheBasicFunction {
private final static Logger logger = Logger.getLogger(GetFunction.class);
public final static FunctionSignature signatures[] = {
new FunctionSignature(
new QName("get", CacheModule.NAMESPACE_URI, CacheModule.PREFIX),
"Get data from identified global cache by key",
new SequenceType[] {
new FunctionParameterSequenceType("cache-identity", Type.ITEM, Cardinality.ONE, "Either the Java cache object or the name of the cache"),
new FunctionParameterSequenceType("key", Type.ANY_TYPE, Cardinality.ONE_OR_MORE, "The key to the object within the cache")
},
new FunctionParameterSequenceType("value", Type.ANY_TYPE, Cardinality.ZERO_OR_MORE, "the value that is associated with the key")
)
};
public GetFunction(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
Item item = args[0].itemAt(0);
try {
String key = serialize(args[1]);
if (item.getType()==Type.STRING){
if( logger.isTraceEnabled() ) {
logger.trace("getting cache value [" + item.getStringValue() + ", " + key +"]");
}
return Cache.get(item.getStringValue(), key);
} else {
if( logger.isTraceEnabled() ) {
logger.trace("getting cache value [" + item.toJavaObject(Cache.class).toString() + ", " + key +"]");
}
return ((Cache)item.toJavaObject(Cache.class)).get(key);
}
} catch (SAXException e) {
logger.error("Error getting cache value", e);
}
return Sequence.EMPTY_SEQUENCE;
}
} | lgpl-2.1 |
fioan89/coldswap | swapcore/src/main/java/org/coldswap/util/ByteCodeClassWriter.java | 3447 | package org.coldswap.util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* (C) Copyright 2013 Faur Ioan-Aurel.
* <p/>
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
* <p/>
* This library 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
* Lesser General Public License for more details.
* <p/>
* Contributors:
* faur
* <p/>
* Created at:
* 5:56 PM 4/19/13
*/
/**
* Writes an array of bytes to a file.
*/
public class ByteCodeClassWriter {
private static File outDir = null;
/**
* Writes the given byte array to a file using the last class path that was
* set with {@link ByteCodeClassWriter#setClassPath(String)}.
*
* @param className the name of the class.
* @param bytes array of bytes representing the class body.
* @throws IOException if the file could not be written.
* @throws ClassPathNullPointerException if the class path was not settled before.
*/
public static void writeClass(String className, byte[] bytes) throws IOException, ClassPathNullPointerException {
if (outDir == null) {
throw new ClassPathNullPointerException("Class Path is null! You must specify where to write class " +
className + "!");
}
// create the file and schedule for removing when jvm stops
File classToRemove = new File(outDir, className + ".class");
//classToRemove.deleteOnExit();
DataOutputStream dout = new DataOutputStream(new FileOutputStream(classToRemove));
dout.write(bytes, 0, bytes.length);
dout.flush();
dout.close();
}
/**
* Writes the given byte array to a file using the last class path that was
* set with {@link ByteCodeClassWriter#setClassPath(String)}.
*
* @param className the name of the class.
* @param bytes array of bytes representing the class body.
* @param removeClass should remove or not, the file after app is down.
* @throws IOException if the file could not be written.
* @throws ClassPathNullPointerException if the class path was not settled before.
*/
public static void writeClass(String className, byte[] bytes, boolean removeClass) throws IOException, ClassPathNullPointerException {
if (outDir == null) {
throw new ClassPathNullPointerException("Class Path is null! You must specify where to write class " +
className + "!");
}
// create the file and schedule for removing when jvm stops
File classToRemove = new File(outDir, className + ".class");
if (removeClass) {
classToRemove.deleteOnExit();
}
DataOutputStream dout = new DataOutputStream(new FileOutputStream(classToRemove));
dout.write(bytes, 0, bytes.length);
dout.flush();
dout.close();
}
public static void setClassPath(String location) {
outDir = new File(location);
outDir.mkdir();
}
}
| lgpl-2.1 |
vonpower/VonRep | CES2/FFSystem/ynugis/geo/Merge.java | 5369 | /*
* @author 冯涛,创建日期:2003-10-16
* blog--http://apower.blogone.net
* QQ:17463776
* MSN:apower511@msn.com
* E-Mail:VonPower@Gmail.com
*/
package ynugis.geo;
import java.io.IOException;
import com.esri.arcgis.geoanalyst.IRasterAnalysisEnvironment;
import com.esri.arcgis.geoanalyst.IRasterAnalysisEnvironmentProxy;
import com.esri.arcgis.geodatabase.IGeoDataset;
import com.esri.arcgis.interop.AutomationException;
import com.esri.arcgis.spatialanalyst.IMapAlgebraOp;
import com.esri.arcgis.spatialanalyst.RasterMapAlgebraOp;
public class Merge {
// private variable definition
private double cellSize = 0;
private String outputPath = "";
private IGeoDataset[] dataArray;
private IMapAlgebraOp mapAlgebraOp;
private IRasterAnalysisEnvironment rasterAnalysisEnvironment;
/**
* setOutputPath(GV.getDefaultTempFileDirectoryPath()); setCellSize(50);
*
* @throws Exception
* @throws IOException
*/
public Merge(IRasterAnalysisEnvironment env) throws Exception, IOException {
super();
initial();
Utility.RasterAnalysisEnvCopy(env, rasterAnalysisEnvironment);
}
/**
*
*
* @param outputPath
* @param cellSize
* @throws Exception
* @throws IOException
*/
/*
* public Merge(String outputPath,double cellSize) throws Exception,
* IOException { super(); initial(); setOutputPath(outputPath);
* setCellSize(cellSize);
* }
*
*
*/
/**
*
*
* @throws Exception
* @throws IOException
*/
private void initial() throws Exception, IOException {
mapAlgebraOp = new RasterMapAlgebraOp();
rasterAnalysisEnvironment = new IRasterAnalysisEnvironmentProxy(
mapAlgebraOp);
}
/**
* 指定用于合并的数据层
*
* @param data
* @throws Exception
*/
public void specifyDataLayers(IGeoDataset[] data) throws Exception {
dataArray = data;
}
/**
* 合并(specifyDataLayers()方法)所指定的数据层
*
* @return
* @throws Exception
*/
public IGeoDataset mergeDataLayers() throws Exception {
double[] foo = new double[dataArray.length];
for (int i = 0; i < foo.length; i++) {
foo[i] = 1;
}
return mergeDataLayers(foo);
}
public IGeoDataset mergeUseBigValue() throws AutomationException, IOException {
IGeoDataset result;
if (dataArray.length == 0)
return null;
if (dataArray.length == 1)
{
mapAlgebraOp.bindRaster(dataArray[0],"R1");
return mapAlgebraOp.execute("CON(isNull([R1]) ,0 ,[R1])");
}
// 构造地图代数运算表达式
result=dataArray[0];
for (int i = 1; i < dataArray.length; i++) {
mapAlgebraOp.bindRaster(result,"R1");
mapAlgebraOp.bindRaster(dataArray[i],"R2");
// 将[Rt]定中的nodata格指定为“0”;
result=mapAlgebraOp.execute("CON(isNull([R1]) ,0 ,[R1])");
dataArray[i]=mapAlgebraOp.execute("CON(isNull([R2]) ,0 ,[R2])");
result=mapAlgebraOp.execute("CON([R2] > [R1] ,[R2] ,[R1])");
}
mapAlgebraOp.unbindRaster("R1");
mapAlgebraOp.unbindRaster("R2");
return result;
}
/**
* 按照所指定的权重(weights)合并所指定的数据层
*
* @param weights
* weights和当前所指定的数据层一一对应,表示每层的权重
* @return
* @throws Exception
*/
public IGeoDataset mergeDataLayers(double[] weights) throws Exception {
IGeoDataset result;
if (dataArray.length == 0)
return null;
if (dataArray.length == 1)
return dataArray[0];
if (dataArray.length != weights.length)
throw new Exception("叠加数据个数和指定的权重个数不匹配!");
String[] alias = new String[dataArray.length];
// 构造地图代数运算表达式
String commandStr = "";
for (int i = 0; i < dataArray.length; i++) {
if (i != 0)
commandStr += " + ";
alias[i] = "R" + i;
mapAlgebraOp.bindRaster(dataArray[i], alias[i]);
// 将[Rt]定中的nodata格指定为“0”;
dataArray[i] = mapAlgebraOp.execute("CON(isNull([" + alias[i]
+ "]) ,0 ,[" + alias[i] + "])");
mapAlgebraOp.bindRaster(dataArray[i], alias[i]);
commandStr += "[" + "R" + i + "]" + " * " + weights[i];
}
result = mapAlgebraOp.execute(commandStr);
// 把单元格分值超过100的进行处理
mapAlgebraOp.bindRaster(result, "R0");
result = mapAlgebraOp
.execute("CON([R0] > 100 ,98 + [R0] / 1000 ,[R0])");
// 解除本次使用的GeoDataset绑定;
for (int i = 0; i < alias.length; i++) {
mapAlgebraOp.unbindRaster(alias[i]);
}
return result;
}
/*
* public double getCellSize() { return cellSize; }
*
* public void setCellSize(double cellSize) throws Exception, IOException {
* this.cellSize = cellSize;
* rasterAnalysisEnvironment.setCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue,
* new Double(cellSize)); }
*
* public String getOutputPath() { return outputPath; }
*
* public void setOutputPath(String output) throws Exception, IOException {
* this.outputPath = output; IWorkspaceFactory rasterWSF = new
* RasterWorkspaceFactory(); IWorkspace workspace =
* rasterWSF.openFromFile(getOutputPath(), 0);
* rasterAnalysisEnvironment.setOutWorkspaceByRef(workspace);
* }
*
*/
}
| lgpl-2.1 |
EgorZhuk/pentaho-reporting | engine/extensions/src/main/java/org/pentaho/reporting/engine/classic/extensions/modules/connections/PooledDatasourceService.java | 4614 | /*!
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2005-2015 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.reporting.engine.classic.extensions.modules.connections;
import javax.sql.DataSource;
import org.pentaho.database.model.IDatabaseConnection;
import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
import org.pentaho.reporting.engine.classic.core.modules.misc.connections.DataSourceMgmtService;
import org.pentaho.reporting.engine.classic.core.modules.misc.connections.DataSourceService;
import org.pentaho.reporting.engine.classic.core.modules.misc.connections.DatasourceMgmtServiceException;
import org.pentaho.reporting.engine.classic.core.modules.misc.connections.DatasourceServiceException;
import org.pentaho.reporting.libraries.base.boot.ObjectFactory;
import org.pentaho.reporting.libraries.base.boot.SingletonHint;
@SingletonHint
public class PooledDatasourceService implements DataSourceService {
private DataSourceCache cacheManager;
public PooledDatasourceService() {
final ObjectFactory objectFactory = ClassicEngineBoot.getInstance().getObjectFactory();
final DataSourceCacheManager manager = objectFactory.get( DataSourceCacheManager.class );
cacheManager = manager.getDataSourceCache();
}
protected DataSource retrieve( final String datasource ) throws DatasourceServiceException {
final DataSourceMgmtService datasourceMgmtSvc =
ClassicEngineBoot.getInstance().getObjectFactory().get( DataSourceMgmtService.class );
try {
final IDatabaseConnection databaseConnection = datasourceMgmtSvc.getDatasourceByName( datasource );
return PooledDatasourceHelper.setupPooledDataSource( databaseConnection );
} catch ( DatasourceMgmtServiceException daoe ) {
return queryFallback( datasource );
}
}
protected DataSource queryFallback( final String dataSource ) {
throw new DatasourceServiceException( Messages.getInstance().getString(
"PooledDataSourceService.ERROR_0002_UNABLE_TO_GET_DATASOURCE", dataSource ) ); //$NON-NLS-1$
}
/**
* This method clears the JNDI DS cache. The need exists because after a JNDI connection edit the old DS must be
* removed from the cache.
*/
public void clearCache() {
cacheManager.clear();
}
/**
* This method clears the JNDI DS cache. The need exists because after a JNDI connection edit the old DS must be
* removed from the cache.
*/
public void clearDataSource( final String dsName ) {
cacheManager.remove( dsName );
}
/**
* Since JNDI is supported different ways in different app servers, it's nearly impossible to have a ubiquitous way to
* look up a datasource. This method is intended to hide all the lookups that may be required to find a jndi name.
*
* @param dsName
* The Datasource name
* @return DataSource if there is one bound in JNDI
*/
public DataSource getDataSource( final String dsName ) throws DatasourceServiceException {
if ( cacheManager != null ) {
final DataSource foundDs = cacheManager.get( dsName );
if ( foundDs != null ) {
return foundDs;
} else {
return retrieve( dsName );
}
}
return null;
}
/**
* Since JNDI is supported different ways in different app servers, it's nearly impossible to have a ubiquitous way to
* look up a datasource. This method is intended to hide all the lookups that may be required to find a jndi name, and
* return the actual bound name.
*
* @param dsName
* The Datasource name (like SampleData)
* @return The bound DS name if it is bound in JNDI (like "jdbc/SampleData")
* @throws org.pentaho.reporting.engine.classic.core.modules.misc.connections.DatasourceServiceException
*/
public String getDSBoundName( final String dsName ) throws DatasourceServiceException {
return dsName;
}
}
| lgpl-2.1 |
fastcat-co/analytics | analytics-server/src/test/java/org/fastcatsearch/analytics/analysis/ScheduledTasksTest.java | 2465 | package org.fastcatsearch.analytics.analysis;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import org.fastcatsearch.analytics.analysis.log.SearchLog;
import org.fastcatsearch.analytics.analysis.schedule.EveryMinuteSchedule;
import org.fastcatsearch.analytics.analysis.schedule.FixedSchedule;
import org.fastcatsearch.analytics.analysis.schedule.Schedule;
import org.fastcatsearch.analytics.analysis.schedule.ScheduledTaskRunner;
import org.fastcatsearch.analytics.analysis.task.AnalyticsTask;
import org.fastcatsearch.analytics.env.Environment;
import org.fastcatsearch.analytics.job.TestJobExecutor;
import org.junit.Test;
public class ScheduledTasksTest {
@Test
public void test() throws IOException, InterruptedException {
ScheduledTaskRunner taskRunner = new ScheduledTaskRunner("test", new TestJobExecutor(), new Environment("."));
File f = new File("/Users/swsong/tmp/test.log");
String siteId = "a";
List<String> categoryIdList = null;
Calendar calendar = StatisticsUtils.getNowCalendar();
Schedule schedule = new EveryMinuteSchedule(1);
AnalyticsTask<SearchLog> task = new TestAnalyticsTask("1111", siteId, categoryIdList, schedule, 1);
taskRunner.addTask(task);
Schedule schedule2 = new EveryMinuteSchedule(1);
AnalyticsTask<SearchLog> task2 = new TestAnalyticsTask("2222", siteId, categoryIdList, schedule2, 2);
taskRunner.addTask(task2);
taskRunner.start();
System.out.println("Started " + taskRunner);
taskRunner.join();
}
@Test
public void testWithCalculator() throws IOException, InterruptedException {
ScheduledTaskRunner taskRunner = new ScheduledTaskRunner("test", new TestJobExecutor(), new Environment("."));
File f = new File("/Users/swsong/tmp/test.log");
Schedule schedule = new FixedSchedule(StatisticsUtils.getNowCalendar(), 2, 1);
AnalyticsTask<SearchLog> task = null;
String categoryId = "cat1";
taskRunner.addTask(task);
taskRunner.start();
System.out.println("Started " + taskRunner);
taskRunner.join();
}
class TestAnalyticsTask extends AnalyticsTask<SearchLog> {
private static final long serialVersionUID = 5431881216955668282L;
public TestAnalyticsTask(String name, String siteId, List<String> categoryIdList, Schedule schedule, int priority) {
super("TEST", name, siteId, categoryIdList, schedule, priority);
}
@Override
protected void prepare(Calendar calendar) {
}
}
}
| lgpl-2.1 |
gavin-hu/focusns | focusns-web/src/main/java/org/focusns/web/page/interceptor/PageRenderParameterResolver.java | 3945 | package org.focusns.web.page.interceptor;
/*
* #%L
* FocusSNS Web
* %%
* Copyright (C) 2011 - 2013 FocusSNS
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.focusns.common.web.WebUtils;
import org.focusns.common.web.page.engine.PageRenderInterceptor;
import org.focusns.model.core.Project;
import org.focusns.model.core.ProjectCategory;
import org.focusns.model.core.ProjectFeature;
import org.focusns.service.core.ProjectCategoryService;
import org.focusns.service.core.ProjectFeatureService;
import org.focusns.service.core.ProjectService;
import org.focusns.web.Keys;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UrlPathHelper;
public class PageRenderParameterResolver implements PageRenderInterceptor, ApplicationContextAware {
private static final UrlPathHelper urlPathHelper = new UrlPathHelper();
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public boolean beforeRender(HttpServletRequest request, HttpServletResponse response) {
//
Map<String, String> parameterMap = WebUtils.getMatrixParameters(request);
String lookupPath = urlPathHelper.getLookupPathForRequest(request);
//
String projectCode = parameterMap.get(Keys.PARAMETER_PROJECT_CODE);
if (StringUtils.hasText(projectCode)) {
//
ProjectService projectService = applicationContext.getBean(ProjectService.class);
ProjectCategoryService projectCategoryService = applicationContext.getBean(ProjectCategoryService.class);
ProjectFeatureService projectFeatureService = applicationContext.getBean(ProjectFeatureService.class);
//
Project project = projectService.getProject(projectCode);
ProjectCategory projectCategory = projectCategoryService.getCategory(project.getCategoryId());
//
request.setAttribute(Keys.REQUEST_PROJECT, project);
request.setAttribute(Keys.REQUEST_PROJECT_CATEGORY, projectCategory);
//
List<ProjectFeature> projectFeatures = projectFeatureService.getProjectFeatures(project.getId());
for (ProjectFeature projectFeature : projectFeatures) {
if (lookupPath.contains(projectFeature.getCode())) {
request.setAttribute(Keys.REQUEST_PROJECT_FEATURE, projectFeature);
break;
}
}
}
//
Object projectUser = request.getSession().getAttribute(Keys.SESSION_PROJECT_USER);
if (projectUser != null) {
request.setAttribute(Keys.REQUEST_PROJECT_USER, projectUser);
}
//
return true;
}
@Override
public void afterRender(HttpServletRequest request, HttpServletResponse response) {
}
}
| lgpl-2.1 |
ManolitoOctaviano/Language-Identification | src/java/de/danielnaber/languagetool/tagging/disambiguation/rules/eo/EsperantoRuleDisambiguator.java | 1232 | /* LanguageTool, a natural language style checker
* Copyright (C) 2007 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package de.danielnaber.languagetool.tagging.disambiguation.rules.eo;
import de.danielnaber.languagetool.Language;
import de.danielnaber.languagetool.tagging.disambiguation.rules.AbstractRuleDisambiguator;
public class EsperantoRuleDisambiguator extends AbstractRuleDisambiguator {
@Override
protected Language getLanguage() {
return Language.ESPERANTO;
}
}
| lgpl-2.1 |
pengqiuyuan/jcaptcha | src/main/java/com/octo/captcha/engine/sound/SoundCaptchaEngine.java | 3636 | /*
* JCaptcha, the open source java framework for captcha definition and integration
* Copyright (c) 2007 jcaptcha.net. All Rights Reserved.
* See the LICENSE.txt file distributed with this package.
*/
/*
* jcaptcha, the open source java framework for captcha definition and integration
* copyright (c) 2007 jcaptcha.net. All Rights Reserved.
* See the LICENSE.txt file distributed with this package.
*/
/*
* jcaptcha, the open source java framework for captcha definition and integration
* copyright (c) 2007 jcaptcha.net. All Rights Reserved.
* See the LICENSE.txt file distributed with this package.
*/
package com.octo.captcha.engine.sound;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import com.octo.captcha.Captcha;
import com.octo.captcha.CaptchaFactory;
import com.octo.captcha.engine.CaptchaEngineException;
import com.octo.captcha.sound.SoundCaptcha;
import com.octo.captcha.sound.SoundCaptchaFactory;
/**
* <p>Description: abstract base class for SoundCaptcha engines</p>.
*
* @author Benoit Doumas
* @version 1.0
*/
public abstract class SoundCaptchaEngine
implements com.octo.captcha.engine.CaptchaEngine {
protected List factories = new ArrayList();
protected Random myRandom = new SecureRandom();
/**
* This return a new captcha. It may be used directly.
*
* @return a new Captcha
*/
public final Captcha getNextCaptcha() {
return getNextSoundCaptcha();
}
/**
* This return a new captcha. It may be used directly.
*
* @param locale the desired locale
*
* @return a new Captcha
*/
public final Captcha getNextCaptcha(Locale locale) {
return getNextSoundCaptcha(locale);
}
/**
* @return captcha factories used by this engine
*/
public CaptchaFactory[] getFactories() {
return (CaptchaFactory[]) this.factories.toArray(new CaptchaFactory[factories.size()]);
}
/**
* @param factories new captcha factories for this engine
*/
public void setFactories(CaptchaFactory[] factories) throws CaptchaEngineException {
checkNotNullOrEmpty(factories);
ArrayList tempFactories = new ArrayList();
for (int i = 0; i < factories.length; i++) {
if (!SoundCaptchaFactory.class.isAssignableFrom(factories[i].getClass())) {
throw new CaptchaEngineException("This factory is not an sound captcha factory " + factories[i].getClass());
}
tempFactories.add(factories[i]);
}
this.factories = tempFactories;
}
protected void checkNotNullOrEmpty(CaptchaFactory[] factories) {
if (factories == null || factories.length == 0) {
throw new CaptchaEngineException("impossible to set null or empty factories");
}
}
/**
* This method build a SoundCaptchaFactory.
*
* @return a CaptchaFactory
*/
public SoundCaptchaFactory getSoundCaptchaFactory() {
return (SoundCaptchaFactory) factories.get(myRandom
.nextInt(factories.size()));
}
/**
* This method build a SoundCaptchaFactory.
*
* @return a SoundCaptcha
*/
public SoundCaptcha getNextSoundCaptcha() {
return getSoundCaptchaFactory().getSoundCaptcha();
}
/**
* This method build a SoundCaptchaFactory.
*
* @return a SoundCaptcha
*/
public SoundCaptcha getNextSoundCaptcha(Locale locale) {
return getSoundCaptchaFactory().getSoundCaptcha(locale);
}
}
| lgpl-2.1 |
phoenixctms/ctsms | core/src/test/java/org/phoenixctms/ctsms/service/trial/test/TrialService_getTimelineEventIntervalTest.java | 1409 | // This file is part of the Phoenix CTMS project (www.phoenixctms.org),
// distributed under LGPL v2.1. Copyright (C) 2011 - 2017.
//
package org.phoenixctms.ctsms.service.trial.test;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* <p>
* Test case for method <code>getTimelineEventInterval</code> of service <code>TrialService</code>.
* </p>
*
* @see org.phoenixctms.ctsms.service.trial.TrialService#getTimelineEventInterval(org.phoenixctms.ctsms.vo.AuthenticationVO, java.lang.Long, java.lang.Long, java.lang.Long, java.lang.Long, java.lang.Boolean, java.util.Date, java.util.Date)
*/
@Test(groups={"service","TrialService"})
public class TrialService_getTimelineEventIntervalTest extends TrialServiceBaseTest {
/**
* Test succes path for service method <code>getTimelineEventInterval</code>
*
* Tests expected behaviour of service method.
*/
@Test
public void testSuccessPath() {
Assert.fail( "Test 'TrialService_getTimelineEventIntervalTest.testSuccessPath()}' not implemented." );
}
/*
* Add test methods for each test case of the 'TrialService.org.andromda.cartridges.spring.metafacades.SpringServiceOperationLogicImpl[org.phoenixctms.ctsms.service.trial.TrialService.getTimelineEventInterval]()' service method.
*/
/**
* Test special case XYZ for service method <code></code>
*/
/*
@Test
public void testCaseXYZ() {
}
*/
} | lgpl-2.1 |
geotools/geotools | modules/ogc/net.opengis.wmts/src/net/opengis/gml311/impl/DirectionPropertyTypeImpl.java | 32781 | /**
*/
package net.opengis.gml311.impl;
import net.opengis.gml311.CodeType;
import net.opengis.gml311.CompassPointEnumeration;
import net.opengis.gml311.DirectionPropertyType;
import net.opengis.gml311.DirectionVectorType;
import net.opengis.gml311.Gml311Package;
import net.opengis.gml311.StringOrRefType;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.MinimalEObjectImpl;
import org.w3.xlink.ActuateType;
import org.w3.xlink.ShowType;
import org.w3.xlink.TypeType;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Direction Property Type</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getDirectionVector <em>Direction Vector</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getCompassPoint <em>Compass Point</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getDirectionKeyword <em>Direction Keyword</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getDirectionString <em>Direction String</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getActuate <em>Actuate</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getArcrole <em>Arcrole</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getHref <em>Href</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getRemoteSchema <em>Remote Schema</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getRole <em>Role</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getShow <em>Show</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getTitle <em>Title</em>}</li>
* <li>{@link net.opengis.gml311.impl.DirectionPropertyTypeImpl#getType <em>Type</em>}</li>
* </ul>
*
* @generated
*/
public class DirectionPropertyTypeImpl extends MinimalEObjectImpl.Container implements DirectionPropertyType {
/**
* The cached value of the '{@link #getDirectionVector() <em>Direction Vector</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDirectionVector()
* @generated
* @ordered
*/
protected DirectionVectorType directionVector;
/**
* The default value of the '{@link #getCompassPoint() <em>Compass Point</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompassPoint()
* @generated
* @ordered
*/
protected static final CompassPointEnumeration COMPASS_POINT_EDEFAULT = CompassPointEnumeration.N;
/**
* The cached value of the '{@link #getCompassPoint() <em>Compass Point</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCompassPoint()
* @generated
* @ordered
*/
protected CompassPointEnumeration compassPoint = COMPASS_POINT_EDEFAULT;
/**
* This is true if the Compass Point attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean compassPointESet;
/**
* The cached value of the '{@link #getDirectionKeyword() <em>Direction Keyword</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDirectionKeyword()
* @generated
* @ordered
*/
protected CodeType directionKeyword;
/**
* The cached value of the '{@link #getDirectionString() <em>Direction String</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getDirectionString()
* @generated
* @ordered
*/
protected StringOrRefType directionString;
/**
* The default value of the '{@link #getActuate() <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getActuate()
* @generated
* @ordered
*/
protected static final ActuateType ACTUATE_EDEFAULT = ActuateType.ON_LOAD_LITERAL;
/**
* The cached value of the '{@link #getActuate() <em>Actuate</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getActuate()
* @generated
* @ordered
*/
protected ActuateType actuate = ACTUATE_EDEFAULT;
/**
* This is true if the Actuate attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean actuateESet;
/**
* The default value of the '{@link #getArcrole() <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArcrole()
* @generated
* @ordered
*/
protected static final String ARCROLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getArcrole() <em>Arcrole</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getArcrole()
* @generated
* @ordered
*/
protected String arcrole = ARCROLE_EDEFAULT;
/**
* The default value of the '{@link #getHref() <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHref()
* @generated
* @ordered
*/
protected static final String HREF_EDEFAULT = null;
/**
* The cached value of the '{@link #getHref() <em>Href</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHref()
* @generated
* @ordered
*/
protected String href = HREF_EDEFAULT;
/**
* The default value of the '{@link #getRemoteSchema() <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRemoteSchema()
* @generated
* @ordered
*/
protected static final String REMOTE_SCHEMA_EDEFAULT = null;
/**
* The cached value of the '{@link #getRemoteSchema() <em>Remote Schema</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRemoteSchema()
* @generated
* @ordered
*/
protected String remoteSchema = REMOTE_SCHEMA_EDEFAULT;
/**
* The default value of the '{@link #getRole() <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRole()
* @generated
* @ordered
*/
protected static final String ROLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getRole() <em>Role</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getRole()
* @generated
* @ordered
*/
protected String role = ROLE_EDEFAULT;
/**
* The default value of the '{@link #getShow() <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShow()
* @generated
* @ordered
*/
protected static final ShowType SHOW_EDEFAULT = ShowType.NEW_LITERAL;
/**
* The cached value of the '{@link #getShow() <em>Show</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShow()
* @generated
* @ordered
*/
protected ShowType show = SHOW_EDEFAULT;
/**
* This is true if the Show attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean showESet;
/**
* The default value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected static final String TITLE_EDEFAULT = null;
/**
* The cached value of the '{@link #getTitle() <em>Title</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getTitle()
* @generated
* @ordered
*/
protected String title = TITLE_EDEFAULT;
/**
* The default value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected static final TypeType TYPE_EDEFAULT = TypeType.SIMPLE_LITERAL;
/**
* The cached value of the '{@link #getType() <em>Type</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getType()
* @generated
* @ordered
*/
protected TypeType type = TYPE_EDEFAULT;
/**
* This is true if the Type attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean typeESet;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected DirectionPropertyTypeImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Gml311Package.eINSTANCE.getDirectionPropertyType();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public DirectionVectorType getDirectionVector() {
return directionVector;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDirectionVector(DirectionVectorType newDirectionVector, NotificationChain msgs) {
DirectionVectorType oldDirectionVector = directionVector;
directionVector = newDirectionVector;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR, oldDirectionVector, newDirectionVector);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setDirectionVector(DirectionVectorType newDirectionVector) {
if (newDirectionVector != directionVector) {
NotificationChain msgs = null;
if (directionVector != null)
msgs = ((InternalEObject)directionVector).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR, null, msgs);
if (newDirectionVector != null)
msgs = ((InternalEObject)newDirectionVector).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR, null, msgs);
msgs = basicSetDirectionVector(newDirectionVector, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR, newDirectionVector, newDirectionVector));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public CompassPointEnumeration getCompassPoint() {
return compassPoint;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setCompassPoint(CompassPointEnumeration newCompassPoint) {
CompassPointEnumeration oldCompassPoint = compassPoint;
compassPoint = newCompassPoint == null ? COMPASS_POINT_EDEFAULT : newCompassPoint;
boolean oldCompassPointESet = compassPointESet;
compassPointESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT, oldCompassPoint, compassPoint, !oldCompassPointESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetCompassPoint() {
CompassPointEnumeration oldCompassPoint = compassPoint;
boolean oldCompassPointESet = compassPointESet;
compassPoint = COMPASS_POINT_EDEFAULT;
compassPointESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT, oldCompassPoint, COMPASS_POINT_EDEFAULT, oldCompassPointESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetCompassPoint() {
return compassPointESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public CodeType getDirectionKeyword() {
return directionKeyword;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDirectionKeyword(CodeType newDirectionKeyword, NotificationChain msgs) {
CodeType oldDirectionKeyword = directionKeyword;
directionKeyword = newDirectionKeyword;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD, oldDirectionKeyword, newDirectionKeyword);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setDirectionKeyword(CodeType newDirectionKeyword) {
if (newDirectionKeyword != directionKeyword) {
NotificationChain msgs = null;
if (directionKeyword != null)
msgs = ((InternalEObject)directionKeyword).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD, null, msgs);
if (newDirectionKeyword != null)
msgs = ((InternalEObject)newDirectionKeyword).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD, null, msgs);
msgs = basicSetDirectionKeyword(newDirectionKeyword, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD, newDirectionKeyword, newDirectionKeyword));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public StringOrRefType getDirectionString() {
return directionString;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDirectionString(StringOrRefType newDirectionString, NotificationChain msgs) {
StringOrRefType oldDirectionString = directionString;
directionString = newDirectionString;
if (eNotificationRequired()) {
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING, oldDirectionString, newDirectionString);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setDirectionString(StringOrRefType newDirectionString) {
if (newDirectionString != directionString) {
NotificationChain msgs = null;
if (directionString != null)
msgs = ((InternalEObject)directionString).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING, null, msgs);
if (newDirectionString != null)
msgs = ((InternalEObject)newDirectionString).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING, null, msgs);
msgs = basicSetDirectionString(newDirectionString, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING, newDirectionString, newDirectionString));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ActuateType getActuate() {
return actuate;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setActuate(ActuateType newActuate) {
ActuateType oldActuate = actuate;
actuate = newActuate == null ? ACTUATE_EDEFAULT : newActuate;
boolean oldActuateESet = actuateESet;
actuateESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE, oldActuate, actuate, !oldActuateESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetActuate() {
ActuateType oldActuate = actuate;
boolean oldActuateESet = actuateESet;
actuate = ACTUATE_EDEFAULT;
actuateESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE, oldActuate, ACTUATE_EDEFAULT, oldActuateESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetActuate() {
return actuateESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getArcrole() {
return arcrole;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setArcrole(String newArcrole) {
String oldArcrole = arcrole;
arcrole = newArcrole;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__ARCROLE, oldArcrole, arcrole));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getHref() {
return href;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setHref(String newHref) {
String oldHref = href;
href = newHref;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__HREF, oldHref, href));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getRemoteSchema() {
return remoteSchema;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setRemoteSchema(String newRemoteSchema) {
String oldRemoteSchema = remoteSchema;
remoteSchema = newRemoteSchema;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__REMOTE_SCHEMA, oldRemoteSchema, remoteSchema));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getRole() {
return role;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setRole(String newRole) {
String oldRole = role;
role = newRole;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__ROLE, oldRole, role));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public ShowType getShow() {
return show;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setShow(ShowType newShow) {
ShowType oldShow = show;
show = newShow == null ? SHOW_EDEFAULT : newShow;
boolean oldShowESet = showESet;
showESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW, oldShow, show, !oldShowESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetShow() {
ShowType oldShow = show;
boolean oldShowESet = showESet;
show = SHOW_EDEFAULT;
showESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW, oldShow, SHOW_EDEFAULT, oldShowESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetShow() {
return showESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getTitle() {
return title;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setTitle(String newTitle) {
String oldTitle = title;
title = newTitle;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__TITLE, oldTitle, title));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public TypeType getType() {
return type;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setType(TypeType newType) {
TypeType oldType = type;
type = newType == null ? TYPE_EDEFAULT : newType;
boolean oldTypeESet = typeESet;
typeESet = true;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE, oldType, type, !oldTypeESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetType() {
TypeType oldType = type;
boolean oldTypeESet = typeESet;
type = TYPE_EDEFAULT;
typeESet = false;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.UNSET, Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE, oldType, TYPE_EDEFAULT, oldTypeESet));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetType() {
return typeESet;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR:
return basicSetDirectionVector(null, msgs);
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD:
return basicSetDirectionKeyword(null, msgs);
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING:
return basicSetDirectionString(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR:
return getDirectionVector();
case Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT:
return getCompassPoint();
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD:
return getDirectionKeyword();
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING:
return getDirectionString();
case Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE:
return getActuate();
case Gml311Package.DIRECTION_PROPERTY_TYPE__ARCROLE:
return getArcrole();
case Gml311Package.DIRECTION_PROPERTY_TYPE__HREF:
return getHref();
case Gml311Package.DIRECTION_PROPERTY_TYPE__REMOTE_SCHEMA:
return getRemoteSchema();
case Gml311Package.DIRECTION_PROPERTY_TYPE__ROLE:
return getRole();
case Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW:
return getShow();
case Gml311Package.DIRECTION_PROPERTY_TYPE__TITLE:
return getTitle();
case Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE:
return getType();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR:
setDirectionVector((DirectionVectorType)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT:
setCompassPoint((CompassPointEnumeration)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD:
setDirectionKeyword((CodeType)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING:
setDirectionString((StringOrRefType)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE:
setActuate((ActuateType)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ARCROLE:
setArcrole((String)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__HREF:
setHref((String)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__REMOTE_SCHEMA:
setRemoteSchema((String)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ROLE:
setRole((String)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW:
setShow((ShowType)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__TITLE:
setTitle((String)newValue);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE:
setType((TypeType)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR:
setDirectionVector((DirectionVectorType)null);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT:
unsetCompassPoint();
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD:
setDirectionKeyword((CodeType)null);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING:
setDirectionString((StringOrRefType)null);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE:
unsetActuate();
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ARCROLE:
setArcrole(ARCROLE_EDEFAULT);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__HREF:
setHref(HREF_EDEFAULT);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__REMOTE_SCHEMA:
setRemoteSchema(REMOTE_SCHEMA_EDEFAULT);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ROLE:
setRole(ROLE_EDEFAULT);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW:
unsetShow();
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__TITLE:
setTitle(TITLE_EDEFAULT);
return;
case Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE:
unsetType();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_VECTOR:
return directionVector != null;
case Gml311Package.DIRECTION_PROPERTY_TYPE__COMPASS_POINT:
return isSetCompassPoint();
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_KEYWORD:
return directionKeyword != null;
case Gml311Package.DIRECTION_PROPERTY_TYPE__DIRECTION_STRING:
return directionString != null;
case Gml311Package.DIRECTION_PROPERTY_TYPE__ACTUATE:
return isSetActuate();
case Gml311Package.DIRECTION_PROPERTY_TYPE__ARCROLE:
return ARCROLE_EDEFAULT == null ? arcrole != null : !ARCROLE_EDEFAULT.equals(arcrole);
case Gml311Package.DIRECTION_PROPERTY_TYPE__HREF:
return HREF_EDEFAULT == null ? href != null : !HREF_EDEFAULT.equals(href);
case Gml311Package.DIRECTION_PROPERTY_TYPE__REMOTE_SCHEMA:
return REMOTE_SCHEMA_EDEFAULT == null ? remoteSchema != null : !REMOTE_SCHEMA_EDEFAULT.equals(remoteSchema);
case Gml311Package.DIRECTION_PROPERTY_TYPE__ROLE:
return ROLE_EDEFAULT == null ? role != null : !ROLE_EDEFAULT.equals(role);
case Gml311Package.DIRECTION_PROPERTY_TYPE__SHOW:
return isSetShow();
case Gml311Package.DIRECTION_PROPERTY_TYPE__TITLE:
return TITLE_EDEFAULT == null ? title != null : !TITLE_EDEFAULT.equals(title);
case Gml311Package.DIRECTION_PROPERTY_TYPE__TYPE:
return isSetType();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (compassPoint: ");
if (compassPointESet) result.append(compassPoint); else result.append("<unset>");
result.append(", actuate: ");
if (actuateESet) result.append(actuate); else result.append("<unset>");
result.append(", arcrole: ");
result.append(arcrole);
result.append(", href: ");
result.append(href);
result.append(", remoteSchema: ");
result.append(remoteSchema);
result.append(", role: ");
result.append(role);
result.append(", show: ");
if (showESet) result.append(show); else result.append("<unset>");
result.append(", title: ");
result.append(title);
result.append(", type: ");
if (typeESet) result.append(type); else result.append("<unset>");
result.append(')');
return result.toString();
}
} //DirectionPropertyTypeImpl
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/tools/importer/FileExporter.java | 3296 | /*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library 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 Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.tools.importer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
/**
*
* The <code>FileExporter</code> writes a new file.
*
* @author <a href="mailto:buesching@lat-lon.de">Lyn Buesching</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*
*/
public class FileExporter implements Exporter {
private static final ILogger LOG = LoggerFactory.getLogger( FileExporter.class );
/**
* @param objectToExport
* contains a ListArray of objects, where the first object contains an Array of bytes
* to export and the second object the information of the target to export
* @return true, when expor is successful; otherwise false
*/
public boolean export( Object objectToExport ) {
Boolean result = false;
byte[] byteArray = (byte[]) ( (ArrayList<Object>) objectToExport ).get( 0 );
String target = (String) ( (ArrayList<Object>) objectToExport ).get( 1 );
LOG.logInfo( Messages.getString( "FileExporter.EXPORT", target ) );
File file = new File( target );
if ( !file.exists() ) {
try {
FileOutputStream fileOS = new FileOutputStream( file );
BufferedOutputStream bufferedOS = new BufferedOutputStream( fileOS );
bufferedOS.write( byteArray, 0, byteArray.length );
bufferedOS.close();
fileOS.close();
result = true;
} catch ( IOException e ) {
LOG.logError( Messages.getString( "FileExporter.ERROR_WRITE_FILE", target, e.getMessage() ) );
e.printStackTrace();
}
} else {
LOG.logInfo( Messages.getString( "FileExporter.ERROR_EXPORT_FILE", target ) );
}
return result;
}
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/jimple/spark/pag/VarNode.java | 4681 | package soot.jimple.spark.pag;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2002 Ondrej Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.AnySubType;
import soot.Context;
import soot.RefLikeType;
import soot.Type;
import soot.toolkits.scalar.Pair;
/**
* Represents a simple variable node (Green) in the pointer assignment graph.
*
* @author Ondrej Lhotak
*/
public abstract class VarNode extends ValNode implements Comparable {
private static final Logger logger = LoggerFactory.getLogger(VarNode.class);
public Context context() {
return null;
}
/** Returns all field ref nodes having this node as their base. */
public Collection<FieldRefNode> getAllFieldRefs() {
if (fields == null) {
return Collections.emptyList();
}
return fields.values();
}
/**
* Returns the field ref node having this node as its base, and field as its field; null if nonexistent.
*/
public FieldRefNode dot(SparkField field) {
return fields == null ? null : fields.get(field);
}
public int compareTo(Object o) {
VarNode other = (VarNode) o;
if (other.finishingNumber == finishingNumber && other != this) {
logger.debug("" + "This is: " + this + " with id " + getNumber() + " and number " + finishingNumber);
logger.debug("" + "Other is: " + other + " with id " + other.getNumber() + " and number " + other.finishingNumber);
throw new RuntimeException("Comparison error");
}
return other.finishingNumber - finishingNumber;
}
public void setFinishingNumber(int i) {
finishingNumber = i;
if (i > pag.maxFinishNumber) {
pag.maxFinishNumber = i;
}
}
/** Returns the underlying variable that this node represents. */
public Object getVariable() {
return variable;
}
/**
* Designates this node as the potential target of a interprocedural assignment edge which may be added during on-the-fly
* call graph updating.
*/
public void setInterProcTarget() {
interProcTarget = true;
}
/**
* Returns true if this node is the potential target of a interprocedural assignment edge which may be added during
* on-the-fly call graph updating.
*/
public boolean isInterProcTarget() {
return interProcTarget;
}
/**
* Designates this node as the potential source of a interprocedural assignment edge which may be added during on-the-fly
* call graph updating.
*/
public void setInterProcSource() {
interProcSource = true;
}
/**
* Returns true if this node is the potential source of a interprocedural assignment edge which may be added during
* on-the-fly call graph updating.
*/
public boolean isInterProcSource() {
return interProcSource;
}
/** Returns true if this VarNode represents the THIS pointer */
public boolean isThisPtr() {
if (variable instanceof Pair) {
Pair o = (Pair) variable;
return o.isThisParameter();
}
return false;
}
/* End of public methods. */
VarNode(PAG pag, Object variable, Type t) {
super(pag, t);
if (!(t instanceof RefLikeType) || t instanceof AnySubType) {
throw new RuntimeException("Attempt to create VarNode of type " + t);
}
this.variable = variable;
pag.getVarNodeNumberer().add(this);
setFinishingNumber(++pag.maxFinishNumber);
}
/** Registers a frn as having this node as its base. */
void addField(FieldRefNode frn, SparkField field) {
if (fields == null) {
fields = new HashMap<SparkField, FieldRefNode>();
}
fields.put(field, frn);
}
/* End of package methods. */
protected Object variable;
protected Map<SparkField, FieldRefNode> fields;
protected int finishingNumber = 0;
protected boolean interProcTarget = false;
protected boolean interProcSource = false;
protected int numDerefs = 0;
}
| lgpl-2.1 |
jfinkels/tuxguitar | src/main/java/org/herac/tuxguitar/gui/actions/duration/SetThirtySecondDurationAction.java | 2345 | /*
* Created on 17-dic-2005
*
* TODO To change the template for this generated file go to Window -
* Preferences - Java - Code Style - Code Templates
*/
package org.herac.tuxguitar.gui.actions.duration;
import org.eclipse.swt.events.TypedEvent;
import org.herac.tuxguitar.gui.TuxGuitar;
import org.herac.tuxguitar.gui.actions.Action;
import org.herac.tuxguitar.gui.editors.tab.Caret;
import org.herac.tuxguitar.gui.undo.undoables.measure.UndoableMeasureGeneric;
import org.herac.tuxguitar.song.models.TGBeat;
import org.herac.tuxguitar.song.models.TGDuration;
import org.herac.tuxguitar.song.models.TGVoice;
/**
* @author julian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SetThirtySecondDurationAction extends Action {
public static final String NAME = "action.note.duration.set-thirty-second";
public static final int VALUE = TGDuration.THIRTY_SECOND;
public SetThirtySecondDurationAction() {
super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | DISABLE_ON_PLAYING
| KEY_BINDING_AVAILABLE);
}
@Override
protected int execute(TypedEvent e) {
Caret caret = getEditor().getTablature().getCaret();
TGBeat beat = caret.getSelectedBeat();
if (beat != null) {
TGVoice voice = beat.getVoice(caret.getVoice());
TGDuration duration = getSelectedDuration();
if (duration.getValue() != VALUE
|| (!voice.isEmpty() && voice.getDuration().getValue() != VALUE)) {
// comienza el undoable
UndoableMeasureGeneric undoable = UndoableMeasureGeneric.startUndo();
getSelectedDuration().setValue(VALUE);
getSelectedDuration().setDotted(false);
getSelectedDuration().setDoubleDotted(false);
setDurations();
// termia el undoable
addUndoableEdit(undoable.endUndo());
}
}
return 0;
}
public TGDuration getSelectedDuration() {
return getEditor().getTablature().getCaret().getDuration();
}
private void setDurations() {
Caret caret = getEditor().getTablature().getCaret();
caret.changeDuration(getSelectedDuration().clone());
TuxGuitar.instance().getFileHistory().setUnsavedFile();
fireUpdate(getEditor().getTablature().getCaret().getMeasure().getNumber());
}
}
| lgpl-2.1 |
solmix/datax | jdbc/src/main/java/org/solmix/datax/jdbc/core/RowCallbackHandler.java | 1016 | /**
* Copyright 2015 The Solmix Project
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.gnu.org/licenses/
* or see the FSF site: http://www.fsf.org.
*/
package org.solmix.datax.jdbc.core;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author solmix.f@gmail.com
* @version $Id$ 2016年5月8日
*/
public interface RowCallbackHandler
{
void processRow(ResultSet rs) throws SQLException;
}
| lgpl-2.1 |
jagazee/teiid-8.7 | engine/src/main/java/org/teiid/dqp/internal/datamgr/ConnectorManager.java | 10168 | /*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.dqp.internal.datamgr;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.naming.InitialContext;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.util.Assertion;
import org.teiid.dqp.message.AtomicRequestID;
import org.teiid.dqp.message.AtomicRequestMessage;
import org.teiid.logging.CommandLogMessage;
import org.teiid.logging.CommandLogMessage.Event;
import org.teiid.logging.LogConstants;
import org.teiid.logging.LogManager;
import org.teiid.logging.MessageLevel;
import org.teiid.metadata.FunctionMethod;
import org.teiid.query.QueryPlugin;
import org.teiid.query.optimizer.capabilities.BasicSourceCapabilities;
import org.teiid.query.optimizer.capabilities.SourceCapabilities;
import org.teiid.query.sql.lang.Command;
import org.teiid.translator.ExecutionContext;
import org.teiid.translator.ExecutionFactory;
import org.teiid.translator.TranslatorException;
/**
* The <code>ConnectorManager</code> manages an {@link ExecutionFactory}
* and its associated workers' state.
*/
public class ConnectorManager {
private static final String JAVA_CONTEXT = "java:/"; //$NON-NLS-1$
private final String translatorName;
private final String connectionName;
private final String jndiName;
private final List<String> id;
// known requests
private final ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem> requestStates = new ConcurrentHashMap<AtomicRequestID, ConnectorWorkItem>();
private volatile SourceCapabilities cachedCapabilities;
private volatile boolean stopped;
private final ExecutionFactory<Object, Object> executionFactory;
public ConnectorManager(String translatorName, String connectionName) {
this(translatorName, connectionName, new ExecutionFactory<Object, Object>());
}
public ConnectorManager(String translatorName, String connectionName, ExecutionFactory<Object, Object> ef) {
this.translatorName = translatorName;
this.connectionName = connectionName;
if (this.connectionName != null) {
if (!this.connectionName.startsWith(JAVA_CONTEXT)) {
jndiName = JAVA_CONTEXT + this.connectionName;
} else {
jndiName = this.connectionName;
}
} else {
jndiName = null;
}
this.executionFactory = ef;
this.id = Arrays.asList(translatorName, connectionName);
}
public String getStausMessage() {
String msg = ""; //$NON-NLS-1$
ExecutionFactory<Object, Object> ef = getExecutionFactory();
if(ef != null) {
if (ef.isSourceRequired()) {
Object conn = null;
try {
conn = getConnectionFactory();
} catch (TranslatorException e) {
// treat this as connection not found.
}
if (conn == null) {
msg = QueryPlugin.Util.getString("datasource_not_found", this.connectionName); //$NON-NLS-1$
}
}
}
else {
msg = QueryPlugin.Util.getString("translator_not_found", this.translatorName); //$NON-NLS-1$
}
return msg;
}
public List<FunctionMethod> getPushDownFunctions(){
return getExecutionFactory().getPushDownFunctions();
}
public SourceCapabilities getCapabilities() throws TranslatorException, TeiidComponentException {
if (cachedCapabilities != null) {
return cachedCapabilities;
}
checkStatus();
ExecutionFactory<Object, Object> translator = getExecutionFactory();
synchronized (this) {
if (cachedCapabilities != null) {
return cachedCapabilities;
}
if (translator.isSourceRequiredForCapabilities()) {
Object connection = null;
Object connectionFactory = null;
try {
connectionFactory = getConnectionFactory();
if (connectionFactory != null) {
connection = translator.getConnection(connectionFactory, null);
}
if (connection == null) {
throw new TranslatorException(QueryPlugin.Event.TEIID31108, QueryPlugin.Util.getString("datasource_not_found", getConnectionName())); //$NON-NLS-1$);
}
LogManager.logDetail(LogConstants.CTX_CONNECTOR, "Initializing the capabilities for", translatorName); //$NON-NLS-1$
executionFactory.initCapabilities(connection);
} finally {
if (connection != null) {
translator.closeConnection(connection, connectionFactory);
}
}
}
BasicSourceCapabilities resultCaps = CapabilitiesConverter.convertCapabilities(translator, id);
cachedCapabilities = resultCaps;
}
return cachedCapabilities;
}
public ConnectorWork registerRequest(AtomicRequestMessage message) throws TeiidComponentException {
checkStatus();
AtomicRequestID atomicRequestId = message.getAtomicRequestID();
LogManager.logDetail(LogConstants.CTX_CONNECTOR, new Object[] {atomicRequestId, "Create State"}); //$NON-NLS-1$
ConnectorWorkItem item = new ConnectorWorkItem(message, this);
Assertion.isNull(requestStates.put(atomicRequestId, item), "State already existed"); //$NON-NLS-1$
return item;
}
ConnectorWork getState(AtomicRequestID requestId) {
return requestStates.get(requestId);
}
/**
* Remove the state associated with
* the given <code>RequestID</code>.
*/
boolean removeState(AtomicRequestID sid) {
LogManager.logDetail(LogConstants.CTX_CONNECTOR, sid, "Remove State"); //$NON-NLS-1$
return requestStates.remove(sid) != null;
}
int size() {
return requestStates.size();
}
/**
* initialize this <code>ConnectorManager</code>.
* @throws TranslatorException
*/
public void start() {
LogManager.logDetail(LogConstants.CTX_CONNECTOR, QueryPlugin.Util.getString("ConnectorManagerImpl.Initializing_connector", translatorName)); //$NON-NLS-1$
}
/**
* Stop this connector.
*/
public void stop() {
stopped = true;
//ensure that all requests receive a response
for (ConnectorWork workItem : this.requestStates.values()) {
workItem.cancel();
}
}
/**
* Add begin point to transaction monitoring table.
* @param qr Request that contains the MetaMatrix command information in the transaction.
*/
void logSRCCommand(AtomicRequestMessage qr, ExecutionContext context, Event cmdStatus, Integer finalRowCnt) {
if (!LogManager.isMessageToBeRecorded(LogConstants.CTX_COMMANDLOGGING, MessageLevel.DETAIL)) {
return;
}
String sqlStr = null;
if(cmdStatus == Event.NEW){
Command cmd = qr.getCommand();
sqlStr = cmd != null ? cmd.toString() : null;
}
String userName = qr.getWorkContext().getUserName();
String transactionID = null;
if ( qr.isTransactional() ) {
transactionID = qr.getTransactionContext().getTransactionId();
}
String modelName = qr.getModelName();
AtomicRequestID sid = qr.getAtomicRequestID();
String principal = userName == null ? "unknown" : userName; //$NON-NLS-1$
CommandLogMessage message = null;
if (cmdStatus == Event.NEW) {
message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), sid.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, sqlStr, context);
}
else {
message = new CommandLogMessage(System.currentTimeMillis(), qr.getRequestID().toString(), sid.getNodeID(), transactionID, modelName, translatorName, qr.getWorkContext().getSessionId(), principal, finalRowCnt, cmdStatus, context);
}
LogManager.log(MessageLevel.DETAIL, LogConstants.CTX_COMMANDLOGGING, message);
}
/**
* Get the <code>Translator</code> object managed by this manager.
* @return the <code>ExecutionFactory</code>.
*/
public ExecutionFactory<Object, Object> getExecutionFactory() {
return this.executionFactory;
}
/**
* Get the ConnectionFactory object required by this manager
* @return
*/
public Object getConnectionFactory() throws TranslatorException {
if (this.connectionName != null) {
try {
InitialContext ic = new InitialContext();
try {
return ic.lookup(jndiName);
} catch (Exception e) {
if (!jndiName.equals(this.connectionName)) {
return ic.lookup(this.connectionName);
}
throw e;
}
} catch (Exception e) {
throw new TranslatorException(QueryPlugin.Event.TEIID30481, e, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30481, this.connectionName));
}
}
return null;
}
private void checkStatus() throws TeiidComponentException {
if (stopped) {
throw new TeiidComponentException(QueryPlugin.Event.TEIID30482, QueryPlugin.Util.gs(QueryPlugin.Event.TEIID30482, this.translatorName));
}
}
public String getTranslatorName() {
return this.translatorName;
}
public String getConnectionName() {
return this.connectionName;
}
public List<String> getId() {
return id;
}
}
| lgpl-2.1 |
Othlon/CherryPig | src/main/java/othlon/cherrypig/client/ClientHandler.java | 1588 | package othlon.cherrypig.client;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.color.ItemColors;
import net.minecraftforge.client.event.ColorHandlerEvent;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import othlon.cherrypig.client.render.PiggyRenderer;
import othlon.cherrypig.init.CPRegistry;
import othlon.cherrypig.items.CustomSpawnEggItem;
public class ClientHandler {
public static void registerRenders(FMLClientSetupEvent event) {
RenderingRegistry.registerEntityRenderingHandler(CPRegistry.CHERRY_PIG.get(), PiggyRenderer::new);
RenderTypeLookup.setRenderLayer(CPRegistry.CHERRY_SAPLING.get(), RenderType.getCutout());;
//Don't use the CHECK_DECAY or DECAYABLE properties for rendering
// ModelLoader.setCustomStateMapper(CPBlocks.cherryLeaf, new StateMap.Builder().ignore(SaplingBlock.STAGE, CHECK_DECAY, DECAYABLE).build());
// ModelLoader.setCustomStateMapper(CPBlocks.cherrySapling, new StateMap.Builder().ignore(SaplingBlock.TYPE).build()); TODO: Not needed
}
public static void registerItemColors(final ColorHandlerEvent.Item event) {
ItemColors colors = event.getItemColors();
for(CustomSpawnEggItem spawneggitem : CustomSpawnEggItem.getEggs()) {
colors.register((p_198141_1_, p_198141_2_) -> {
return spawneggitem.getColor(p_198141_2_);
}, spawneggitem);
}
}
}
| lgpl-2.1 |
gado4b2/device-controllers | application_lyr_dc/application-lyr-dc-common/src/main/java/com/hpe/iot/southbound/service/inflow/SouthboundService.java | 220 | /**
*
*/
package com.hpe.iot.southbound.service.inflow;
/**
* @author sveera
*
*/
public interface SouthboundService {
void processPayload(String manufacturer, String modelId, String version, byte[] payload);
}
| lgpl-2.1 |
ambs/exist | exist-core/src/main/java/org/exist/xquery/functions/util/PrologFunctions.java | 6370 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package org.exist.xquery.functions.util;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.dom.QName;
import org.exist.xquery.*;
import org.exist.xquery.Module;
import org.exist.xquery.functions.fn.LoadXQueryModule;
import org.exist.xquery.value.*;
public class PrologFunctions extends BasicFunction {
protected static final Logger logger = LogManager.getLogger(PrologFunctions.class);
public final static FunctionSignature[] signatures = {
new FunctionSignature(
new QName("import-module", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Dynamically imports an XQuery module into the current context. The parameters have the same " +
"meaning as in an 'import module ...' expression in the query prolog.",
new SequenceType[] {
new FunctionParameterSequenceType("module-uri", Type.ANY_URI, Cardinality.EXACTLY_ONE, "The namespace URI of the module"),
new FunctionParameterSequenceType("prefix", Type.STRING, Cardinality.EXACTLY_ONE, "The prefix to be assigned to the namespace"),
new FunctionParameterSequenceType("location", Type.ANY_URI, Cardinality.ZERO_OR_MORE, "The location of the module")
},
new SequenceType(Type.ITEM, Cardinality.EMPTY_SEQUENCE),
LoadXQueryModule.LOAD_XQUERY_MODULE_2),
new FunctionSignature(
new QName("declare-namespace", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Dynamically declares a namespace/prefix mapping for the current context.",
new SequenceType[] {
new FunctionParameterSequenceType("prefix", Type.STRING, Cardinality.EXACTLY_ONE, "The prefix to be assigned to the namespace"),
new FunctionParameterSequenceType("namespace-uri", Type.ANY_URI, Cardinality.EXACTLY_ONE, "The namespace URI")
},
new SequenceType(Type.ITEM, Cardinality.EMPTY_SEQUENCE)),
new FunctionSignature(
new QName("declare-option", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Dynamically declares a serialization option as with 'declare option'.",
new SequenceType[] {
new FunctionParameterSequenceType("name", Type.STRING, Cardinality.EXACTLY_ONE, "The serialization option name"),
new FunctionParameterSequenceType("option", Type.STRING, Cardinality.EXACTLY_ONE, "The serialization option value")
},
new SequenceType(Type.ITEM, Cardinality.EMPTY_SEQUENCE)),
new FunctionSignature(
new QName("get-option", UtilModule.NAMESPACE_URI, UtilModule.PREFIX),
"Gets the value of a serialization option as set with 'declare option'.",
new SequenceType[] {
new FunctionParameterSequenceType("name", Type.STRING, Cardinality.EXACTLY_ONE, "The serialization option name")
},
new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE))
};
public PrologFunctions(XQueryContext context, FunctionSignature signature) {
super(context, signature);
}
public Sequence eval(Sequence[] args, Sequence contextSequence)
throws XPathException {
if (isCalledAs("declare-namespace")) {
declareNamespace(args);
} else if (isCalledAs("declare-option")) {
declareOption(args);
} else if(isCalledAs("get-option")) {
return getOption(args);
} else{
importModule(args);
}
return Sequence.EMPTY_SEQUENCE;
}
private void declareNamespace(Sequence[] args) throws XPathException {
context.saveState();
String prefix;
if (args[0].isEmpty())
{prefix = "";}
else
{prefix = args[0].getStringValue();}
final String uri = args[1].getStringValue();
context.declareNamespace(prefix, uri);
}
private void importModule(Sequence[] args) throws XPathException {
context.saveState();
final String uri = args[0].getStringValue();
final String prefix = args[1].getStringValue();
final Sequence seq = args[2];
final AnyURIValue[] locationHints = new AnyURIValue[seq.getItemCount()];
for (int i = 0; i < locationHints.length; i++) {
locationHints[i] = (AnyURIValue)seq.itemAt(i);
}
final Module[] modules = context.importModule(uri, prefix, locationHints);
context.getRootContext().resolveForwardReferences();
for (final Module module : modules) {
if (!module.isInternalModule()) {
// ensure variable declarations in the imported module are analyzed.
// unlike when using a normal import statement, this is not done automatically
((ExternalModule)module).analyzeGlobalVars();
}
}
// context.getRootContext().analyzeAndOptimizeIfModulesChanged((PathExpr) context.getRootExpression());
}
private void declareOption(Sequence[] args) throws XPathException {
final String qname = args[0].getStringValue();
final String options = args[1].getStringValue();
context.addDynamicOption(qname, options);
}
private Sequence getOption(final Sequence[] args) throws XPathException {
final String qnameString = args[0].getStringValue();
try {
final QName qname = QName.parse(context, qnameString, context.getDefaultFunctionNamespace());
final Option option = context.getOption(qname);
if (option != null) {
return new StringValue(option.getContents());
} else {
return Sequence.EMPTY_SEQUENCE;
}
} catch (final QName.IllegalQNameException e) {
throw new XPathException(this, ErrorCodes.XPST0081, "No namespace defined for prefix " + qnameString);
}
}
}
| lgpl-2.1 |
backham/AnbFrameForWeb | com.anbtech.anbframe.web/src/main/java/com/anbtech/anbframe/common/service/CodeMngService.java | 219 | package com.anbtech.anbframe.common.service;
import java.util.List;
import com.anbtech.anbframe.anbweb.vo.CodeMngVO;
public interface CodeMngService {
public List getListCode(CodeMngVO param) throws Exception;
}
| lgpl-2.1 |
esig/dss | dss-asic-xades/src/test/java/eu/europa/esig/dss/asic/xades/signature/asics/ASiCSXAdESLevelBMultiFilesParallelTest.java | 6475 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.asic.xades.signature.asics;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.jupiter.api.Test;
import eu.europa.esig.dss.asic.common.ASiCContent;
import eu.europa.esig.dss.asic.common.AbstractASiCContainerExtractor;
import eu.europa.esig.dss.asic.xades.ASiCWithXAdESContainerExtractor;
import eu.europa.esig.dss.asic.xades.ASiCWithXAdESSignatureParameters;
import eu.europa.esig.dss.asic.xades.signature.ASiCWithXAdESService;
import eu.europa.esig.dss.diagnostic.DiagnosticData;
import eu.europa.esig.dss.enumerations.ASiCContainerType;
import eu.europa.esig.dss.enumerations.Indication;
import eu.europa.esig.dss.enumerations.SignatureLevel;
import eu.europa.esig.dss.model.DSSDocument;
import eu.europa.esig.dss.model.FileDocument;
import eu.europa.esig.dss.model.InMemoryDocument;
import eu.europa.esig.dss.model.MimeType;
import eu.europa.esig.dss.model.SignatureValue;
import eu.europa.esig.dss.model.ToBeSigned;
import eu.europa.esig.dss.spi.DSSUtils;
import eu.europa.esig.dss.test.PKIFactoryAccess;
import eu.europa.esig.dss.validation.SignedDocumentValidator;
import eu.europa.esig.dss.validation.reports.Reports;
public class ASiCSXAdESLevelBMultiFilesParallelTest extends PKIFactoryAccess {
@Test
public void test() throws Exception {
List<DSSDocument> documentToSigns = new ArrayList<>();
documentToSigns.add(new InMemoryDocument("Hello World !".getBytes(), "test.text", MimeType.TEXT));
documentToSigns.add(new InMemoryDocument("Bye World !".getBytes(), "test2.text", MimeType.TEXT));
ASiCWithXAdESSignatureParameters signatureParameters = new ASiCWithXAdESSignatureParameters();
signatureParameters.bLevel().setSigningDate(new Date());
signatureParameters.setSigningCertificate(getSigningCert());
signatureParameters.setCertificateChain(getCertificateChain());
signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B);
signatureParameters.aSiC().setContainerType(ASiCContainerType.ASiC_S);
ASiCWithXAdESService service = new ASiCWithXAdESService(getCompleteCertificateVerifier());
ToBeSigned dataToSign = service.getDataToSign(documentToSigns, signatureParameters);
SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), getPrivateKeyEntry());
DSSDocument signedDocument = service.signDocument(documentToSigns, signatureParameters, signatureValue);
signatureParameters.bLevel().setSigningDate(new Date());
signatureParameters.setSigningCertificate(getSigningCert());
signatureParameters.setCertificateChain(getCertificateChain());
signatureParameters.setSignatureLevel(SignatureLevel.XAdES_BASELINE_B);
signatureParameters.aSiC().setContainerType(ASiCContainerType.ASiC_S);
service = new ASiCWithXAdESService(getCompleteCertificateVerifier());
dataToSign = service.getDataToSign(signedDocument, signatureParameters);
signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), getPrivateKeyEntry());
DSSDocument resignedDocument = service.signDocument(signedDocument, signatureParameters, signatureValue);
resignedDocument.writeTo(new FileOutputStream("target/resigned.asics"));
DSSDocument docToCheck = new FileDocument(new File("target/resigned.asics"));
SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(docToCheck);
validator.setCertificateVerifier(getCompleteCertificateVerifier());
Reports reports = validator.validateDocument();
// reports.print();
DiagnosticData diagnosticData = reports.getDiagnosticData();
List<String> signatureIdList = diagnosticData.getSignatureIdList();
assertEquals(2, signatureIdList.size());
for (String sigId : signatureIdList) {
assertTrue(diagnosticData.isBLevelTechnicallyValid(sigId));
assertNotEquals(Indication.FAILED, reports.getSimpleReport().getIndication(sigId));
}
AbstractASiCContainerExtractor extractor = new ASiCWithXAdESContainerExtractor(docToCheck);
ASiCContent result = extractor.extract();
assertEquals(0, result.getUnsupportedDocuments().size());
List<DSSDocument> signatureDocuments = result.getSignatureDocuments();
assertEquals(1, signatureDocuments.size());
String signatureFilename = signatureDocuments.get(0).getName();
assertTrue(signatureFilename.startsWith("META-INF/signature"));
assertTrue(signatureFilename.endsWith(".xml"));
List<DSSDocument> manifestDocuments = result.getManifestDocuments();
assertEquals(0, manifestDocuments.size());
List<DSSDocument> signedDocuments = result.getSignedDocuments();
assertEquals(1, signedDocuments.size());
assertEquals("package.zip", signedDocuments.get(0).getName());
List<DSSDocument> containerDocuments = result.getContainerDocuments();
assertEquals(2, containerDocuments.size());
DSSDocument mimeTypeDocument = result.getMimeTypeDocument();
byte[] mimeTypeContent = DSSUtils.toByteArray(mimeTypeDocument);
try {
assertEquals(MimeType.ASICS.getMimeTypeString(), new String(mimeTypeContent, "UTF-8"));
} catch (UnsupportedEncodingException e) {
fail(e.getMessage());
}
}
@Override
protected String getSigningAlias() {
return GOOD_USER;
}
}
| lgpl-2.1 |
esig/dss | dss-cades/src/test/java/eu/europa/esig/dss/cades/signature/DSS798Test.java | 5360 | /**
* DSS - Digital Signature Services
* Copyright (C) 2015 European Commission, provided under the CEF programme
*
* This file is part of the "DSS - Digital Signature Services" project.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package eu.europa.esig.dss.cades.signature;
import eu.europa.esig.dss.cades.CAdESSignatureParameters;
import eu.europa.esig.dss.enumerations.SignatureLevel;
import eu.europa.esig.dss.enumerations.SignaturePackaging;
import eu.europa.esig.dss.model.DSSDocument;
import eu.europa.esig.dss.model.DSSException;
import eu.europa.esig.dss.model.InMemoryDocument;
import eu.europa.esig.dss.model.SignatureValue;
import eu.europa.esig.dss.model.ToBeSigned;
import eu.europa.esig.dss.simplereport.SimpleReport;
import eu.europa.esig.dss.test.PKIFactoryAccess;
import eu.europa.esig.dss.validation.SignedDocumentValidator;
import eu.europa.esig.dss.validation.reports.Reports;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Date;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DSS798Test extends PKIFactoryAccess {
@Test
public void testExtendDetachedWithoutFile() throws Exception {
DSSDocument documentToSign = new InMemoryDocument("Hello".getBytes(StandardCharsets.UTF_8), "bin.bin");
CAdESSignatureParameters signatureParameters = new CAdESSignatureParameters();
signatureParameters.bLevel().setSigningDate(new Date());
signatureParameters.setSigningCertificate(getSigningCert());
signatureParameters.setCertificateChain(getCertificateChain());
signatureParameters.setSignaturePackaging(SignaturePackaging.DETACHED);
signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_B);
CAdESService service = new CAdESService(getOfflineCertificateVerifier());
// Level B
ToBeSigned dataToSign = service.getDataToSign(documentToSign, signatureParameters);
SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), getPrivateKeyEntry());
DSSDocument signedDocument = service.signDocument(documentToSign, signatureParameters, signatureValue);
// Level T without detached document
CAdESService serviceExtend = new CAdESService(getOfflineCertificateVerifier());
serviceExtend.setTspSource(getGoodTsa());
CAdESSignatureParameters parametersExtend = new CAdESSignatureParameters();
parametersExtend.setSignatureLevel(SignatureLevel.CAdES_BASELINE_T);
assertThrows(DSSException.class, () -> serviceExtend.extendDocument(signedDocument, parametersExtend));
}
@Test
public void testExtendDetachedWithFile() throws Exception {
DSSDocument documentToSign = new InMemoryDocument("Hello".getBytes(StandardCharsets.UTF_8), "bin.bin");
CAdESSignatureParameters signatureParameters = new CAdESSignatureParameters();
signatureParameters.bLevel().setSigningDate(new Date());
signatureParameters.setSigningCertificate(getSigningCert());
signatureParameters.setCertificateChain(getCertificateChain());
signatureParameters.setSignaturePackaging(SignaturePackaging.DETACHED);
signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_B);
CAdESService service = new CAdESService(getOfflineCertificateVerifier());
// Level B
ToBeSigned dataToSign = service.getDataToSign(documentToSign, signatureParameters);
SignatureValue signatureValue = getToken().sign(dataToSign, signatureParameters.getDigestAlgorithm(), getPrivateKeyEntry());
DSSDocument signedDocument = service.signDocument(documentToSign, signatureParameters, signatureValue);
// Level T with detached document
CAdESService serviceExtend = new CAdESService(getOfflineCertificateVerifier());
serviceExtend.setTspSource(getGoodTsa());
CAdESSignatureParameters parametersExtend = new CAdESSignatureParameters();
parametersExtend.setSignatureLevel(SignatureLevel.CAdES_BASELINE_T);
parametersExtend.setDetachedContents(Arrays.asList(documentToSign));
DSSDocument extendedDocument = serviceExtend.extendDocument(signedDocument, parametersExtend);
SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(extendedDocument);
validator.setCertificateVerifier(getOfflineCertificateVerifier());
validator.setDetachedContents(Arrays.asList(documentToSign));
Reports reports = validator.validateDocument();
SimpleReport simpleReport = reports.getSimpleReport();
assertEquals(SignatureLevel.CAdES_BASELINE_T, simpleReport.getSignatureFormat(simpleReport.getFirstSignatureId()));
}
@Override
protected String getSigningAlias() {
return GOOD_USER;
}
}
| lgpl-2.1 |
comundus/opencms-comundus | src/main/java/org/opencms/widgets/CmsMultiSelectWidget.java | 7554 | /*
* File : $Source: /usr/local/cvs/opencms/src/org/opencms/widgets/CmsMultiSelectWidget.java,v $
* Date : $Date: 2008-02-27 12:05:44 $
* Version: $Revision: 1.5 $
*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) 2002 - 2008 Alkacon Software GmbH (http://www.alkacon.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* For further information about Alkacon Software GmbH, please see the
* company website: http://www.alkacon.com
*
* For further information about OpenCms, please see the
* project website: http://www.opencms.org
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.opencms.widgets;
import org.opencms.file.CmsObject;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* Provides a widget for a standard HTML form multi select list or a group of check boxes.<p>
*
* Please see the documentation of <code>{@link org.opencms.widgets.CmsSelectWidgetOption}</code> for a description
* about the configuration String syntax for the select options.<p>
*
* The multi select widget does use the following select options:<ul>
* <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#getValue()}</code> for the value of the option
* <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#isDefault()}</code> for pre-selecting a specific value
* <li><code>{@link org.opencms.widgets.CmsSelectWidgetOption#getOption()}</code> for the display name of the option
* </ul>
* <p>
*
* @author Michael Moossen
*
* @version $Revision: 1.5 $
*
* @since 6.0.0
*/
public class CmsMultiSelectWidget extends A_CmsSelectWidget {
/** Indicates if used html code is a multi selection list or a list of checkboxes. */
private boolean m_asCheckBoxes;
/**
* Creates a new select widget.<p>
*/
public CmsMultiSelectWidget() {
// empty constructor is required for class registration
super();
}
/**
* Creates a select widget with the select options specified in the given configuration List.<p>
*
* The list elements must be of type <code>{@link CmsSelectWidgetOption}</code>.<p>
*
* @param configuration the configuration (possible options) for the select widget
*
* @see CmsSelectWidgetOption
*/
public CmsMultiSelectWidget(List configuration) {
this(configuration, false);
}
/**
* Creates a select widget with the select options specified in the given configuration List.<p>
*
* The list elements must be of type <code>{@link CmsSelectWidgetOption}</code>.<p>
*
* @param configuration the configuration (possible options) for the select widget
* @param asCheckboxes indicates if used html code is a multi selection list or a list of checkboxes
*
* @see CmsSelectWidgetOption
*/
public CmsMultiSelectWidget(List configuration, boolean asCheckboxes) {
super(configuration);
m_asCheckBoxes = asCheckboxes;
}
/**
* Creates a select widget with the specified select options.<p>
*
* @param configuration the configuration (possible options) for the select box
*/
public CmsMultiSelectWidget(String configuration) {
super(configuration);
}
/**
* @see org.opencms.widgets.I_CmsWidget#setEditorValue(org.opencms.file.CmsObject, java.util.Map, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
public void setEditorValue(
CmsObject cms,
Map formParameters,
I_CmsWidgetDialog widgetDialog,
I_CmsWidgetParameter param) {
String[] values = (String[])formParameters.get(param.getId());
if ((values != null) && (values.length > 0)) {
StringBuffer value = new StringBuffer(128);
for (int i = 0; i < values.length; i++) {
if (i > 0) {
value.append(',');
}
value.append(values[i]);
}
// set the value
param.setStringValue(cms, value.toString());
}
}
/**
* @see org.opencms.widgets.I_CmsWidget#getDialogWidget(org.opencms.file.CmsObject, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
public String getDialogWidget(CmsObject cms, I_CmsWidgetDialog widgetDialog, I_CmsWidgetParameter param) {
String id = param.getId();
StringBuffer result = new StringBuffer(16);
List options = parseSelectOptions(cms, widgetDialog, param);
result.append("<td class=\"xmlTd\">");
if (!m_asCheckBoxes) {
result.append("<select multiple size='");
result.append(options.size());
result.append("' class=\"xmlInput");
if (param.hasError()) {
result.append(" xmlInputError");
}
result.append("\" name=\"");
result.append(id);
result.append("\" id=\"");
result.append(id);
result.append("\">");
}
// get select box options from default value String
List selected = getSelectedValues(cms, param);
Iterator i = options.iterator();
while (i.hasNext()) {
CmsSelectWidgetOption option = (CmsSelectWidgetOption)i.next();
// create the option
if (!m_asCheckBoxes) {
result.append("<option value=\"");
result.append(option.getValue());
result.append("\"");
if (selected.contains(option.getValue())) {
result.append(" selected=\"selected\"");
}
result.append(">");
result.append(option.getOption());
result.append("</option>");
} else {
result.append("<input type='checkbox' name='");
result.append(id);
result.append("' value='");
result.append(option.getValue());
result.append("'");
if (selected.contains(option.getValue())) {
result.append(" checked");
}
result.append(">");
result.append(option.getOption());
result.append("<br>");
}
}
if (!m_asCheckBoxes) {
result.append("</select>");
}
result.append("</td>");
return result.toString();
}
/**
* @see org.opencms.widgets.I_CmsWidget#newInstance()
*/
public I_CmsWidget newInstance() {
return new CmsMultiSelectWidget(getConfiguration());
}
} | lgpl-2.1 |
sefaakca/EvoSuite-Sefa | client/src/main/java/org/evosuite/coverage/ibranch/IBranchSecondaryObjective.java | 2748 | /**
* Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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
* Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package org.evosuite.coverage.ibranch;
import org.evosuite.ga.SecondaryObjective;
import org.evosuite.testsuite.TestSuiteChromosome;
/**
* <p>
* IBranchSecondaryObjective class.
* </p>
*
* @author mattia
*/
public class IBranchSecondaryObjective extends SecondaryObjective<TestSuiteChromosome> {
//Ibranch fitness
private IBranchSuiteFitness ff;
private static final long serialVersionUID = 7211557650429998223L;
public IBranchSecondaryObjective() {
ff = new IBranchSuiteFitness();
}
@Override
public int compareChromosomes(
TestSuiteChromosome chromosome1,
TestSuiteChromosome chromosome2) {
double fitness1 = ff.getFitness(chromosome1, false);
double fitness2 = ff.getFitness(chromosome2, false);
int i = (int) Math.signum(fitness1 - fitness2);
// if (!chromosome1.hasExecutedFitness(ff) || chromosome1.isChanged())
// ff.getFitness(chromosome1);
// if (!chromosome2.hasExecutedFitness(ff) || chromosome2.isChanged())
// ff.getFitness(chromosome2);
ff.updateCoveredGoals();
return i;
}
@Override
public int compareGenerations(
TestSuiteChromosome parent1,
TestSuiteChromosome parent2,
TestSuiteChromosome child1,
TestSuiteChromosome child2) {
logger.debug("Comparing sizes: " + parent1.size() + ", " + parent1.size() + " vs "
+ child1.size() + ", " + child2.size());
if (!parent1.hasExecutedFitness(ff) ||parent1.isChanged())
ff.getFitness(parent1);
if (!parent2.hasExecutedFitness(ff) ||parent2.isChanged())
ff.getFitness(parent2);
if (!child1.hasExecutedFitness(ff) ||child1.isChanged())
ff.getFitness(child1);
if (!child2.hasExecutedFitness(ff) ||child2.isChanged())
ff.getFitness(child2);
double minParents = Math.min(parent1.getFitness(ff), parent2.getFitness(ff));
double minChildren = Math.min(child1.getFitness(ff), child2.getFitness(ff));
if (minParents < minChildren) {
return -1;
}
if (minParents > minChildren) {
return 1;
}
return 0;
}
}
| lgpl-3.0 |
nnen/nmcalc | src/main/java/cz/milik/nmcalc/peg/PegScope.java | 2366 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cz.milik.nmcalc.peg;
import cz.milik.nmcalc.utils.IMonad;
import cz.milik.nmcalc.utils.Monad;
import cz.milik.nmcalc.utils.Pair;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
*
* @author jan
*/
public class PegScope {
private final PegScope parent;
public PegScope getParent() {
return parent;
}
private List<Pair<String, Object>> values;
public void add(String aName, Object aValue) {
if (values == null) {
values = new LinkedList();
}
values.add(new Pair(aName, aValue));
}
public <T> IMonad<T> get(String aName, Class<T> aClass) {
if (values == null) {
return Monad.nothing();
}
for (Pair<String, Object> p : values) {
if (p.getFirst().equals(aName)) {
return Monad.just(aClass.cast(p.getSecond()));
}
}
return Monad.nothing();
}
public <T> T expect(String aName, Class<T> aClass) throws PegException {
if (values != null) {
for (Pair<String, Object> p : values) {
if (p.getFirst().equals(aName)) {
return aClass.cast(p.getSecond());
}
}
}
throw new PegException("Value " + aName + " is missing.");
}
public <T> List<T> getAll(String aName, Class<T> aClass) {
if (values == null) {
return Collections.emptyList();
}
List<T> result = new ArrayList();
for (Pair<String, Object> p : values) {
if (p.getFirst().equals(aName)) {
result.add(aClass.cast(p.getSecond()));
}
}
return result;
}
public void update(PegScope other) {
if (values == null) {
if (other.values == null) {
return;
}
values = new LinkedList();
}
values.addAll(other.values);
}
public PegScope(PegScope parent) {
this.parent = parent;
}
}
| lgpl-3.0 |
Glydar/Glydar.next | ParaGlydar/src/main/java/org/glydar/paraglydar/data/DataCreator.java | 255 | package org.glydar.paraglydar.data;
public interface DataCreator {
public EntityData createEntityData();
public EntityData createEntityData(EntityData e);
public Appearance createAppearance();
public Appearance createAppearance(Appearance a);
}
| lgpl-3.0 |
racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/css/model/property/standard/TransitionTimingFunction.java | 1747 | /*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: david.racodon@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.css.model.property.standard;
import org.sonar.css.model.function.standard.CubicBezier;
import org.sonar.css.model.function.standard.Steps;
import org.sonar.css.model.property.StandardProperty;
import org.sonar.css.model.property.validator.HashMultiplierValidator;
import org.sonar.css.model.property.validator.valueelement.IdentifierValidator;
import org.sonar.css.model.property.validator.valueelement.function.FunctionValidator;
public class TransitionTimingFunction extends StandardProperty {
public TransitionTimingFunction() {
addLinks("https://drafts.csswg.org/css-transitions-1/#propdef-transition-timing-function");
addValidators(new HashMultiplierValidator(
new IdentifierValidator("ease", "linear", "ease-in", "ease-out", "ease-in-out", "step-start", "step-end"),
new FunctionValidator(Steps.class, CubicBezier.class)));
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-core/src/main/java/org/sonar/server/platform/ClusterSystemInfoWriter.java | 3968 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.server.platform;
import java.util.Collection;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.health.ClusterHealth;
import org.sonar.server.health.HealthChecker;
import org.sonar.server.platform.monitoring.cluster.AppNodesInfoLoader;
import org.sonar.server.platform.monitoring.cluster.GlobalInfoLoader;
import org.sonar.server.platform.monitoring.cluster.NodeInfo;
import org.sonar.server.platform.monitoring.cluster.SearchNodesInfoLoader;
import org.sonar.server.telemetry.TelemetryDataJsonWriter;
import org.sonar.server.telemetry.TelemetryDataLoader;
public class ClusterSystemInfoWriter extends AbstractSystemInfoWriter {
private final GlobalInfoLoader globalInfoLoader;
private final AppNodesInfoLoader appNodesInfoLoader;
private final SearchNodesInfoLoader searchNodesInfoLoader;
private final HealthChecker healthChecker;
public ClusterSystemInfoWriter(GlobalInfoLoader globalInfoLoader, AppNodesInfoLoader appNodesInfoLoader, SearchNodesInfoLoader searchNodesInfoLoader,
HealthChecker healthChecker, TelemetryDataLoader telemetry, TelemetryDataJsonWriter dataJsonWriter) {
super(telemetry, dataJsonWriter);
this.globalInfoLoader = globalInfoLoader;
this.appNodesInfoLoader = appNodesInfoLoader;
this.searchNodesInfoLoader = searchNodesInfoLoader;
this.healthChecker = healthChecker;
}
@Override
public void write(JsonWriter json) throws InterruptedException {
ClusterHealth clusterHealth = healthChecker.checkCluster();
writeHealth(clusterHealth.getHealth(), json);
writeGlobalSections(json);
writeApplicationNodes(json, clusterHealth);
writeSearchNodes(json, clusterHealth);
writeTelemetry(json);
}
private void writeGlobalSections(JsonWriter json) {
writeSections(globalInfoLoader.load(), json);
}
private void writeApplicationNodes(JsonWriter json, ClusterHealth clusterHealth) throws InterruptedException {
json.name("Application Nodes").beginArray();
Collection<NodeInfo> appNodes = appNodesInfoLoader.load();
for (NodeInfo applicationNode : appNodes) {
writeNodeInfo(applicationNode, clusterHealth, json);
}
json.endArray();
}
private void writeSearchNodes(JsonWriter json, ClusterHealth clusterHealth) {
json.name("Search Nodes").beginArray();
Collection<NodeInfo> searchNodes = searchNodesInfoLoader.load();
searchNodes.forEach(node -> writeNodeInfo(node, clusterHealth, json));
json.endArray();
}
private void writeNodeInfo(NodeInfo nodeInfo, ClusterHealth clusterHealth, JsonWriter json) {
json.beginObject();
json.prop("Name", nodeInfo.getName());
json.prop("Error", nodeInfo.getErrorMessage().orElse(null));
json.prop("Host", nodeInfo.getHost().orElse(null));
json.prop("Started At", nodeInfo.getStartedAt().orElse(null));
clusterHealth.getNodeHealth(nodeInfo.getName()).ifPresent(h -> {
json.prop("Health", h.getStatus().name());
json.name("Health Causes").beginArray().values(h.getCauses()).endArray();
});
writeSections(nodeInfo.getSections(), json);
json.endObject();
}
}
| lgpl-3.0 |
racodond/sonar-css-plugin | css-frontend/src/main/java/org/sonar/plugins/css/api/visitors/issue/LineIssue.java | 1856 | /*
* SonarQube CSS / SCSS / Less Analyzer
* Copyright (C) 2013-2017 David RACODON
* mailto: david.racodon@gmail.com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.plugins.css.api.visitors.issue;
import com.google.common.base.Preconditions;
import java.io.File;
import javax.annotation.Nullable;
import org.sonar.plugins.css.api.CssCheck;
public class LineIssue implements Issue {
private final CssCheck check;
private final File file;
private Double cost;
private final String message;
private final int line;
public LineIssue(CssCheck check, File file, int line, String message) {
Preconditions.checkArgument(line > 0);
this.check = check;
this.file = file;
this.message = message;
this.line = line;
this.cost = null;
}
public String message() {
return message;
}
public int line() {
return line;
}
@Override
public CssCheck check() {
return check;
}
public File file() {
return file;
}
@Nullable
@Override
public Double cost() {
return cost;
}
@Override
public Issue cost(double cost) {
this.cost = cost;
return this;
}
}
| lgpl-3.0 |
nervepoint/identity4j | identity4j-salesforce/src/main/java/com/identity4j/connector/salesforce/services/GroupService.java | 12452 | package com.identity4j.connector.salesforce.services;
/*
* #%L
* Identity4J Salesforce
* %%
* Copyright (C) 2013 - 2017 LogonBox
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import java.io.IOException;
import java.util.List;
import com.identity4j.connector.PrincipalType;
import com.identity4j.connector.exception.ConnectorException;
import com.identity4j.connector.exception.PrincipalAlreadyExistsException;
import com.identity4j.connector.exception.PrincipalNotFoundException;
import com.identity4j.connector.salesforce.SalesforceConfiguration;
import com.identity4j.connector.salesforce.entity.Group;
import com.identity4j.connector.salesforce.entity.GroupMember;
import com.identity4j.connector.salesforce.entity.GroupMembers;
import com.identity4j.connector.salesforce.entity.Groups;
import com.identity4j.util.StringUtil;
import com.identity4j.util.http.HttpPair;
import com.identity4j.util.http.HttpResponse;
import com.identity4j.util.http.request.HttpRequestHandler;
import com.identity4j.util.json.JsonMapperService;
/**
*
* This class is responsible for managing REST calls for Group entity.
*
* @author gaurav
*
*/
public class GroupService extends AbstractRestAPIService {
/**
* Group attributes represented by Group entity in Salesforce data source
*/
private static final String GROUP_ATTRIBUTES = "Id,Name,DeveloperName,RelatedId,Type,Email,OwnerId,"
+ "DoesSendEmailToMembers,DoesIncludeBosses,CreatedDate,CreatedById,LastModifiedDate,"
+ "LastModifiedById,SystemModstamp";
/**
* GroupMember and Group attributes together represented by GroupMember
* entity in Salesforce data source. <br/>
* <b>Note: </b> Group attributes are namespaced by 'Group'.
*/
private static final String GROUP_MEMBER_ATTRIBUTES = "Id,GroupId,UserOrGroupId,Group.Name,Group.Email,Group.DeveloperName,"
+ "Group.RelatedId,Group.Type,Group.OwnerId,Group.DoesSendEmailToMembers,Group.DoesIncludeBosses,Group.CreatedDate,"
+ "Group.CreatedById,Group.LastModifiedDate,Group.LastModifiedById,Group.SystemModstamp";
public GroupService(HttpRequestHandler httpRequestHandler, SalesforceConfiguration serviceConfiguration) {
super(httpRequestHandler, serviceConfiguration);
}
/**
* This method retrieves an instance of Group corresponding to provided
* guid. If group is not found in data store it throws
* PrincipalNotFoundException.
*
* @param guid
* @return Group entity
* @throws PrincipalNotFoundException
* if principal by guid not present in data source
*/
public Group getByGuid(String guid) {
Group group = null;
HttpResponse response = httpRequestHandler.handleRequestGet(constructURI(String.format("Group/%s", guid)),
getHeaders().toArray(new HttpPair[0]));
try {
if (response.status().getCode() == 404 || response.status().getCode() == 400) {
throw new PrincipalNotFoundException(guid + " not found.", null, PrincipalType.role);
}
group = JsonMapperService.getInstance().getObject(Group.class, response.contentString());
return group;
} finally {
response.release();
}
}
/**
* This method retrieves an instance of Group corresponding to provided
* group name. If group is not found in data store it throws
* PrincipalNotFoundException <br />
* This method makes use of <b>Salesforce Object Query Language</b> for
* fetching group.
*
* @param name
* @return Group entity
* @throws PrincipalNotFoundException
* if principal by guid not present in data source
*/
public Group getByName(String name) {
HttpResponse response = httpRequestHandler.handleRequestGet(
constructSOQLURI(String.format(serviceConfiguration.getGetByNameGroupQuery(), GROUP_ATTRIBUTES, name)),
getHeaders().toArray(new HttpPair[0]));
try {
if (response.status().getCode() == 404) {
throw new PrincipalNotFoundException(name + " not found.", null, PrincipalType.role);
}
@SuppressWarnings("unchecked")
List<String> records = (List<String>) JsonMapperService.getInstance()
.getJsonProperty(response.contentString(), "records");
if (records.isEmpty()) {
throw new PrincipalNotFoundException(name + " not found.", null, PrincipalType.role);
}
return JsonMapperService.getInstance().convert(records.get(0), Group.class);
} finally {
response.release();
}
}
/**
* This method retrieves all groups present in the data store. <br />
* This method makes use of <b>Salesforce Object Query Language</b> for
* fetching all groups.
*
* @return groups list
*/
public Groups all() {
HttpResponse response = httpRequestHandler.handleRequestGet(
constructSOQLURI(String.format(serviceConfiguration.getGetAllGroups(), GROUP_ATTRIBUTES)),
getHeaders().toArray(new HttpPair[0]));
try {
return JsonMapperService.getInstance().getObject(Groups.class, response.contentString());
}
finally {
response.release();
}
}
/**
* Saves group into Salesforce datastore.
*
* @param group
* @throws PrincipalAlreadyExistsException
* if group by same principal name exists.
* @throws ConnectorException
* for possible json mapping exceptions or network exceptions
* @return
*/
public Group save(Group group) {
try {
HttpResponse response = httpRequestHandler.handleRequestPost(constructURI("Group"),
JsonMapperService.getInstance().getJson(group), getHeaders().toArray(new HttpPair[0]));
String id = JsonMapperService.getInstance().getJsonProperty(response.contentString(), "id").toString();
group.setId(id);
return group;
} catch (IOException e) {
throw new ConnectorException("Problem in saving group", e);
}
}
/**
* Updates group properties sent for update. <br />
* For finding group to update it makes use of guid.
*
* @param group
* @throws PrincipalNotFoundException
* if the group by object id not found in active directory.
* @throws ConnectorException
* for service related exception.
*/
public void update(Group group) {
String id = null;
try {
// we cannot send id as updatable property hence we cache it and
// clear from pojo
id = group.getId();
group.setId(null);
HttpResponse response = httpRequestHandler.handleRequestPatch(constructURI(String.format("Group/%s", id)),
JsonMapperService.getInstance().getJson(group), getHeaders().toArray(new HttpPair[0]));
if (response.status().getCode() == 404) {
throw new PrincipalNotFoundException(group.getId() + " not found.", null, PrincipalType.role);
}
if (response.status().getCode() != 204) {
throw new ConnectorException("Problem in updating group as status code is not 204 is "
+ response.status().getCode() + " : " + response.contentString());
}
} catch (IOException e) {
throw new ConnectorException("Problem in updating group", e);
} finally {
// reset the cached values
group.setId(id);
}
}
/**
* Deletes group by specified guid.
*
* @param object
* guid of group
* @throws PrincipalNotFoundException
* if the group by object id not found in active directory.
* @throws ConnectorException
* for service related exception.
*/
public void delete(String guid) {
HttpResponse response = httpRequestHandler.handleRequestDelete(constructURI(String.format("Group/%s", guid)),
getHeaders().toArray(new HttpPair[0]));
if (response.status().getCode() == 404 || response.status().getCode() == 400) {
throw new PrincipalNotFoundException(guid + " not found.", null, PrincipalType.role);
}
if (response.status().getCode() != 204) {
throw new ConnectorException("Problem in deleting group as status code is not 204 is "
+ response.status().getCode() + " : " + response.contentString());
}
}
/**
* Adds user to group.
*
* @param userOjectId
* @param groupObjectId
* @throws ConnectorException
* for service related exception.
* @return GroupMember entity representing relation between user and group.
*/
public GroupMember addUserToGroup(String userOjectId, String groupObjectId) {
try {
GroupMember groupMember = new GroupMember();
groupMember.setGroupId(groupObjectId);
groupMember.setUserOrGroupId(userOjectId);
HttpResponse response = httpRequestHandler.handleRequestPost(constructURI("GroupMember"),
JsonMapperService.getInstance().getJson(groupMember), getHeaders().toArray(new HttpPair[0]));
if (response.status().getCode() == 400) {
throw new ConnectorException("Problem in adding group member " + response.status().getCode() + " : "
+ response.contentString());
}
String id = JsonMapperService.getInstance().getJsonProperty(response.contentString().toString(), "id")
.toString();
if (StringUtil.isNullOrEmpty(id)) {
throw new ConnectorException("Problem in saving group member " + response.contentString().toString());
}
groupMember.setId(id);
return groupMember;
} catch (IOException e) {
throw new ConnectorException("Problem in saving group member.", e);
}
}
/**
* Removes user from group.
*
* @param userObjectId
* @param groupObjectId
* @throws ConnectorException
* for service related exception.
*/
public void removeUserFromGroup(String userObjectId, String groupObjectId) {
// first find group member representing relation between user and group
GroupMember groupMember = getGroupMemberForUserAndGroup(userObjectId, groupObjectId);
// using group member id for deleting relation
HttpResponse response = httpRequestHandler.handleRequestDelete(
constructURI(String.format("GroupMember/%s", groupMember.getId())), getHeaders().toArray(new HttpPair[0]));
if (response.status().getCode() != 204) {
throw new ConnectorException("Problem in deleting group member as status code is not 204 is "
+ response.status().getCode() + " : " + response.contentString());
}
}
/**
* Finds relationship id i.e. between user and group represented by
* GroupMember entity.
*
* @param userObjectId
* @param groupObjectId
* @return GroupMember
* @throws PrincipalNotFoundException
* if relationship cannot be determined between user and group
*/
public GroupMember getGroupMemberForUserAndGroup(String userObjectId, String groupObjectId) {
GroupMembers groupMembers = getGroupMembersForUser(userObjectId);
if (groupMembers.getGroupMembers().isEmpty()) {
throw new PrincipalNotFoundException("Group member not found for User ID and Group Id " + userObjectId + " "
+ groupObjectId + " not found.", null, PrincipalType.role);
}
return groupMembers.getGroupMembers().get(0);
}
/**
* Finds relationship id i.e. between user and group represented by
* GroupMember entity.
*
* @param userObjectId
* @return GroupMembers id
* @throws PrincipalNotFoundException
* if relationship cannot be determined between user and group
*/
public GroupMembers getGroupMembersForUser(String userObjectId) {
HttpResponse response = httpRequestHandler.handleRequestGet(constructSOQLURI(
String.format(serviceConfiguration.getGetGroupMembersForUser(), GROUP_MEMBER_ATTRIBUTES, userObjectId)),
getHeaders().toArray(new HttpPair[0]));
try {
return JsonMapperService.getInstance().getObject(GroupMembers.class, response.contentString().toString());
}
finally {
response.release();
}
}
/**
* Helper method to check for already existing group response message
*
* @param group
* @param response
*/
public boolean groupAlreadyExists(String groupName) {
try {
Group group = getByName(groupName);
return group != null && groupName.equals(group.getName());
} catch (PrincipalNotFoundException e) {
return false;
}
}
}
| lgpl-3.0 |
neduard/YORLL-Java | marl/visualisation/KeyboardInput.java | 3814 | package marl.visualisation;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* <p>This Class was written by Tim Wright, 12-11-2008. All credit goes to
* him, thank you very much Tim 'tis a very useful class indeed!</p>
* <p>It was access and copied on 12-11-2008, from
* <a href="http://www.gamedev.net/reference/programming/features/javainput/page2.asp">
* http://www.gamedev.net/reference/programming/features/javainput/page2.asp}</a>.</p>
*
*
* @author Tim Wright
*
*/
public class KeyboardInput implements KeyListener, InputMonitor
{
private static final int KEY_COUNT = 256;
private enum KeyState {
RELEASED, // Not down
PRESSED, // Down, but not the first time
ONCE // Down for the first time
}
// Current state of the keyboard
private boolean[] currentKeys = null;
// Polled keyboard state
private KeyState[] keys = null;
public KeyboardInput() {
currentKeys = new boolean[ KEY_COUNT ];
keys = new KeyState[ KEY_COUNT ];
clear();
}
/**
* @see scopesproject.io.InputMonitor#poll()
*/
@Override
public synchronized void poll() {
for( int i = 0; i < KEY_COUNT; ++i ) {
// Set the key state
if( currentKeys[ i ] ) {
// If the key is down now, but was not
// down last frame, set it to ONCE,
// otherwise, set it to PRESSED
if( keys[ i ] == KeyState.RELEASED )
keys[ i ] = KeyState.ONCE;
else
keys[ i ] = KeyState.PRESSED;
} else {
keys[ i ] = KeyState.RELEASED;
}
}
}
/**
* @see scopesproject.io.InputMonitor#clear()
*/
@Override
public synchronized void clear() {
for( int i = 0; i < KEY_COUNT; ++i ) {
currentKeys[ i ] = false;
keys[ i ] = KeyState.RELEASED;
}
}
/**
* <p>Check to see if the specified {@link KeyEvent key event}
* <code>keyCode</code> was pressed or still is down since the
* input monitor was last polled.</p>
* @param keyCode The key code to check
* @return True if was pressed or still is pressed
*/
public boolean keyDown( int keyCode ) {
return keys[ keyCode ] == KeyState.ONCE ||
keys[ keyCode ] == KeyState.PRESSED;
}
/**
* <p>Check to see if the specified {@link KeyEvent key event}
* <code>keyCode</code> was pressed and wasn't down last time the
* input monitor was last polled.</p>
* @param keyCode The key code to be check
* @return True if was pressed not last time
*/
public boolean keyDownOnce( int keyCode ) {
return keys[ keyCode ] == KeyState.ONCE;
}
/**
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
@Override
public synchronized void keyPressed( KeyEvent e ) {
int keyCode = e.getKeyCode();
if( keyCode >= 0 && keyCode < KEY_COUNT ) {
currentKeys[ keyCode ] = true;
}
}
/**
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@Override
public synchronized void keyReleased( KeyEvent e ) {
int keyCode = e.getKeyCode();
if( keyCode >= 0 && keyCode < KEY_COUNT ) {
currentKeys[ keyCode ] = false;
}
}
/**
* <p>This method is not needed.</p>
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
@Override
public void keyTyped( KeyEvent e ) {
// Not needed
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | benchmark_typechecker/subjectSystems/GUIDSL/fillgs_stubfix/ConsStmt.java | 80 | import de.uni_passau.spl.bytecodecomposer.stubs.Stub;
public class ConsStmt {
}
| lgpl-3.0 |
SirmaITT/conservation-space-1.7.0 | docker/sirma-platform/platform/seip-parent/platform/domain-model/instance-export/src/test/java/com/sirma/sep/export/ExportURIBuilderImplTest.java | 2499 | package com.sirma.sep.export;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.net.URI;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import com.sirma.itt.seip.configuration.SystemConfiguration;
import com.sirma.itt.seip.resources.EmfUser;
import com.sirma.itt.seip.rest.secirity.SecurityTokensManager;
import com.sirma.itt.seip.security.context.SecurityContext;
import com.sirma.itt.seip.testutil.mocks.ConfigurationPropertyMock;
/**
* Test for {@link ExportURIBuilderImpl}.
*
* @author A. Kunchev
*/
public class ExportURIBuilderImplTest {
@InjectMocks
private ExportURIBuilder builder;
@Mock
private SystemConfiguration systemConfiguration;
@Mock
private SecurityTokensManager securityTokensManager;
@Mock
private SecurityContext securityContext;
@Before
public void setup() {
builder = new ExportURIBuilderImpl();
MockitoAnnotations.initMocks(this);
}
@Test(expected = IllegalArgumentException.class)
public void generateURI_emptyInstanceId() {
builder.generateURI("");
}
@Test(expected = IllegalArgumentException.class)
public void generateURI_nullInstanceId() {
builder.generateURI(null);
}
@Test
public void generateURI_defaultToken() {
mockToken("current-user-jwt-token");
when(systemConfiguration.getUi2Url()).thenReturn(new ConfigurationPropertyMock<>("http://localhost:5000/"));
URI generatedURI = builder.generateURI("instance-id", null);
assertEquals("http://localhost:5000/#/idoc/instance-id?jwt=current-user-jwt-token&mode=print",
generatedURI.toString());
}
@Test
public void generateURIForTabs_withTokenAndTabs() {
when(systemConfiguration.getUi2Url()).thenReturn(new ConfigurationPropertyMock<>("http://localhost:5000/"));
URI generatedURI = builder.generateURIForTabs(Arrays.asList("tab-1", "tab-2"), "instance-id", "user-token");
assertEquals("http://localhost:5000/#/idoc/instance-id?tab=tab-1&tab=tab-2&jwt=user-token&mode=print",
generatedURI.toString());
}
@Test
public void getCurrentJwtToken_withAuthenticatedUser() {
mockToken("current-user-token");
assertEquals("current-user-token", builder.getCurrentJwtToken());
}
private void mockToken(String token) {
EmfUser user = new EmfUser();
when(securityContext.getAuthenticated()).thenReturn(user);
when(securityTokensManager.generate(user)).thenReturn(token);
}
} | lgpl-3.0 |
SergiyKolesnikov/fuji | examples/AHEAD/bcSmx/SmExtendsClause.java | 163 |
public class SmExtendsClause {
public String GetName() {
AstNode.override( "SmExtendsClause.GetName()", this );
return null;
}
}
| lgpl-3.0 |
OurGrid/OurGrid | src/main/java/org/ourgrid/worker/ui/async/client/WorkerAsyncComponentClient.java | 4673 | /*
* Copyright (C) 2008 Universidade Federal de Campina Grande
*
* This file is part of OurGrid.
*
* OurGrid is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.ourgrid.worker.ui.async.client;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.ourgrid.common.interfaces.management.WorkerManager;
import org.ourgrid.common.ui.OurGridUIController;
import org.ourgrid.common.ui.servicesetup.ServiceSetupException;
import org.ourgrid.peer.ui.async.client.PeerAsyncApplicationClient;
import org.ourgrid.worker.ui.async.model.GetWorkerStatusRepeatedAction;
import org.ourgrid.worker.ui.async.model.WorkerAsyncUIModel;
import br.edu.ufcg.lsd.commune.container.servicemanager.client.InitializationContext;
import br.edu.ufcg.lsd.commune.container.servicemanager.client.async.AsyncApplicationClient;
import br.edu.ufcg.lsd.commune.context.ModuleContext;
import br.edu.ufcg.lsd.commune.network.ConnectionListener;
import br.edu.ufcg.lsd.commune.network.xmpp.CommuneNetworkException;
import br.edu.ufcg.lsd.commune.processor.ProcessorStartException;
/**
* Asynchronous Component Client for Worker Component
*
*/
public class WorkerAsyncComponentClient extends
AsyncApplicationClient<WorkerManager, WorkerAsyncManagerClient> implements OurGridUIController {
private WorkerAsyncUIModel model;
public static final String GET_STATUS_ACTION = "GET_STATUS_ACTION";
public WorkerAsyncComponentClient(ModuleContext context, WorkerAsyncUIModel model, ConnectionListener listener)
throws CommuneNetworkException, ProcessorStartException {
super("WORKER_ASYNC_UI", context, listener);
this.model = model;
}
@Override
protected void deploymentDone() {
addActionForRepetition(GET_STATUS_ACTION, new GetWorkerStatusRepeatedAction());
}
/**
* Requests the Worker Component to pause.
* Uses the ControlClient as callback.
*/
public void pause() {
getManager().pause(getManagerClient());
model.workerPaused();
}
/**
* Requests the Worker Component to resume.
* Uses the ControlClient as callback.
*/
public void resume() {
getManager().resume(getManagerClient());
model.workerResumed();
}
@Override
protected InitializationContext<WorkerManager, WorkerAsyncManagerClient> createInitializationContext() {
return new WorkerAsyncInitializationContext();
}
/**
* Load properties stored on peer properties file on the model.
*/
public void loadProperties() {
model.loadProperties();
}
/**
* Saves current properties on its correspondent file
* @see WorkerAsyncUIModel.saveProperties
*/
public void saveProperties() throws IOException {
model.saveProperties();
}
/**
* Sets a property value on the model.
* @param prop The property to be set
* @param value The new value for this property
*/
public void setProperty(String prop, String value) {
model.setProperty(prop, value);
}
/**
* @return The model associated to this ComponentClient
*/
public WorkerAsyncUIModel getModel() {
return model;
}
/**
* Requests worker complete status, using the
* WorkerStatusProviderClient as callback object.
*/
public void getWorkerCompleteStatus() {
getManager().getCompleteStatus(getManagerClient());
}
/**
* Install peer as service
* @throws ServiceSetupException
*/
public void installAsService() throws ServiceSetupException {
model.getServiceSetup().installAsService();
}
/**
* Uninstall peer service
* @throws ServiceSetupException
*/
public void uninstallService() throws ServiceSetupException {
model.getServiceSetup().uninstallService();
}
public void workerStarted() {
model.workerStarted();
if (getModel().isStatusFutureCancelled()) {
getModel().setStatusFuture(scheduleActionWithFixedDelay(
PeerAsyncApplicationClient.GET_STATUS_ACTION, 0, 10,
TimeUnit.SECONDS, null));
}
}
public void workerStopped() {
model.workerStopped();
model.cancelStatusFuture();
}
public void restoreDefaultPropertiesValues() {
getModel().restoreDefaultPropertiesValues();
}
}
| lgpl-3.0 |
nelasoft/OpenCmsMobile-AndroidApp | OpenCmsMobile/src/cz/nelasoft/opencms/mobile/NewsAdapter.java | 2483 | package cz.nelasoft.opencms.mobile;
import java.util.List;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class NewsAdapter extends ArrayAdapter<News> {
private final LayoutInflater mInflater;
private List<News> data;
private Context context;
// private DrawableBackgroundDownloader dbd = new
// DrawableBackgroundDownloader();
private ImageLoader imageLoader;
public NewsAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
imageLoader = new ImageLoader(context, R.drawable.z_file_png);
}
public void setData(List<News> data) {
this.data = data;
clear();
if (data != null) {
for (News appEntry : data) {
add(appEntry);
}
}
}
public List<News> getData() {
return data;
}
/**
* Populate new items in the list.
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
view = mInflater.inflate(R.layout.list_item_news, parent, false);
} else {
view = convertView;
}
News item = getItem(position);
/**
* if (item.getBitmap() != null) {
* ((ImageView)view.findViewById(R.id.newsImage
* )).setImageBitmap(item.getBitmap()); } else {
* ((ImageView)view.findViewById
* (R.id.newsImage)).setImageResource(R.drawable.z_file_png); }
*/
if (!TextUtils.isEmpty(item.getImagePath())) {
imageLoader.displayImage(Config.getConfigContext() + item.getImagePath(), (ImageView) view.findViewById(R.id.newsImage));
}
// dbd.loadDrawable(Config.getConfigContext() + item.getImagePath(),
// (ImageView)view.findViewById(R.id.newsImage), null);
((TextView) view.findViewById(R.id.newsHeadline)).setText(item.getHeadline());
// ((TextView)view.findViewById(R.id.newsPerex)).setText(item.getPerex());
if (item.getDate() != null) {
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(context);
String dateValue = dateFormat.format(item.getDate());
((TextView) view.findViewById(R.id.newsDate)).setText(dateValue);
}
return view;
}
}
| lgpl-3.0 |
scodynelson/JCL | jcl-core/src/main/java/jcl/lang/statics/NumberConstants.java | 9980 | /*
* Copyright (C) 2011-2014 Cody Nelson - All rights reserved.
*/
package jcl.lang.statics;
import jcl.lang.DoubleFloatStruct;
import jcl.lang.FloatStruct;
import jcl.lang.IntegerStruct;
import jcl.lang.SingleFloatStruct;
import jcl.lang.internal.ConstantStructImpl;
import org.apache.commons.math3.util.Precision;
public interface NumberConstants {
ConstantStructImpl<IntegerStruct> BOOLE_1 = ConstantStructImpl.valueOf("BOOLE-1", GlobalPackageStruct.COMMON_LISP, IntegerStruct.ZERO);
ConstantStructImpl<IntegerStruct> BOOLE_2 = ConstantStructImpl.valueOf("BOOLE-2", GlobalPackageStruct.COMMON_LISP, IntegerStruct.ONE);
ConstantStructImpl<IntegerStruct> BOOLE_AND = ConstantStructImpl.valueOf("BOOLE-AND", GlobalPackageStruct.COMMON_LISP, IntegerStruct.TWO);
ConstantStructImpl<IntegerStruct> BOOLE_ANDC1 = ConstantStructImpl.valueOf("BOOLE-ANDC1", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(3));
ConstantStructImpl<IntegerStruct> BOOLE_ANDC2 = ConstantStructImpl.valueOf("BOOLE-ANDC2", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(4));
ConstantStructImpl<IntegerStruct> BOOLE_C1 = ConstantStructImpl.valueOf("BOOLE-C1", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(5));
ConstantStructImpl<IntegerStruct> BOOLE_C2 = ConstantStructImpl.valueOf("BOOLE-C2", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(6));
ConstantStructImpl<IntegerStruct> BOOLE_CLR = ConstantStructImpl.valueOf("BOOLE-CLR", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(7));
ConstantStructImpl<IntegerStruct> BOOLE_EQV = ConstantStructImpl.valueOf("BOOLE-EQV", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(8));
ConstantStructImpl<IntegerStruct> BOOLE_IOR = ConstantStructImpl.valueOf("BOOLE-IOR", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(9));
ConstantStructImpl<IntegerStruct> BOOLE_NAND = ConstantStructImpl.valueOf("BOOLE-NAND", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(10));
ConstantStructImpl<IntegerStruct> BOOLE_NOR = ConstantStructImpl.valueOf("BOOLE-NOR", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(11));
ConstantStructImpl<IntegerStruct> BOOLE_ORC1 = ConstantStructImpl.valueOf("BOOLE-ORC1", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(12));
ConstantStructImpl<IntegerStruct> BOOLE_ORC2 = ConstantStructImpl.valueOf("BOOLE-ORC2", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(13));
ConstantStructImpl<IntegerStruct> BOOLE_SET = ConstantStructImpl.valueOf("BOOLE-SET", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(14));
ConstantStructImpl<IntegerStruct> BOOLE_XOR = ConstantStructImpl.valueOf("BOOLE-XOR", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(15));
ConstantStructImpl<IntegerStruct> MOST_POSITIVE_FIXNUM = ConstantStructImpl.valueOf("MOST-POSITIVE-FIXNUM", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(Integer.MAX_VALUE));
ConstantStructImpl<IntegerStruct> MOST_NEGATIVE_FIXNUM = ConstantStructImpl.valueOf("MOST-NEGATIVE-FIXNUM", GlobalPackageStruct.COMMON_LISP, IntegerStruct.toLispInteger(Integer.MIN_VALUE));
Object EPSILON_PLACEHOLDER = Precision.EPSILON;
ConstantStructImpl<FloatStruct> MOST_POSITIVE_SHORT_FLOAT = ConstantStructImpl.valueOf("MOST-POSITIVE-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_SHORT_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_NORMALIZED_SHORT_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-NORMALIZED-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MIN_NORMAL));
ConstantStructImpl<FloatStruct> MOST_NEGATIVE_SHORT_FLOAT = ConstantStructImpl.valueOf("MOST-NEGATIVE-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_SHORT_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_NORMALIZED_SHORT_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-NORMALIZED-SHORT-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MIN_NORMAL));
ConstantStructImpl<FloatStruct> SHORT_FLOAT_EPSILON = ConstantStructImpl.valueOf("SHORT-FLOAT-EPSILON", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(5.960465E-8F));
ConstantStructImpl<FloatStruct> SHORT_FLOAT_NEGATIVE_EPSILON = ConstantStructImpl.valueOf("SHORT-FLOAT-NEGATIVE-EPSILON", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(2.9802326e-8F));
ConstantStructImpl<FloatStruct> MOST_POSITIVE_SINGLE_FLOAT = ConstantStructImpl.valueOf("MOST-POSITIVE-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_SINGLE_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_NORMALIZED_SINGLE_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-NORMALIZED-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(Float.MIN_NORMAL));
ConstantStructImpl<FloatStruct> MOST_NEGATIVE_SINGLE_FLOAT = ConstantStructImpl.valueOf("MOST-NEGATIVE-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_SINGLE_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_NORMALIZED_SINGLE_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-NORMALIZED-SINGLE-FLOAT", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(-Float.MIN_NORMAL));
ConstantStructImpl<FloatStruct> SINGLE_FLOAT_EPSILON = ConstantStructImpl.valueOf("SINGLE-FLOAT-EPSILON", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(5.960465E-8F));
ConstantStructImpl<FloatStruct> SINGLE_FLOAT_NEGATIVE_EPSILON = ConstantStructImpl.valueOf("SINGLE-FLOAT-NEGATIVE-EPSILON", GlobalPackageStruct.COMMON_LISP, SingleFloatStruct.toLispFloat(2.9802326e-8F));
ConstantStructImpl<FloatStruct> MOST_POSITIVE_DOUBLE_FLOAT = ConstantStructImpl.valueOf("MOST-POSITIVE-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_DOUBLE_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_NORMALIZED_DOUBLE_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-NORMALIZED-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MIN_NORMAL));
ConstantStructImpl<FloatStruct> MOST_NEGATIVE_DOUBLE_FLOAT = ConstantStructImpl.valueOf("MOST-NEGATIVE-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_DOUBLE_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_NORMALIZED_DOUBLE_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-NORMALIZED-DOUBLE-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MIN_NORMAL));
ConstantStructImpl<FloatStruct> DOUBLE_FLOAT_EPSILON = ConstantStructImpl.valueOf("DOUBLE-FLOAT-EPSILON", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(1.1102230246251568E-16D));
ConstantStructImpl<FloatStruct> DOUBLE_FLOAT_NEGATIVE_EPSILON = ConstantStructImpl.valueOf("DOUBLE-FLOAT-NEGATIVE-EPSILON", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(5.551115123125784E-17D));
ConstantStructImpl<FloatStruct> MOST_POSITIVE_LONG_FLOAT = ConstantStructImpl.valueOf("MOST-POSITIVE-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_LONG_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_POSITIVE_NORMALIZED_LONG_FLOAT = ConstantStructImpl.valueOf("LEAST-POSITIVE-NORMALIZED-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Double.MIN_NORMAL));
ConstantStructImpl<FloatStruct> MOST_NEGATIVE_LONG_FLOAT = ConstantStructImpl.valueOf("MOST-NEGATIVE-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MAX_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_LONG_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MIN_VALUE));
ConstantStructImpl<FloatStruct> LEAST_NEGATIVE_NORMALIZED_LONG_FLOAT = ConstantStructImpl.valueOf("LEAST-NEGATIVE-NORMALIZED-LONG-FLOAT", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(-Double.MIN_NORMAL));
ConstantStructImpl<FloatStruct> LONG_FLOAT_EPSILON = ConstantStructImpl.valueOf("LONG-FLOAT-EPSILON", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(1.1102230246251568E-16D));
ConstantStructImpl<FloatStruct> LONG_FLOAT_NEGATIVE_EPSILON = ConstantStructImpl.valueOf("LONG-FLOAT-NEGATIVE-EPSILON", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(5.551115123125784E-17D));
ConstantStructImpl<FloatStruct> PI = ConstantStructImpl.valueOf("PI", GlobalPackageStruct.COMMON_LISP, DoubleFloatStruct.toLispFloat(Math.PI));
}
| lgpl-3.0 |
Dukmeister/AOChat | src/main/java/net/aocraft/plugins/AOChat/ChatUser.java | 946 | /**
* Needed to hold ignore list and user status (muted, etc)
*/
package net.aocraft.plugins.AOChat;
import java.util.ArrayList;
/**
* @author Ducky
*
*/
public class ChatUser {
// Class fields
String chUserName;
ArrayList<viewPort> chViewPorts;
// Class Constructor
public ChatUser(String pUserName){
chUserName = pUserName;
chViewPorts = new ArrayList<viewPort>();
}
// Class Methods
public void removeViewPort(viewPort pViewPort) {
for (int i = 0; i < chViewPorts.size(); i++) {
if (chViewPorts.get(i) == pViewPort) {
chViewPorts.remove(i);
return;
}
}
}
public void addViewPort(viewPort pViewPort) {
chViewPorts.add(pViewPort);
}
// Class getters and setters
public String getChUserName() {
return chUserName;
}
public void setChUserName(String chUserName) {
this.chUserName = chUserName;
}
public ArrayList<viewPort> getViewPorts() {
return chViewPorts;
}
}
| lgpl-3.0 |
xorware/android_packages_apps_Settings | src/com/android/settings/ConfirmDeviceCredentialBaseFragment.java | 14102 | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.android.settings;
import android.annotation.Nullable;
import android.app.ActivityManager;
import android.app.ActivityManagerNative;
import android.app.ActivityOptions;
import android.app.AlertDialog;
import android.app.IActivityManager;
import android.app.admin.DevicePolicyManager;
import android.app.trust.TrustManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentSender;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.os.UserManager;
import android.security.KeyStore;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.internal.widget.LockPatternUtils;
import com.android.settings.fingerprint.FingerprintUiHelper;
/**
* Base fragment to be shared for PIN/Pattern/Password confirmation fragments.
*/
public abstract class ConfirmDeviceCredentialBaseFragment extends OptionsMenuFragment
implements FingerprintUiHelper.Callback {
public static final String PACKAGE = "com.android.settings";
public static final String TITLE_TEXT = PACKAGE + ".ConfirmCredentials.title";
public static final String HEADER_TEXT = PACKAGE + ".ConfirmCredentials.header";
public static final String DETAILS_TEXT = PACKAGE + ".ConfirmCredentials.details";
public static final String ALLOW_FP_AUTHENTICATION =
PACKAGE + ".ConfirmCredentials.allowFpAuthentication";
public static final String DARK_THEME = PACKAGE + ".ConfirmCredentials.darkTheme";
public static final String SHOW_CANCEL_BUTTON =
PACKAGE + ".ConfirmCredentials.showCancelButton";
public static final String SHOW_WHEN_LOCKED =
PACKAGE + ".ConfirmCredentials.showWhenLocked";
private FingerprintUiHelper mFingerprintHelper;
protected boolean mIsStrongAuthRequired;
private boolean mAllowFpAuthentication;
protected boolean mReturnCredentials = false;
protected Button mCancelButton;
protected ImageView mFingerprintIcon;
protected int mEffectiveUserId;
protected int mUserId;
protected LockPatternUtils mLockPatternUtils;
protected TextView mErrorTextView;
protected final Handler mHandler = new Handler();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAllowFpAuthentication = getActivity().getIntent().getBooleanExtra(
ALLOW_FP_AUTHENTICATION, false);
mReturnCredentials = getActivity().getIntent().getBooleanExtra(
ChooseLockSettingsHelper.EXTRA_KEY_RETURN_CREDENTIALS, false);
// Only take this argument into account if it belongs to the current profile.
Intent intent = getActivity().getIntent();
mUserId = Utils.getUserIdFromBundle(getActivity(), intent.getExtras());
final UserManager userManager = UserManager.get(getActivity());
mEffectiveUserId = userManager.getCredentialOwnerProfile(mUserId);
mLockPatternUtils = new LockPatternUtils(getActivity());
mIsStrongAuthRequired = isFingerprintDisallowedByStrongAuth();
mAllowFpAuthentication = mAllowFpAuthentication && !isFingerprintDisabledByAdmin()
&& !mReturnCredentials && !mIsStrongAuthRequired;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mCancelButton = (Button) view.findViewById(R.id.cancelButton);
mFingerprintIcon = (ImageView) view.findViewById(R.id.fingerprintIcon);
mFingerprintHelper = new FingerprintUiHelper(
mFingerprintIcon,
(TextView) view.findViewById(R.id.errorText), this, mEffectiveUserId);
boolean showCancelButton = getActivity().getIntent().getBooleanExtra(
SHOW_CANCEL_BUTTON, false);
mCancelButton.setVisibility(showCancelButton ? View.VISIBLE : View.GONE);
mCancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().finish();
}
});
int credentialOwnerUserId = Utils.getCredentialOwnerUserId(
getActivity(),
Utils.getUserIdFromBundle(
getActivity(),
getActivity().getIntent().getExtras()));
if (Utils.isManagedProfile(UserManager.get(getActivity()), credentialOwnerUserId)) {
setWorkChallengeBackground(view, credentialOwnerUserId);
}
}
private boolean isFingerprintDisabledByAdmin() {
DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
final int disabledFeatures = dpm.getKeyguardDisabledFeatures(null, mEffectiveUserId);
return (disabledFeatures & DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT) != 0;
}
// User could be locked while Effective user is unlocked even though the effective owns the
// credential. Otherwise, fingerprint can't unlock fbe/keystore through
// verifyTiedProfileChallenge. In such case, we also wanna show the user message that
// fingerprint is disabled due to device restart.
private boolean isFingerprintDisallowedByStrongAuth() {
return !(mLockPatternUtils.isFingerprintAllowedForUser(mEffectiveUserId)
&& KeyStore.getInstance().state(mUserId) == KeyStore.State.UNLOCKED);
}
@Override
public void onResume() {
super.onResume();
if (mAllowFpAuthentication) {
mFingerprintHelper.startListening();
}
if (isProfileChallenge()) {
updateErrorMessage(mLockPatternUtils.getCurrentFailedPasswordAttempts(
mEffectiveUserId));
}
}
protected void setAccessibilityTitle(CharSequence supplementalText) {
Intent intent = getActivity().getIntent();
if (intent != null) {
CharSequence titleText = intent.getCharSequenceExtra(
ConfirmDeviceCredentialBaseFragment.TITLE_TEXT);
if (titleText == null || supplementalText == null) {
return;
}
String accessibilityTitle =
new StringBuilder(titleText).append(",").append(supplementalText).toString();
getActivity().setTitle(Utils.createAccessibleSequence(titleText, accessibilityTitle));
}
}
@Override
public void onPause() {
super.onPause();
if (mAllowFpAuthentication) {
mFingerprintHelper.stopListening();
}
}
@Override
public void onAuthenticated() {
// Check whether we are still active.
if (getActivity() != null && getActivity().isResumed()) {
TrustManager trustManager =
(TrustManager) getActivity().getSystemService(Context.TRUST_SERVICE);
trustManager.setDeviceLockedForUser(mEffectiveUserId, false);
authenticationSucceeded();
authenticationSucceeded();
checkForPendingIntent();
}
}
protected abstract void authenticationSucceeded();
@Override
public void onFingerprintIconVisibilityChanged(boolean visible) {
}
public void prepareEnterAnimation() {
}
public void startEnterAnimation() {
}
protected void checkForPendingIntent() {
int taskId = getActivity().getIntent().getIntExtra(Intent.EXTRA_TASK_ID, -1);
if (taskId != -1) {
try {
IActivityManager activityManager = ActivityManagerNative.getDefault();
final ActivityOptions options = ActivityOptions.makeBasic();
options.setLaunchStackId(ActivityManager.StackId.INVALID_STACK_ID);
activityManager.startActivityFromRecents(taskId, options.toBundle());
return;
} catch (RemoteException e) {
// Do nothing.
}
}
IntentSender intentSender = getActivity().getIntent()
.getParcelableExtra(Intent.EXTRA_INTENT);
if (intentSender != null) {
try {
getActivity().startIntentSenderForResult(intentSender, -1, null, 0, 0, 0);
} catch (IntentSender.SendIntentException e) {
/* ignore */
}
}
}
private void setWorkChallengeBackground(View baseView, int userId) {
View mainContent = getActivity().findViewById(com.android.settings.R.id.main_content);
if (mainContent != null) {
// Remove the main content padding so that the background image is full screen.
mainContent.setPadding(0, 0, 0, 0);
}
DevicePolicyManager dpm = (DevicePolicyManager) getActivity().getSystemService(
Context.DEVICE_POLICY_SERVICE);
baseView.setBackground(new ColorDrawable(dpm.getOrganizationColorForUser(userId)));
ImageView imageView = (ImageView) baseView.findViewById(R.id.background_image);
if (imageView != null) {
Drawable image = getResources().getDrawable(R.drawable.work_challenge_background);
image.setColorFilter(
getResources().getColor(R.color.confirm_device_credential_transparent_black),
PorterDuff.Mode.DARKEN);
imageView.setImageDrawable(image);
Point screenSize = new Point();
getActivity().getWindowManager().getDefaultDisplay().getSize(screenSize);
imageView.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
screenSize.y));
}
}
protected boolean isProfileChallenge() {
return Utils.isManagedProfile(UserManager.get(getContext()), mEffectiveUserId);
}
protected void reportSuccessfullAttempt() {
if (isProfileChallenge()) {
mLockPatternUtils.reportSuccessfulPasswordAttempt(mEffectiveUserId);
// Keyguard is responsible to disable StrongAuth for primary user. Disable StrongAuth
// for work challenge only here.
mLockPatternUtils.userPresent(mEffectiveUserId);
}
}
protected void reportFailedAttempt() {
if (isProfileChallenge()) {
// + 1 for this attempt.
updateErrorMessage(
mLockPatternUtils.getCurrentFailedPasswordAttempts(mEffectiveUserId) + 1);
mLockPatternUtils.reportFailedPasswordAttempt(mEffectiveUserId);
}
}
protected void updateErrorMessage(int numAttempts) {
final int maxAttempts =
mLockPatternUtils.getMaximumFailedPasswordsForWipe(mEffectiveUserId);
if (maxAttempts > 0 && numAttempts > 0) {
int remainingAttempts = maxAttempts - numAttempts;
if (remainingAttempts == 1) {
// Last try
final String title = getActivity().getString(
R.string.lock_profile_wipe_warning_title);
final String message = getActivity().getString(getLastTryErrorMessage());
showDialog(title, message, android.R.string.ok, false /* dismiss */);
} else if (remainingAttempts <= 0) {
// Profile is wiped
final String message = getActivity().getString(R.string.lock_profile_wipe_content);
showDialog(null, message, R.string.lock_profile_wipe_dismiss, true /* dismiss */);
}
if (mErrorTextView != null) {
final String message = getActivity().getString(R.string.lock_profile_wipe_attempts,
numAttempts, maxAttempts);
showError(message, 0);
}
}
}
protected abstract int getLastTryErrorMessage();
private final Runnable mResetErrorRunnable = new Runnable() {
@Override
public void run() {
mErrorTextView.setText("");
}
};
protected void showError(CharSequence msg, long timeout) {
mErrorTextView.setText(msg);
onShowError();
mHandler.removeCallbacks(mResetErrorRunnable);
if (timeout != 0) {
mHandler.postDelayed(mResetErrorRunnable, timeout);
}
}
protected abstract void onShowError();
protected void showError(int msg, long timeout) {
showError(getText(msg), timeout);
}
private void showDialog(String title, String message, int buttonString, final boolean dismiss) {
final AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(message)
.setPositiveButton(buttonString, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (dismiss) {
getActivity().finish();
}
}
})
.create();
dialog.show();
}
}
| lgpl-3.0 |
johnniegf/chessbot | src/de/htwsaar/chessbot/Engine.java | 6411 | package de.htwsaar.chessbot;
import de.htwsaar.chessbot.core.Game;
import de.htwsaar.chessbot.config.Config;
import de.htwsaar.chessbot.search.eval.EvaluationFunction;
import de.htwsaar.chessbot.search.eval.Evaluator;
import de.htwsaar.chessbot.uci.UCI;
import de.htwsaar.chessbot.uci.UCISender;
import de.htwsaar.chessbot.uci.Logger;
import de.htwsaar.chessbot.core.Board;
import de.htwsaar.chessbot.search.MoveSearcher;
import de.htwsaar.chessbot.search.NegaMaxSearcher;
import de.htwsaar.chessbot.search.PrincipalVariationSearcher;
import de.htwsaar.chessbot.search.SearchConfiguration;
import de.htwsaar.chessbot.search.SearchWorker;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
/**
*
* @author David Holzapfel
* @author Dominik Becker
*
*/
public class Engine {
private static final EvaluationFunction DEFAULT_EVALUATOR = new Evaluator();
private static final String OPT_SEARCH = "SearchAlgorithm";
private static final String OPT_SEARCH_VAL_PVS = "PrincipalVariation";
private static final String OPT_SEARCH_VAL_NEGAMAX = "NegaMax";
private static final String[] OPT_SEARCH_VALUES = new String[] {
OPT_SEARCH_VAL_NEGAMAX, OPT_SEARCH_VAL_PVS
};
static {
Config.getInstance().addComboOption(
OPT_SEARCH, OPT_SEARCH_VAL_PVS, Arrays.asList(OPT_SEARCH_VALUES)
);
}
private Game mGame;
private SearchWorker mSearchThread;
private final UCI mUCI;
private MoveSearcher createSearcher(EvaluationFunction eval) {
String searchType = Config.getInstance().getOption(OPT_SEARCH).getValue().toString().trim();
switch (searchType) {
case OPT_SEARCH_VAL_NEGAMAX:
return new NegaMaxSearcher(eval);
case OPT_SEARCH_VAL_PVS:
return new PrincipalVariationSearcher(eval);
default:
throw new IllegalStateException();
}
}
public Engine() {
//Initialize Engine
//Initialize Game
mGame = new Game();
//Initialize Config
Config.getInstance();
//Initialize UCISender
// UCISender.getInstance().sendDebug("Initialized UCISender");
//Initialize move searcher
mSearchThread = new SearchWorker(
createSearcher(DEFAULT_EVALUATOR)
);
//Initialize UCI-Protocoll
mUCI = new UCI(this);
mUCI.initialize();
}
public void start() {
mSearchThread.start();
mUCI.start();
}
//======================================
//= uci
//======================================
public void uci() {
UCISender.getInstance().sendToGUI("id name chessbot");
UCISender.getInstance().sendToGUI("id author grpKretschmer");
UCISender.getInstance().sendToGUI("uciok");
}
//======================================
//= isready
//======================================
public void isready() {
while (isSearching()) {
// busy wait
}
UCISender.getInstance().sendToGUI("readyok");
}
public MoveSearcher getSearcher() {
return mSearchThread.getSearcher();
}
//======================================
//= ucinewgame
//======================================
/*
* erstellt ein neues Spiel.
*/
public void newGame() {
stop();
mGame = new Game();
mSearchThread.setSearcher( createSearcher(DEFAULT_EVALUATOR) );
}
//======================================
//= position
//======================================
/**
* setzt das Spiel auf die Startstellung
* fuehrt Zuege aus falls vorhanden.
*/
public void resetBoard(final List<String> moves) {
mGame = new Game();
executeMoves(moves);
// mSearchThread.getSearcher().setBoard(mGame.getCurrentBoard());
}
public Game getGame() {
return mGame;
}
/*
* erzeugt eine Stellung auf Grund des fens
* fuehrt die uebergegebenen Zuege aus falls vorhanden.
*/
public void setBoard(final String fen, final List<String> moves) {
mGame = new Game(fen);
executeMoves(moves);
// mSearchThread.getSearcher().setBoard(mGame.getCurrentBoard());
}
public Board getBoard() {
return mGame.getCurrentBoard();
}
/**
* fuehrt die uebergebenen Zuege aus.
*
* @param moves
*/
public void executeMoves(final List<String> moves) {
if (moves == null)
return;
for (String moveString : moves) {
mGame.doMove(moveString);
}
}
//========================================
//= go
//========================================
public void search(final SearchConfiguration config) {
if (isSearching())
stop();
// stop();
// while (!mSearchThread.isSearcherDone()) {
// // do a busy wait...
// }
getSearcher().setGame(mGame);
getSearcher().getConfiguration().set(config);
mSearchThread.startSearching();
}
public void ponderhit() {
if (mSearchThread.getSearcher().getConfiguration().isPondering()) {
mSearchThread.getSearcher().getConfiguration().setPonder(false);
mSearchThread.getSearcher().getConfiguration().prepareForSearch();
}
}
//========================================
//= stop
//========================================
public void stop() {
mSearchThread.stopSearching();
// while (isSearching()) {
// //busy wait
// }
}
public boolean isSearching() {
return mSearchThread.isSearching() || !mSearchThread.isSearcherDone();
}
public boolean isReady() {
return !isSearching();
}
//========================================
//= quit
//========================================
/**
* beendet das Programm
*/
public void quit() {
mSearchThread.quit();
Logger.getInstance().close();
System.exit(0);
}
/*
* main-Methode der Engine.
*/
public static void main(String[] args) {
//UCIManager anlegen
Thread.currentThread().setName("chessbot-main");
Engine chessbot = new Engine();
chessbot.start();
}
}
| lgpl-3.0 |
jtraviesor/semafor-parser | semafor-deps/src/main/java/edu/cmu/cs/lti/ark/util/ds/map/AbstractCounter.java | 1208 | /*******************************************************************************
* Copyright (c) 2011 Dipanjan Das Language Technologies Institute, Carnegie Mellon University, All Rights Reserved.
*
* AbstractCounter.java is part of SEMAFOR 2.0.
*
* SEMAFOR 2.0 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* SEMAFOR 2.0 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 SEMAFOR 2.0. If not, see
* <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.cmu.cs.lti.ark.util.ds.map;
import java.util.Map;
public abstract class AbstractCounter<K, V extends Number> implements Map<K, V> {
//public abstract V sumOfProducts(AbstractCounter<? extends Number,? extends Number> that);
}
| lgpl-3.0 |
XzeroAir/Trinkets-1.12.2 | main/java/xzeroair/trinkets/client/events/RenderHandler.java | 9036 | package xzeroair.trinkets.client.events;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.RenderBlockOverlayEvent;
import net.minecraftforge.client.event.RenderBlockOverlayEvent.OverlayType;
import net.minecraftforge.client.event.RenderLivingEvent;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.fml.common.Loader;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import xzeroair.trinkets.api.TrinketHelper;
import xzeroair.trinkets.capabilities.Capabilities;
import xzeroair.trinkets.capabilities.race.RaceProperties;
import xzeroair.trinkets.init.ModItems;
import xzeroair.trinkets.items.effects.EffectsDragonsEye;
import xzeroair.trinkets.util.TrinketsConfig;
public class RenderHandler {
// Minecraft mc = Minecraft.getMinecraft();
// @SubscribeEvent
// public void onRenderTick(RenderTickEvent event) {
// if ((this.mc.player != null) && (this.mc.player.world != null)) {
// }
// }
// @SubscribeEvent
// public void renderFogColor(EntityViewRenderEvent.FogColors event) {
//
// }
@SubscribeEvent
public void renderFog(EntityViewRenderEvent.FogDensity event) {
if (event.getEntity() instanceof EntityPlayer) {
if (TrinketHelper.AccessoryCheck((EntityPlayer) event.getEntity(), ModItems.trinkets.TrinketDragonsEye)) {
if (event.getEntity().isInLava() && (event.getState().getMaterial() == Material.LAVA)) {
if ((event.getDensity() >= 0.1f) && !event.isCanceled()) {
event.setCanceled(true);
event.setDensity(0.1f);
}
}
}
if (TrinketHelper.AccessoryCheck((EntityPlayer) event.getEntity(), ModItems.trinkets.TrinketSea)) {
if (event.getEntity().isInWater() && (event.getState().getMaterial() == Material.WATER)) {
if ((event.getDensity() >= 0.1f) && !event.isCanceled()) {
event.setCanceled(true);
event.setDensity(0.02f);
}
}
}
}
}
// @SubscribeEvent
// public void renderGameOverlay(RenderGameOverlayEvent event) {
// }
@SubscribeEvent
public void renderBlockOverlay(RenderBlockOverlayEvent event) {
if (event.getOverlayType() == OverlayType.FIRE) {
if (TrinketHelper.AccessoryCheck(event.getPlayer(), ModItems.trinkets.TrinketDragonsEye)) {
event.setCanceled(true);
}
}
}
@SubscribeEvent
public void renderPlayerPre(RenderPlayerEvent.Pre event) {
final EntityPlayer player = event.getEntityPlayer();
RaceProperties cap = Capabilities.getEntityRace(player);
if (cap != null) {
final int size = cap.getSize();
final float scale = size * 0.01F;
if ((cap.getTrans() == true)) {
GlStateManager.pushMatrix();
if ((Loader.isModLoaded("artemislib")) && TrinketsConfig.compat.artemislib) {
float W = 1F;
if (cap.getSize() < 30) {
W = 0.5F;
}
if (cap.getSize() != cap.getTarget()) {
GlStateManager.scale(scale * W, scale, scale * W);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
} else {
if (cap.getSize() == 25) {
GlStateManager.scale(W, 1, W);
}
}
if (player.isSneaking()) {
GlStateManager.translate(0F, 0.125F, 0F);
}
if (player.isRiding()) {
if (TrinketHelper.AccessoryCheck(player, ModItems.trinkets.TrinketFairyRing) || cap.getFood().contentEquals("fairy_dew")) {
GlStateManager.translate(0F, 0.45F, 0F);
}
if (TrinketHelper.AccessoryCheck(player, ModItems.trinkets.TrinketDwarfRing) || cap.getFood().contentEquals("dwarf_stout")) {
GlStateManager.translate(0, 0.125F, 0);
}
}
} else {
GlStateManager.scale(scale, scale, scale);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
if (player.isRiding()) {
if (TrinketHelper.AccessoryCheck(player, ModItems.trinkets.TrinketFairyRing) || cap.getFood().contentEquals("fairy_dew")) {
GlStateManager.translate(0F, 1.8F, 0F);
}
if (TrinketHelper.AccessoryCheck(player, ModItems.trinkets.TrinketDwarfRing) || cap.getFood().contentEquals("dwarf_stout")) {
GlStateManager.translate(0, 0.125F, 0);
}
}
}
} else {
if (cap.getSize() != cap.getTarget()) {
GlStateManager.pushMatrix();
GlStateManager.scale(scale, scale, scale);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
}
}
}
}
@SubscribeEvent
public void renderPlayerPost(RenderPlayerEvent.Post event) {
final EntityPlayer player = event.getEntityPlayer();
RaceProperties cap = Capabilities.getEntityRace(player);
if (cap != null) {
if (cap.getTrans() == true) {
GlStateManager.popMatrix();
} else {
if (cap.getSize() != cap.getTarget()) {
GlStateManager.popMatrix();
}
}
}
}
@SubscribeEvent
public void onRenderSpecialPre(RenderLivingEvent.Specials.Pre event) {
if (event.getEntity() instanceof EntityPlayer) {
final EntityPlayer player = (EntityPlayer) event.getEntity();
RaceProperties cap = Capabilities.getEntityRace(player);
if (cap != null) {
if (TrinketHelper.AccessoryCheck(player, TrinketHelper.SizeTrinkets) || !cap.getFood().contentEquals("none")) {
GlStateManager.pushMatrix();
final float scale = (float) cap.getTarget() / 100;
GlStateManager.translate(0, 0.3 / scale, 0);
}
}
}
}
@SubscribeEvent
public void onRenderSpecialPost(RenderLivingEvent.Specials.Post event) {
if (event.getEntity() instanceof EntityPlayer) {
final EntityPlayer player = (EntityPlayer) event.getEntity();
RaceProperties cap = Capabilities.getEntityRace(player);
if (cap != null) {
if (TrinketHelper.AccessoryCheck(player, TrinketHelper.SizeTrinkets) || !cap.getFood().contentEquals("none")) {
GlStateManager.popMatrix();
}
}
}
}
@SubscribeEvent
public void onRenderLivingPre(RenderLivingEvent.Pre event) {
if ((event.getEntity() instanceof EntityLivingBase) && !(event.getEntity() instanceof EntityPlayer)) {
final EntityLivingBase entity = event.getEntity();
RaceProperties cap = Capabilities.getEntityRace(entity);
if (cap != null) {
final int size = cap.getSize();
final float scale = size * 0.01F;
if ((cap.getTrans() == true)) {
GlStateManager.pushMatrix();
if ((Loader.isModLoaded("artemislib")) && TrinketsConfig.compat.artemislib) {
float W = 1F;
if (cap.getSize() < 30) {
W = 0.5F;
}
if (cap.getSize() != cap.getTarget()) {
GlStateManager.scale(scale * W, scale, scale * W);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
} else {
if (cap.getSize() == 25) {
GlStateManager.scale(W, 1, W);
}
}
} else {
GlStateManager.scale(scale, scale, scale);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
}
} else {
if (cap.getSize() != cap.getTarget()) {
GlStateManager.pushMatrix();
GlStateManager.scale(scale, scale, scale);
GlStateManager.translate((event.getX() / scale) - event.getX(), (event.getY() / scale) - event.getY(), (event.getZ() / scale) - event.getZ());
}
}
}
}
}
@SubscribeEvent
public void onRenderLivingPost(RenderLivingEvent.Post event) {
if ((event.getEntity() instanceof EntityLivingBase) && !(event.getEntity() instanceof EntityPlayer)) {
final EntityLivingBase entity = event.getEntity();
RaceProperties cap = Capabilities.getEntityRace(entity);
if (cap != null) {
if (cap.getTrans() == true) {
GlStateManager.popMatrix();
} else {
if (cap.getSize() != cap.getTarget()) {
GlStateManager.popMatrix();
}
}
}
}
}
@SubscribeEvent
public void onWorldRenderLast(RenderWorldLastEvent event) {
if (Minecraft.getMinecraft().player != null) {
final EntityPlayer player = Minecraft.getMinecraft().player;
if (TrinketHelper.AccessoryCheck(player, ModItems.trinkets.TrinketDragonsEye)) {
final ItemStack stack = TrinketHelper.getAccessory(player, ModItems.trinkets.TrinketDragonsEye);
EffectsDragonsEye.playerTicks(stack, player);
}
}
}
}
| lgpl-3.0 |
Spirakos/CloudsimTest | examples/org/cloudbus/cloudsim/examples/TestD.java | 9700 | /*
* Title: CloudSim Toolkit
* Description: CloudSim (Cloud Simulation) Toolkit for Modeling and Simulation
* of Clouds
* Licence: GPL - http://www.gnu.org/copyleft/gpl.html
*
* Copyright (c) 2009, The University of Melbourne, Australia
*/
package org.cloudbus.cloudsim.examples;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletSchedulerTimeShared;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterBroker;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Pe;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.UtilizationModel;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicySimple;
import org.cloudbus.cloudsim.VmSchedulerTimeShared;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.provisioners.BwProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.PeProvisionerSimple;
import org.cloudbus.cloudsim.provisioners.RamProvisionerSimple;
/**
* A simple example showing how to create
* a datacenter with one host and run two
* cloudlets on it. The cloudlets run in
* VMs with the same MIPS requirements.
* The cloudlets will take the same time to
* complete the execution.
*/
public class TestD {
/** The cloudlet list. */
private static List<Cloudlet> cloudletList;
/** The vmlist. */
private static List<Vm> vmlist;
/**
* Creates main() to run this example
*/
public static void main(String[] args) {
Log.printLine("Starting CloudSimExample2...");
try {
// First step: Initialize the CloudSim package. It should be called
// before creating any entities.
int num_user = 1; // number of cloud users
Calendar calendar = Calendar.getInstance();
boolean trace_flag = false; // mean trace events
// Initialize the CloudSim library
CloudSim.init(num_user, calendar, trace_flag);
// Second step: Create Datacenters
//Datacenters are the resource providers in CloudSim. We need at list one of them to run a CloudSim simulation
@SuppressWarnings("unused")
Datacenter datacenter0 = createDatacenter("Datacenter_0");
//Third step: Create Broker
MyDB broker = createBroker();
int brokerId = broker.getId();
//Fourth step: Create one virtual machine
vmlist = new ArrayList<Vm>();
//VM description
int vmid = 0;
int mips = 250;
long size = 10000; //image size (MB)
int ram = 512; //vm memory (MB)
long bw = 1000;
int pesNumber = 1; //number of cpus
String vmm = "Xen"; //VMM name
//create two VMs
Vm vm1 = new Vm(vmid, brokerId, mips, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
vmid++;
Vm vm2 = new Vm(vmid, brokerId, mips * 2, pesNumber, ram, bw, size, vmm, new CloudletSchedulerTimeShared());
//add the VMs to the vmList
vmlist.add(vm1);
vmlist.add(vm2);
//submit vm list to the broker
broker.submitVmList(vmlist);
//Fifth step: Create two Cloudlets
cloudletList = new ArrayList<Cloudlet>();
//Cloudlet properties
int id = 0;
pesNumber=1;
long length = 250000; //ALLAZEI TON XRONO STO OUTPOUT
long fileSize = 300;
long outputSize = 300;
UtilizationModel utilizationModel = new UtilizationModelFull();
Cloudlet cloudlet1 = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet1.setUserId(brokerId);
id++;
Cloudlet cloudlet2 = new Cloudlet(id, length, pesNumber, fileSize, outputSize, utilizationModel, utilizationModel, utilizationModel);
cloudlet2.setUserId(brokerId);
//add the cloudlets to the list
cloudletList.add(cloudlet1);
cloudletList.add(cloudlet2);
//submit cloudlet list to the broker
broker.submitCloudletList(cloudletList);
//bind the cloudlets to the vms. This way, the broker
// will submit the bound cloudlets only to the specific VM
broker.bindCloudletToVm(cloudlet1.getCloudletId(),vm1.getId());
broker.bindCloudletToVm(cloudlet2.getCloudletId(),vm2.getId());
// Sixth step: Starts the simulation
CloudSim.startSimulation();
// Final step: Print results when simulation is over
List<Cloudlet> newList = broker.getCloudletReceivedList();
CloudSim.stopSimulation();
printCloudletList(newList);
Log.printLine("CloudSimExample2 finished!");
}
catch (Exception e) {
e.printStackTrace();
Log.printLine("The simulation has been terminated due to an unexpected error");
}
}
private static Datacenter createDatacenter(String name){
// Here are the steps needed to create a PowerDatacenter:
// 1. We need to create a list to store
// our machine
List<Host> hostList = new ArrayList<Host>();
// 2. A Machine contains one or more PEs or CPUs/Cores.
// In this example, it will have only one core.
List<Pe> peList = new ArrayList<Pe>();
int mips = 1000;
// 3. Create PEs and add these into a list.
peList.add(new Pe(0, new PeProvisionerSimple(mips))); // need to store Pe id and MIPS Rating
//4. Create Host with its id and list of PEs and add them to the list of machines
int hostId=0;
int ram = 2048; //host memory (MB)
long storage = 1000000; //host storage
int bw = 10000;
hostList.add(
new Host(
hostId,
new RamProvisionerSimple(ram),
new BwProvisionerSimple(bw),
storage,
peList,
new VmSchedulerTimeShared(peList)
)
); // This is our machine
// 5. Create a DatacenterCharacteristics object that stores the
// properties of a data center: architecture, OS, list of
// Machines, allocation policy: time- or space-shared, time zone
// and its price (G$/Pe time unit).
String arch = "x86"; // system architecture
String os = "Linux"; // operating system
String vmm = "Xen";
double time_zone = 10.0; // time zone this resource located
double cost = 3.0; // the cost of using processing in this resource
double costPerMem = 0.05; // the cost of using memory in this resource
double costPerStorage = 0.001; // the cost of using storage in this resource
double costPerBw = 0.0; // the cost of using bw in this resource
LinkedList<Storage> storageList = new LinkedList<Storage>(); //we are not adding SAN devices by now
DatacenterCharacteristics characteristics = new DatacenterCharacteristics(
arch, os, vmm, hostList, time_zone, cost, costPerMem, costPerStorage, costPerBw);
// 6. Finally, we need to create a PowerDatacenter object.
Datacenter datacenter = null;
try {
datacenter = new Datacenter(name, characteristics, new VmAllocationPolicySimple(hostList), storageList, 0);
} catch (Exception e) {
e.printStackTrace();
}
return datacenter;
}
//We strongly encourage users to develop their own broker policies, to submit vms and cloudlets according
//to the specific rules of the simulated scenario
private static MyDB createBroker() {
MyDB broker = null;
try {
broker = new MyDB("Broker");
} catch (Exception e) {
e.printStackTrace();
return null;
}
return broker;
}
/**
* Prints the Cloudlet objects
* @param list list of Cloudlets
*/
private static void printCloudletList(List<Cloudlet> list) {
int size = list.size();
Cloudlet cloudlet;
String indent = " ";
Log.printLine();
Log.printLine("========== OUTPUT ==========");
Log.printLine("Cloudlet ID" + indent + "STATUS" + indent +
"Data center ID" + indent + "VM ID" + indent + "Time" + indent + "Start Time" + indent + "Finish Time");
DecimalFormat dft = new DecimalFormat("###.##");
for (int i = 0; i < size; i++) {
cloudlet = list.get(i);
Log.print(indent + cloudlet.getCloudletId() + indent + indent);
if (cloudlet.getCloudletStatus() == Cloudlet.SUCCESS){
Log.print("SUCCESS");
Log.printLine( indent + indent + cloudlet.getResourceId() + indent + indent + indent + cloudlet.getVmId() +
indent + indent + dft.format(cloudlet.getActualCPUTime()) + indent + indent + dft.format(cloudlet.getExecStartTime())+
indent + indent + dft.format(cloudlet.getFinishTime()));
}
}
}
}
| lgpl-3.0 |
CSTARS/gwt-esri | src/main/java/edu/ucdavis/cstars/client/tasks/RelationshipQuery.java | 3927 | package edu.ucdavis.cstars.client.tasks;
import com.google.gwt.core.client.JavaScriptObject;
import edu.ucdavis.cstars.client.SpatialReference;
import edu.ucdavis.cstars.client.Util;
/**
* Define query parameters for the feature layer's queryRelateFeatures method.
*
* @author Justin Merz
*/
public class RelationshipQuery extends JavaScriptObject {
protected RelationshipQuery() {}
/**
* Create a new RelationshipQuery object
*
* @return RelationshipQuery
*/
public static native RelationshipQuery create() /*-{
return new $wnd.esri.tasks.RelationshipQuery();
}-*/;
/**
* Set the definition expression for this query
*
* @param expression - The definition expression to be applied to the related table
* or layer. Only records that fit the definition expression and are in the list of ObjectIds
* will be returned.
*/
public final native void setDefinitionExpression(String expression) /*-{
this.definitionExpression = expression;
}-*/;
/**
* Set the max allowable offset for this query
*
* @param maxOffset - The maximum allowable offset used for generalizing geometries
* returned by the query operation. The offset is in the units of the spatialReference. If
* a spatialReference is not defined the spatial reference of the map is used.
*/
public final native void setMaxAllowableOffset(int maxOffset) /*-{
this.maxAllowableOffset = maxOffset;
}-*/;
/**
* Set the object ids for this query
*
* @param ids - Int array of objectIds for the features in the layer/table that you want to query.
*/
public final void setObjectIds(int[] ids) {
_setObjectIds(Util.intArrayToJSO(ids));
}
private final native void _setObjectIds(JavaScriptObject ids) /*-{
this.objectIds = ids;
}-*/;
/**
* Set the outfields for this query
*
* @param outfields - fields to include in the FeatureSet. Fields must exist in the map layer.
* You must list the actual field names rather than the alias names. Returned fields are also the actual
* field names. However, you are able to use the alias names when you display the results. You can set
* field alias names in the map document.
* When you specify the output fields, you should limit the fields to only those you expect to use in
* the query or the results. The fewer fields you include, the faster the response will be.
* Each query must have access to the Shape and Objectid fields for a layer, but your list of fields does
* not need to include these two fields.
*/
public final void setOutfields(String[] outfields) {
_setOutfields(Util.stringArrayToJSO(outfields));
}
private final native void _setOutfields(JavaScriptObject outfields) /*-{
this.outfields = outfields
}-*/;
/**
* Set the spatial reference for the returned geometry
*
* @param outSpatialReference - The spatial reference for the returned geometry. If not specified, the geometry is returned in the
* spatial reference of the map.
*/
public final native void setOutSpatialReference(SpatialReference outSpatialReference) /*-{
this.outSpatialReference = outSpatialReference;
}-*/;
/**
* Set the relationship id for this query
*
* @param relationshipId - The ID of the relationship to test. The ids for the relationships the table or layer particpates in are
* listed in the the ArcGIS Services directory.
*
*/
public final native void setRelationshipId(int relationshipId) /*-{
this.relationshipId = relationshipId;
}-*/;
/**
* Should the returned FeatureSet include geometry.
*
* @param returnGeometry - If "true", each feature in the FeatureSet includes the geometry. Set to "false" (default) if you do
* not plan to include highlighted features on a map since the geometry makes up a significant portion of the response.
*/
public final native void returnGeometry(boolean returnGeometry) /*-{
this.returnGeometry = returnGeometry;
}-*/;
}
| lgpl-3.0 |
lbndev/sonarqube | sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionTest.java | 18895 | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.api.server.rule;
import java.net.URL;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.server.debt.DebtRemediationFunction;
import org.sonar.api.utils.log.LogTester;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class RulesDefinitionTest {
RulesDefinition.Context context = new RulesDefinition.Context();
@Rule
public LogTester logTester = new LogTester();
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void define_repositories() {
assertThat(context.repositories()).isEmpty();
context.createRepository("findbugs", "java").setName("Findbugs").done();
context.createRepository("checkstyle", "java").done();
assertThat(context.repositories()).hasSize(2);
RulesDefinition.Repository findbugs = context.repository("findbugs");
assertThat(findbugs).isNotNull();
assertThat(findbugs.key()).isEqualTo("findbugs");
assertThat(findbugs.language()).isEqualTo("java");
assertThat(findbugs.name()).isEqualTo("Findbugs");
assertThat(findbugs.rules()).isEmpty();
RulesDefinition.Repository checkstyle = context.repository("checkstyle");
assertThat(checkstyle).isNotNull();
assertThat(checkstyle.key()).isEqualTo("checkstyle");
assertThat(checkstyle.language()).isEqualTo("java");
// default name is key
assertThat(checkstyle.name()).isEqualTo("checkstyle");
assertThat(checkstyle.rules()).isEmpty();
assertThat(context.repository("unknown")).isNull();
// test equals() and hashCode()
assertThat(findbugs).isEqualTo(findbugs).isNotEqualTo(checkstyle).isNotEqualTo("findbugs").isNotEqualTo(null);
assertThat(findbugs.hashCode()).isEqualTo(findbugs.hashCode());
}
@Test
public void define_rules() {
RulesDefinition.NewRepository newRepo = context.createRepository("findbugs", "java");
newRepo.createRule("NPE")
.setName("Detect NPE")
.setHtmlDescription("Detect <code>java.lang.NullPointerException</code>")
.setSeverity(Severity.BLOCKER)
.setInternalKey("/something")
.setStatus(RuleStatus.BETA)
.setTags("one", "two")
.addTags("two", "three", "four");
newRepo.createRule("ABC").setName("ABC").setMarkdownDescription("ABC");
newRepo.done();
RulesDefinition.Repository repo = context.repository("findbugs");
assertThat(repo.rules()).hasSize(2);
RulesDefinition.Rule rule = repo.rule("NPE");
assertThat(rule.key()).isEqualTo("NPE");
assertThat(rule.name()).isEqualTo("Detect NPE");
assertThat(rule.severity()).isEqualTo(Severity.BLOCKER);
assertThat(rule.htmlDescription()).isEqualTo("Detect <code>java.lang.NullPointerException</code>");
assertThat(rule.markdownDescription()).isNull();
assertThat(rule.tags()).containsOnly("one", "two", "three", "four");
assertThat(rule.params()).isEmpty();
assertThat(rule.internalKey()).isEqualTo("/something");
assertThat(rule.template()).isFalse();
assertThat(rule.status()).isEqualTo(RuleStatus.BETA);
assertThat(rule.toString()).isEqualTo("[repository=findbugs, key=NPE]");
assertThat(rule.repository()).isSameAs(repo);
RulesDefinition.Rule otherRule = repo.rule("ABC");
assertThat(otherRule.htmlDescription()).isNull();
assertThat(otherRule.markdownDescription()).isEqualTo("ABC");
// test equals() and hashCode()
assertThat(rule).isEqualTo(rule).isNotEqualTo(otherRule).isNotEqualTo("NPE").isNotEqualTo(null);
assertThat(rule.hashCode()).isEqualTo(rule.hashCode());
}
@Test
public void define_rules_with_remediation_function() {
RulesDefinition.NewRepository newRepo = context.createRepository("common-java", "java");
RulesDefinition.NewRule newRule = newRepo.createRule("InsufficientBranchCoverage")
.setName("Insufficient condition coverage")
.setHtmlDescription("Insufficient condition coverage by unit tests")
.setSeverity(Severity.MAJOR)
.setGapDescription("Effort to test one uncovered branch");
newRule.setDebtRemediationFunction(newRule.debtRemediationFunctions().linearWithOffset("1h", "10min"));
newRepo.done();
RulesDefinition.Repository repo = context.repository("common-java");
assertThat(repo.rules()).hasSize(1);
RulesDefinition.Rule rule = repo.rule("InsufficientBranchCoverage");
assertThat(rule.debtRemediationFunction().type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
assertThat(rule.debtRemediationFunction().gapMultiplier()).isEqualTo("1h");
assertThat(rule.debtRemediationFunction().baseEffort()).isEqualTo("10min");
assertThat(rule.gapDescription()).isEqualTo("Effort to test one uncovered branch");
}
@Test
public void define_rule_with_default_fields() {
RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java");
newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE");
newFindbugs.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.key()).isEqualTo("NPE");
assertThat(rule.severity()).isEqualTo(Severity.MAJOR);
assertThat(rule.params()).isEmpty();
assertThat(rule.internalKey()).isNull();
assertThat(rule.status()).isEqualTo(RuleStatus.defaultStatus());
assertThat(rule.tags()).isEmpty();
assertThat(rule.debtRemediationFunction()).isNull();
}
@Test
public void define_rule_parameters() {
RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java");
RulesDefinition.NewRule newNpe = newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE");
newNpe.createParam("level").setDefaultValue("LOW").setName("Level").setDescription("The level").setType(RuleParamType.INTEGER);
newNpe.createParam("effort");
newFindbugs.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.params()).hasSize(2);
RulesDefinition.Param level = rule.param("level");
assertThat(level.key()).isEqualTo("level");
assertThat(level.name()).isEqualTo("Level");
assertThat(level.description()).isEqualTo("The level");
assertThat(level.defaultValue()).isEqualTo("LOW");
assertThat(level.type()).isEqualTo(RuleParamType.INTEGER);
RulesDefinition.Param effort = rule.param("effort");
assertThat(effort.key()).isEqualTo("effort").isEqualTo(effort.name());
assertThat(effort.description()).isNull();
assertThat(effort.defaultValue()).isNull();
assertThat(effort.type()).isEqualTo(RuleParamType.STRING);
// test equals() and hashCode()
assertThat(level).isEqualTo(level).isNotEqualTo(effort).isNotEqualTo("level").isNotEqualTo(null);
assertThat(level.hashCode()).isEqualTo(level.hashCode());
}
@Test
public void define_rule_parameter_with_empty_default_value() {
RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java");
RulesDefinition.NewRule newNpe = newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE");
newNpe.createParam("level").setDefaultValue("").setName("Level").setDescription("The level").setType(RuleParamType.INTEGER);
newFindbugs.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.params()).hasSize(1);
RulesDefinition.Param level = rule.param("level");
assertThat(level.key()).isEqualTo("level");
assertThat(level.name()).isEqualTo("Level");
assertThat(level.description()).isEqualTo("The level");
// Empty value is converted in null value
assertThat(level.defaultValue()).isNull();
assertThat(level.type()).isEqualTo(RuleParamType.INTEGER);
}
@Test
public void sanitize_rule_name() {
RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java");
newFindbugs.createRule("NPE").setName(" \n NullPointer \n ").setHtmlDescription("NPE");
newFindbugs.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.name()).isEqualTo("NullPointer");
}
@Test
public void add_rules_to_existing_repository() {
RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java").setName("Findbugs");
newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE");
newFindbugs.done();
RulesDefinition.NewRepository newFbContrib = context.createRepository("findbugs", "java");
newFbContrib.createRule("VULNERABILITY").setName("Vulnerability").setMarkdownDescription("Detect vulnerability");
newFbContrib.done();
assertThat(context.repositories()).hasSize(1);
RulesDefinition.Repository findbugs = context.repository("findbugs");
assertThat(findbugs.key()).isEqualTo("findbugs");
assertThat(findbugs.language()).isEqualTo("java");
assertThat(findbugs.name()).isEqualTo("Findbugs");
assertThat(findbugs.rules()).extracting("key").containsOnly("NPE", "VULNERABILITY");
}
/**
* This is temporarily accepted only for the support of the common-rules that are still declared
* by plugins. It could be removed in 7.0
* @since 5.2
*/
@Test
public void allow_to_replace_an_existing_common_rule() {
RulesDefinition.NewRepository newCommonJava1 = context.createRepository("common-java", "java").setName("Common Java");
newCommonJava1.createRule("coverage").setName("Lack of coverage").setHtmlDescription("Coverage must be high");
newCommonJava1.done();
RulesDefinition.NewRepository newCommonJava2 = context.createRepository("common-java", "java");
newCommonJava2.createRule("coverage").setName("Lack of coverage (V2)").setMarkdownDescription("Coverage must be high (V2)");
newCommonJava2.done();
RulesDefinition.Repository commonJava = context.repository("common-java");
assertThat(commonJava.rules()).hasSize(1);
RulesDefinition.Rule rule = commonJava.rule("coverage");
assertThat(rule.name()).isEqualTo("Lack of coverage (V2)");
// replacement but not merge -> keep only the v2 (which has markdown but not html description)
assertThat(rule.markdownDescription()).isEqualTo("Coverage must be high (V2)");
assertThat(rule.htmlDescription()).isNull();
// do not log warning
assertThat(logTester.logs()).isEmpty();
}
@Test
public void cant_set_blank_repository_name() {
context.createRepository("findbugs", "java").setName(null).done();
assertThat(context.repository("findbugs").name()).isEqualTo("findbugs");
}
@Test
public void fail_if_duplicated_rule_keys_in_the_same_repository() {
expectedException.expect(IllegalArgumentException.class);
RulesDefinition.NewRepository findbugs = context.createRepository("findbugs", "java");
findbugs.createRule("NPE");
findbugs.createRule("NPE");
}
@Test
public void fail_if_duplicated_rule_param_keys() {
RulesDefinition.NewRule rule = context.createRepository("findbugs", "java").createRule("NPE");
rule.createParam("level");
try {
rule.createParam("level");
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("The parameter 'level' is declared several times on the rule [repository=findbugs, key=NPE]");
}
}
@Test
public void fail_if_blank_rule_name() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName(null).setHtmlDescription("NPE");
try {
newRepository.done();
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Name of rule [repository=findbugs, key=NPE] is empty");
}
}
@Test
public void fail_if_bad_rule_tag() {
try {
// whitespaces are not allowed in tags
context.createRepository("findbugs", "java").createRule("NPE").setTags("coding style");
fail();
} catch (Exception e) {
assertThat(e).isInstanceOf(IllegalArgumentException.class)
.hasMessage("Tag 'coding style' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'");
}
}
@Test
public void load_rule_html_description_from_file() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setHtmlDescription(getClass().getResource("/org/sonar/api/server/rule/RulesDefinitionTest/sample.html"));
newRepository.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.htmlDescription()).isEqualTo("description of rule loaded from file");
}
@Test
public void load_rule_markdown_description_from_file() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setMarkdownDescription(getClass().getResource("/org/sonar/api/server/rule/RulesDefinitionTest/sample.md"));
newRepository.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.markdownDescription()).isEqualTo("description of rule loaded from file");
}
@Test
public void fail_to_load_html_rule_description_from_file() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setHtmlDescription((URL) null);
try {
newRepository.done();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]");
}
}
@Test
public void fail_to_load_markdown_rule_description_from_file() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setMarkdownDescription((URL) null);
try {
newRepository.done();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]");
}
}
@Test
public void fail_if_no_rule_description() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE");
try {
newRepository.done();
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]");
}
}
@Test
public void fail_if_rule_already_has_html_description() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
try {
newRepository.createRule("NPE").setName("NPE").setHtmlDescription("polop").setMarkdownDescription("palap");
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Rule '[repository=findbugs, key=NPE]' already has an HTML description");
}
}
@Test
public void fail_if_rule_already_has_markdown_description() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
try {
newRepository.createRule("NPE").setName("NPE").setMarkdownDescription("palap").setHtmlDescription("polop");
fail();
} catch (IllegalStateException e) {
assertThat(e).hasMessage("Rule '[repository=findbugs, key=NPE]' already has a Markdown description");
}
}
@Test
public void fail_if_bad_rule_severity() {
try {
context.createRepository("findbugs", "java").createRule("NPE").setSeverity("VERY HIGH");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Severity of rule [repository=findbugs, key=NPE] is not correct: VERY HIGH");
}
}
@Test
public void fail_if_removed_status() {
try {
context.createRepository("findbugs", "java").createRule("NPE").setStatus(RuleStatus.REMOVED);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Status 'REMOVED' is not accepted on rule '[repository=findbugs, key=NPE]'");
}
}
@Test
public void sqale_characteristic_is_deprecated_and_is_ignored() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setHtmlDescription("desc")
.setDebtSubCharacteristic(RulesDefinition.SubCharacteristics.API_ABUSE);
newRepository.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.debtSubCharacteristic()).isNull();
}
@Test
public void type_is_defined() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setHtmlDescription("desc")
.setType(RuleType.VULNERABILITY).setTags("bug", "misra");
newRepository.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
// type VULNERABILITY is kept even if the tag "bug" is present
assertThat(rule.type()).isEqualTo(RuleType.VULNERABILITY);
// tag "bug" is reserved and removed.
assertThat(rule.tags()).containsOnly("misra");
}
@Test
public void guess_type_from_tags_if_type_is_missing() {
RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java");
newRepository.createRule("NPE").setName("NPE").setHtmlDescription("desc").setTags("bug", "misra");
newRepository.done();
RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE");
assertThat(rule.type()).isEqualTo(RuleType.BUG);
// tag "bug" is reserved and removed
assertThat(rule.tags()).containsOnly("misra");
}
}
| lgpl-3.0 |
subes/invesdwin-nowicket | invesdwin-nowicket-parent/invesdwin-nowicket/src/main/java/de/invesdwin/nowicket/page/home/HomeRedirect.java | 463 | package de.invesdwin.nowicket.page.home;
import javax.annotation.concurrent.NotThreadSafe;
import de.invesdwin.nowicket.generated.markup.annotation.GeneratedMarkup;
import de.invesdwin.util.bean.AValueObject;
/**
* This model can be returned in generated button methods to redirect to the HomePage that is defined in
* IWebApplication.getHomePage().
*
*/
@GeneratedMarkup
@NotThreadSafe
public class HomeRedirect extends AValueObject {
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/cmis-tck-ws/source/java/org/alfresco/cmis/test/ws/CmisObjectServiceClient.java | 91173 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.cmis.test.ws;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.alfresco.repo.cmis.ws.AddObjectToFolder;
import org.alfresco.repo.cmis.ws.CheckIn;
import org.alfresco.repo.cmis.ws.CheckInResponse;
import org.alfresco.repo.cmis.ws.CheckOut;
import org.alfresco.repo.cmis.ws.CheckOutResponse;
import org.alfresco.repo.cmis.ws.CmisAccessControlEntryType;
import org.alfresco.repo.cmis.ws.CmisAccessControlListType;
import org.alfresco.repo.cmis.ws.CmisAccessControlPrincipalType;
import org.alfresco.repo.cmis.ws.CmisContentStreamType;
import org.alfresco.repo.cmis.ws.CmisFaultType;
import org.alfresco.repo.cmis.ws.CmisObjectType;
import org.alfresco.repo.cmis.ws.CmisPropertiesType;
import org.alfresco.repo.cmis.ws.CmisPropertyId;
import org.alfresco.repo.cmis.ws.CmisPropertyString;
import org.alfresco.repo.cmis.ws.CmisPropertyStringDefinitionType;
import org.alfresco.repo.cmis.ws.CmisRenditionType;
import org.alfresco.repo.cmis.ws.CmisRepositoryCapabilitiesType;
import org.alfresco.repo.cmis.ws.CmisTypeDefinitionType;
import org.alfresco.repo.cmis.ws.CreateDocument;
import org.alfresco.repo.cmis.ws.CreateDocumentFromSource;
import org.alfresco.repo.cmis.ws.CreateFolder;
import org.alfresco.repo.cmis.ws.DeleteContentStream;
import org.alfresco.repo.cmis.ws.DeleteContentStreamResponse;
import org.alfresco.repo.cmis.ws.DeleteObject;
import org.alfresco.repo.cmis.ws.DeleteTree;
import org.alfresco.repo.cmis.ws.DeleteTreeResponse;
import org.alfresco.repo.cmis.ws.EnumCapabilityACL;
import org.alfresco.repo.cmis.ws.EnumCapabilityRendition;
import org.alfresco.repo.cmis.ws.EnumIncludeRelationships;
import org.alfresco.repo.cmis.ws.EnumServiceException;
import org.alfresco.repo.cmis.ws.EnumUnfileObject;
import org.alfresco.repo.cmis.ws.EnumVersioningState;
import org.alfresco.repo.cmis.ws.GetAllVersions;
import org.alfresco.repo.cmis.ws.GetAllowableActions;
import org.alfresco.repo.cmis.ws.GetAllowableActionsResponse;
import org.alfresco.repo.cmis.ws.GetContentStream;
import org.alfresco.repo.cmis.ws.GetContentStreamResponse;
import org.alfresco.repo.cmis.ws.GetObject;
import org.alfresco.repo.cmis.ws.GetObjectByPath;
import org.alfresco.repo.cmis.ws.GetObjectByPathResponse;
import org.alfresco.repo.cmis.ws.GetObjectResponse;
import org.alfresco.repo.cmis.ws.GetProperties;
import org.alfresco.repo.cmis.ws.GetPropertiesOfLatestVersion;
import org.alfresco.repo.cmis.ws.GetPropertiesOfLatestVersionResponse;
import org.alfresco.repo.cmis.ws.GetPropertiesResponse;
import org.alfresco.repo.cmis.ws.GetRenditions;
import org.alfresco.repo.cmis.ws.MoveObject;
import org.alfresco.repo.cmis.ws.ObjectServicePortBindingStub;
import org.alfresco.repo.cmis.ws.SetContentStream;
import org.alfresco.repo.cmis.ws.UpdateProperties;
import org.alfresco.repo.cmis.ws.VersioningServicePortBindingStub;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
/**
* Client for Object Service
*/
public class CmisObjectServiceClient extends AbstractServiceClient
{
private static Log LOGGER = LogFactory.getLog(CmisObjectServiceClient.class);
private static final String UPDATE_FILE_NAME = "UpdatedFileName.txt";
private static final String TEST_IMAGE_NAME = "TestImage.jpg";
private static final String MIMETYPE_IMAGE_JPEG = "image/jpeg";
private static final String PROPERTIES_NOT_RETURNED_MESSAGE = "Properties were not returned";
private static final String CHECKEDOUT_WITHOUT_REQUEST_MESSAGE = "Document was Checked Out without appropriate 'CHECKEDOUT' Versioning State attribute";
private Resource imageResource;
public CmisObjectServiceClient()
{
}
public CmisObjectServiceClient(AbstractService abstractService)
{
super(abstractService);
}
public void setImageResource(Resource imageResource)
{
this.imageResource = imageResource;
}
/**
* Initializes Object Service client
*/
public void initialize() throws Exception
{
if (LOGGER.isInfoEnabled())
{
LOGGER.info("Initializing client...");
}
}
/**
* Invokes all methods in Object Service
*/
public void invoke() throws Exception
{
if (LOGGER.isInfoEnabled())
{
LOGGER.info("Invoking client...");
}
ObjectServicePortBindingStub objectServicePort = getServicesFactory().getObjectService(getProxyUrl() + getService().getPath());
CmisPropertiesType properties = new CmisPropertiesType();
CmisPropertyString cmisPropertyName = new CmisPropertyString();
cmisPropertyName.setPropertyDefinitionId(PROP_NAME);
cmisPropertyName.setValue(new String[] { generateTestFileName() });
CmisPropertyId idProperty = new CmisPropertyId();
idProperty.setPropertyDefinitionId(PROP_OBJECT_TYPE_ID);
idProperty.setValue(new String[] { getAndAssertDocumentTypeId() });
properties.setPropertyString(new CmisPropertyString[] { cmisPropertyName });
properties.setPropertyId(new CmisPropertyId[] { idProperty });
CmisContentStreamType cmisStream = new CmisContentStreamType();
cmisStream.setFilename(generateTestFileName());
cmisStream.setMimeType(MIMETYPE_TEXT_PLAIN);
cmisStream.setStream(TEST_CONTENT.getBytes(ENCODING));
CreateDocument createDocumentParameters = new CreateDocument(getAndAssertRepositoryId(), properties, getAndAssertRootFolderId(), cmisStream, EnumVersioningState
.fromString(EnumVersioningState._major), null, null, null, null);
String documentId = objectServicePort.createDocument(createDocumentParameters).getObjectId();
properties = new CmisPropertiesType();
cmisPropertyName = new CmisPropertyString();
cmisPropertyName.setPropertyDefinitionId(PROP_NAME);
cmisPropertyName.setValue(new String[] { generateTestFolderName() });
idProperty = new CmisPropertyId();
idProperty.setPropertyDefinitionId(PROP_OBJECT_TYPE_ID);
idProperty.setValue(new String[] { getAndAssertFolderTypeId() });
properties.setPropertyString(new CmisPropertyString[] { cmisPropertyName });
properties.setPropertyId(new CmisPropertyId[] { idProperty });
CreateFolder createFolderParameters = new CreateFolder(getAndAssertRepositoryId(), properties, getAndAssertRootFolderId(), null, null, null, null);
String folderId = objectServicePort.createFolder(createFolderParameters).getObjectId();
GetAllowableActions getAllowableActionsParameters = new GetAllowableActions(getAndAssertRepositoryId(), folderId, null);
objectServicePort.getAllowableActions(getAllowableActionsParameters);
objectServicePort.getProperties(new GetProperties(getAndAssertRepositoryId(), documentId, "*", null));
properties = new CmisPropertiesType();
cmisPropertyName = new CmisPropertyString();
cmisPropertyName.setPropertyDefinitionId(PROP_NAME);
cmisPropertyName.setValue(new String[] { UPDATE_FILE_NAME });
properties.setPropertyString(new CmisPropertyString[] { cmisPropertyName });
UpdateProperties updatePropertiesParameters = new UpdateProperties(getAndAssertRepositoryId(), documentId, "", properties, null);
documentId = objectServicePort.updateProperties(updatePropertiesParameters).getObjectId();
objectServicePort.getContentStream(new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null));
MoveObject moveObjectParameters = new MoveObject(getAndAssertRepositoryId(), documentId, folderId, getAndAssertRootFolderId(), null);
objectServicePort.moveObject(moveObjectParameters);
CmisContentStreamType contentStream = new CmisContentStreamType();
contentStream.setFilename(TEST_IMAGE_NAME);
contentStream.setMimeType(MIMETYPE_IMAGE_JPEG);
InputStream viewStream = imageResource.getInputStream();
byte[] streamBytes = new byte[viewStream.available()];
viewStream.read(streamBytes);
contentStream.setStream(streamBytes);
SetContentStream setContentStreamParameters = new SetContentStream(getAndAssertRepositoryId(), documentId, true, "", contentStream, null);
documentId = objectServicePort.setContentStream(setContentStreamParameters).getObjectId();
// TODO WSDL does not correspond to specification
// objectServicePort.deleteContentStream(new DeleteContentStream(getAndAssertRepositoryId(), documentId));
deleteAndAssertObject(documentId);
objectServicePort.deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, false, EnumUnfileObject.fromString(EnumUnfileObject._delete), true, null));
}
@Override
public void release() throws Exception
{
if (LOGGER.isInfoEnabled())
{
LOGGER.info("Releasing client...");
}
}
/**
* Main method to start client
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:wsi-context.xml");
AbstractServiceClient client = (CmisObjectServiceClient) applicationContext.getBean("cmisObjectServiceClient");
try
{
client.initialize();
client.invoke();
client.release();
}
catch (Exception e)
{
LOGGER.error("Some error occured during client running. Exception message: " + e.getMessage());
}
}
@Override
protected void onSetUp() throws Exception
{
super.onSetUp();
}
@Override
protected void onTearDown() throws Exception
{
super.onTearDown();
}
public void testDocumentCreation() throws Exception
{
String documentId = createAndAssertDocument();
deleteAndAssertObject(documentId);
}
public void testDocumentCreationConstrainsObservance() throws Exception
{
String rootFolderId = getAndAssertRootFolderId();
String documentTypeId = getAndAssertDocumentTypeId();
if (!isContentStreamAllowed())
{
assertDocumentConstraitException("Creating Document with Content Stream when Content Stream is 'not allowed'", EnumServiceException.streamNotSupported,
generateTestFileName(), documentTypeId, rootFolderId, TEST_CONTENT, null, true);
}
assertDocumentConstraitException("Creating Document with 'none document' Type Id", generateTestFileName(), getAndAssertFolderTypeId(), rootFolderId, TEST_CONTENT, null);
assertNotAllowedObjectException(rootFolderId, true);
if (isContentStreamRequired())
{
assertDocumentConstraitException("Creating Document with 'required' Content Stream Type without Content Stream input parameter", generateTestFileName(),
documentTypeId, rootFolderId, null, null);
}
String constrainedDocumentTypeId = searchAndAssertNotVersionableDocumentType();
if (null != constrainedDocumentTypeId)
{
assertDocumentConstraitException("Creating not 'versionalbe' Document with Version Type input parameter equal to 'MAJOR'", generateTestFileName(),
constrainedDocumentTypeId, getAndAssertFolderTypeId(), TEST_CONTENT, EnumVersioningState.major);
assertDocumentConstraitException("Creating not 'versionalbe' Document with Version Type input parameter equal to 'CHECKEDOUT'", generateTestFileName(),
constrainedDocumentTypeId, getAndAssertFolderTypeId(), TEST_CONTENT, EnumVersioningState.checkedout);
}
CmisTypeDefinitionType typeDef = getAndAssertTypeDefinition(documentTypeId);
CmisPropertyStringDefinitionType propertyDefinition = null;
for (CmisPropertyStringDefinitionType propDef : typeDef.getPropertyStringDefinition())
{
if ((null != propDef.getMaxLength()) && (BigInteger.ZERO.compareTo(propDef.getMaxLength()) < 0))
{
propertyDefinition = propDef;
break;
}
}
if (null != propertyDefinition)
{
StringBuilder largeAppender = new StringBuilder("");
long boundary = propertyDefinition.getMaxLength().longValue();
for (long i = 0; i <= (boundary + 5); i++)
{
largeAppender.append("A");
}
CmisPropertiesType properties = new CmisPropertiesType();
properties
.setPropertyString(new CmisPropertyString[] { new CmisPropertyString(propertyDefinition.getId(), null, null, null, new String[] { largeAppender.toString() }) });
assertDocumentConstraitException(("Creating Document with outing from bounds Max Length of '" + propertyDefinition.getId() + "' property"),
EnumServiceException.constraint, generateTestFileName(), documentTypeId, getAndAssertRootFolderId(), properties, TEST_CONTENT, null);
}
// TODO: controllablePolicy is set to FALSE and at least one policy is provided
// TODO: controllableACL is set to FALSE and at least one ACE is provided
// TODO: at least one of the permissions is used in an ACE provided which is not supported by the repository
}
private void assertNotAllowedObjectException(String rootFolderId, boolean document) throws Exception
{
String constrainedTypeId = searchAndAssertNotAllowedForFolderObjectTypeId(rootFolderId, document);
String folderId = null;
if (null == constrainedTypeId)
{
String customFolderTypeId = searchAndAssertFolderFromNotBaseType();
CmisPropertiesType properties = new CmisPropertiesType();
properties
.setPropertyId(new CmisPropertyId[] { new CmisPropertyId(PROP_ALLOWED_CHILD_OBJECT_TYPE_IDS, null, null, null, new String[] { getAndAssertDocumentTypeId() }) });
folderId = createAndAssertFolder(generateTestFolderName(), customFolderTypeId, getAndAssertRootFolderId(), properties);
constrainedTypeId = searchAndAssertNotAllowedForFolderObjectTypeId(folderId, document);
}
if (null != constrainedTypeId)
{
rootFolderId = (null != folderId) ? (folderId) : (rootFolderId);
if (document)
{
assertDocumentConstraitException("Creating Document with 'not allowable object type' for Parent Folder", generateTestFileName(), constrainedTypeId, rootFolderId,
TEST_CONTENT, null);
}
else
{
assertFolderConstraitException("Creating Folder with 'not allowable object type' for Parent Folder", EnumServiceException.constraint, generateTestFolderName(),
constrainedTypeId, rootFolderId, null);
}
}
if (null != folderId)
{
deleteAndAssertObject(folderId);
}
}
private void assertDocumentConstraitException(String constraintCase, String documentName, String documentTypeId, String folderId, String content,
EnumVersioningState initialVersion) throws Exception
{
assertDocumentConstraitException(constraintCase, null, documentName, documentTypeId, folderId, content, initialVersion, false);
}
private void assertDocumentConstraitException(String constraintCase, EnumServiceException expectedException, String documentName, String documentTypeId, String folderId,
String content, EnumVersioningState initialVersion, boolean setContentStreamForcibly) throws Exception
{
assertDocumentConstraitException(constraintCase, expectedException, documentName, documentTypeId, folderId, null, content, initialVersion);
}
private void assertDocumentConstraitException(String constraintCase, EnumServiceException expectedException, String documentName, String documentTypeId, String folderId,
CmisPropertiesType properties, String content, EnumVersioningState initialVersion) throws Exception
{
try
{
String documentId = createAndAssertDocument(documentName, documentTypeId, folderId, properties, content, initialVersion);
deleteAndAssertObject(documentId);
fail("Either expected '" + expectedException.getValue() + "' Exception nor any Exception at all was thrown during " + constraintCase);
}
catch (Exception e)
{
assertException(constraintCase, e, expectedException);
}
}
public void testDocumentCreationWithoutProperties() throws Exception
{
assertDocumentConstraitException("Creating Document without mandatory input parameter 'properties'", EnumServiceException.invalidArgument, null, null,
getAndAssertRootFolderId(), null, TEST_CONTENT, null);
}
public void testDocumentCreatingAndUnfilingCapabilitySupporting() throws Exception
{
CmisRepositoryCapabilitiesType capabilities = getAndAssertCapabilities();
if (capabilities.isCapabilityUnfiling())
{
String documentId = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), null, null, TEST_CONTENT, null);
deleteAndAssertObject(documentId);
}
else
{
assertDocumentConstraitException("Creating Document without Parent Folder Id input parameter when Unfiling Capability is not supported", generateTestFileName(),
getAndAssertDocumentTypeId(), null, TEST_CONTENT, null);
}
}
public void testDocumentCreationAccordingToVersioningAttribute() throws Exception
{
if (!isVersioningAllowed())
{
logger.info("No one Document Object Type with 'versionable = true' attribute was found. Test will be skipped...");
return;
}
String documentId = createAndAssertVersionedDocument(EnumVersioningState.minor);
deleteAndAssertObject(documentId);
documentId = createAndAssertVersionedDocument(EnumVersioningState.major);
deleteAndAssertObject(documentId);
documentId = createAndAssertVersionedDocument(EnumVersioningState.checkedout);
documentId = cancelCheckOutAndAssert(documentId);
deleteAndAssertObject(documentId);
}
public void testDocumentCreatingWithACL() throws Exception
{
if (!EnumCapabilityACL.manage.equals(getAndAssertCapabilities().getCapabilityACL()))
{
logger.info("Repository doesn't support 'manage ACL' capability. Test will be skipped...");
return;
}
if (aclPrincipalId == null || aclUsername == null || aclPassword == null)
{
logger.info("ACL Credentials or ACL PrincipalId were not set. Test will be skipped...");
return;
}
CmisAccessControlListType acList = new CmisAccessControlListType();
CmisAccessControlPrincipalType principal = new CmisAccessControlPrincipalType(aclPrincipalId, null);
CmisAccessControlEntryType ace = new CmisAccessControlEntryType(principal, new String[] { PERMISSION_READ }, true, null);
acList.setPermission(new CmisAccessControlEntryType[] { ace });
String documentId = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, null, acList, null);
getPropertiesUsingCredentials(documentId, aclUsername, aclPassword);
deleteAndAssertObject(documentId);
acList = new CmisAccessControlListType();
principal = new CmisAccessControlPrincipalType(aclPrincipalId, null);
ace = new CmisAccessControlEntryType(principal, new String[] { PERMISSION_WRITE }, true, null);
acList.setPermission(new CmisAccessControlEntryType[] { ace });
documentId = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, null, acList, null);
documentId = updatePropertiesUsingCredentials(documentId, aclUsername, aclPassword);
deleteAndAssertObject(documentId);
}
private String createAndAssertVersionedDocument(EnumVersioningState versioningState) throws Exception
{
String documentId = null;
try
{
documentId = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, versioningState);
}
catch (Exception e)
{
fail(e.toString());
}
GetPropertiesOfLatestVersionResponse response = null;
String versionSeriesId = getIdProperty(documentId, PROP_VERSION_SERIES_ID);
assertNotNull("'" + PROP_VERSION_SERIES_ID + "' property is NULL", versionSeriesId);
try
{
LOGGER.info("[VersioningService->getPropertiesOfLatestVersion]");
response = getServicesFactory().getVersioningService().getPropertiesOfLatestVersion(
new GetPropertiesOfLatestVersion(getAndAssertRepositoryId(), versionSeriesId, EnumVersioningState._major.equals(versioningState.getValue()), null, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertNotNull("GetPropertiesOfLatestVersion response is NULL", response);
assertNotNull("GetPropertiesOfLatestVersion response is empty", response.getProperties());
boolean majorVersion = getBooleanProperty(response.getProperties(), PROP_IS_MAJOR_VERSION);
boolean checkedOut = getBooleanProperty(response.getProperties(), PROP_IS_VERSION_SERIES_CHECKED_OUT);
if (EnumVersioningState._major.equals(versioningState.getValue()))
{
assertTrue("Create Document service call was performed with 'MAJOR' Versioning State but it has no 'MAJOR' Versioning State", majorVersion);
assertFalse(CHECKEDOUT_WITHOUT_REQUEST_MESSAGE, checkedOut);
}
else
{
if (EnumVersioningState._checkedout.equals(versioningState.getValue()))
{
assertTrue("Create Document service call was performed with 'CHECKEDOUT' Versioning State but it has no 'CHECKEDOUT' State", checkedOut);
}
else
{
assertFalse("Create Document service call was performed with 'MINOR' Versioning State but it has 'MAJOR' Versioning State", majorVersion);
assertFalse(CHECKEDOUT_WITHOUT_REQUEST_MESSAGE, checkedOut);
}
}
return documentId;
}
// TODO: <Array> policies parameter for createDocument testing
// TODO: <Array> ACE addACEs parameter for createDocument testing
// TODO: <Array> ACE removeACEs parameter for createDocument testing
public void testDocumentFromSourceCreation() throws Exception
{
String sourceDocumentId = createAndAssertDocument();
String targetFolderId = createAndAssertFolder();
String newName = "FROM_SOURCE" + generateTestFileName();
CmisPropertiesType properties = new CmisPropertiesType();
CmisPropertyString cmisPropertyName = new CmisPropertyString();
cmisPropertyName.setPropertyDefinitionId(PROP_NAME);
cmisPropertyName.setValue(new String[] { newName });
properties.setPropertyString(new CmisPropertyString[] { cmisPropertyName });
EnumVersioningState versioningState = isVersioningAllowed() ? EnumVersioningState.major : EnumVersioningState.none;
String documentId = getServicesFactory().getObjectService().createDocumentFromSource(
new CreateDocumentFromSource(getAndAssertRepositoryId(), sourceDocumentId, properties, targetFolderId, versioningState, null, null, null, null)).getObjectId();
assertEquals("Name was not set", newName, getStringProperty(documentId, PROP_NAME));
GetContentStreamResponse response = null;
isDocumentInFolder(documentId, targetFolderId);
if (isContentStreamAllowed())
{
try
{
LOGGER.info("[ObjectService->getContentStream]");
response = getServicesFactory().getObjectService().getContentStream(new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
assertTrue("Invalid content stream was set to document", Arrays.equals(TEST_CONTENT.getBytes(), response.getContentStream().getStream()));
LOGGER.info("[ObjectService->deleteObject]");
}
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), targetFolderId, false, null));
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), sourceDocumentId, true, null));
}
public void testFolderCreation() throws Exception
{
String folderId = createAndAssertFolder();
deleteAndAssertObject(folderId);
}
public void testFolderCreatingWithACL() throws Exception
{
if (!EnumCapabilityACL.manage.equals(getAndAssertCapabilities().getCapabilityACL()))
{
logger.info("Repository doesn't support 'manage ACL' capability. Test will be skipped...");
return;
}
if (aclPrincipalId == null || aclUsername == null || aclPassword == null)
{
logger.info("ACL Credentials or ACL PrincipalId were not set. Test will be skipped...");
return;
}
CmisAccessControlListType acList = new CmisAccessControlListType();
CmisAccessControlPrincipalType principal = new CmisAccessControlPrincipalType(aclPrincipalId, null);
CmisAccessControlEntryType ace = new CmisAccessControlEntryType(principal, new String[] { PERMISSION_READ }, true, null);
acList.setPermission(new CmisAccessControlEntryType[] { ace });
String folderId = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), getAndAssertRootFolderId(), null, acList, null);
getPropertiesUsingCredentials(folderId, aclUsername, aclPassword);
deleteAndAssertObject(folderId);
}
public void testFolderCreationWithoutProperties() throws Exception
{
assertFolderConstraitException("Folder Creation without mandatory 'properties' input parameter", EnumServiceException.invalidArgument, null, null,
getAndAssertRootFolderId(), null);
}
public void testFolderCreationWithDifferentlyInvalidParentId() throws Exception
{
String folderTypeId = getAndAssertFolderTypeId();
String documentId = createAndAssertDocument();
assertFolderConstraitException("Folder Creation with none Folder 'parent folder id' input parameter", null, generateTestFolderName(), folderTypeId, documentId, null);
deleteAndAssertObject(documentId);
assertFolderConstraitException("Folder Creation with invalid 'parent folder id' input parameter", null, generateTestFolderName(), folderTypeId, "Invalid Parent Folder Id",
null);
}
public void testFolderCreationConstraintsObservance() throws Exception
{
String rootFolderId = getAndAssertRootFolderId();
assertFolderConstraitException("Folder Creation with none Folder 'type id' input parameter", EnumServiceException.constraint, generateTestFolderName(),
getAndAssertDocumentTypeId(), rootFolderId, null);
assertNotAllowedObjectException(rootFolderId, false);
// TODO: controllablePolicy is set to FALSE and at least one policy is provided
// TODO: controllableACL is set to FALSE and at least one ACE is provided
// TODO: at least one of the permissions is used in an ACE provided which is not supported by the repository
}
private void assertFolderConstraitException(String constraintCase, EnumServiceException expectedException, String folderName, String folderTypeId, String parentFolderId,
CmisPropertiesType properties) throws Exception
{
try
{
String folderId = createAndAssertFolder(folderName, folderTypeId, parentFolderId, properties);
deleteAndAssertObject(folderId);
fail("Either expected '" + expectedException.getValue() + "' Exception nor any Exception at all was thrown during " + constraintCase);
}
catch (Exception e)
{
assertException(constraintCase, e, expectedException);
}
}
// TODO: <Array> policies parameter for createFolder testing
// TODO: <Array> ACE addACEs parameter for createFolder testing
// TODO: <Array> ACE removeACEs parameter for createFolder testing
public void testCreateRelationship() throws Exception
{
String relationshipId = null;
try
{
relationshipId = createAndAssertRelationship();
}
catch (Exception e)
{
fail(e.toString());
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), relationshipId, false, null));
}
private void assertRelationshipConstraitException(String constraintCase, EnumServiceException expectedException, String sourceId, String targetId, String relationshipTypeId)
throws Exception
{
try
{
String relationshipId = createAndAssertRelationship(sourceId, targetId, relationshipTypeId);
deleteAndAssertObject(relationshipId);
fail("Either expected '" + expectedException.getValue() + "' Exception nor any Exception at all was thrown during " + constraintCase);
}
catch (Exception e)
{
assertException(constraintCase, e, expectedException);
}
}
public void testRelationshipCreationConstraintsObservance() throws Exception
{
assertRelationshipConstraitException("Relationship Creation with typeId is not an Object-Type whose baseType is Relationship", EnumServiceException.invalidArgument, null,
null, getAndAssertFolderTypeId());
String relationshipTypeId = searchAndAssertRelationshipTypeWithAllowedSourceTypes();
if (relationshipTypeId != null)
{
String notAllowdSourceTypeId = searchAndAssertNotAllowedSourceForRelationshipTypeId(relationshipTypeId);
assertRelationshipConstraitException(
"Relationship Creation with the sourceObjectIds ObjectType is not in the list of allowedSourceTypes specified by the Object-Type definition specified by typeId",
null, notAllowdSourceTypeId, null, relationshipTypeId);
}
relationshipTypeId = searchAndAssertRelationshipTypeWithAllowedTargetTypes();
if (relationshipTypeId != null)
{
String notAllowdTargetTypeId = searchAndAssertNotAllowedSourceForRelationshipTypeId(relationshipTypeId);
assertRelationshipConstraitException(
"Relationship Creation with the sourceObjectIds ObjectType is not in the list of allowedTargetTypes specified by the Object-Type definition specified by typeId",
null, null, notAllowdTargetTypeId, relationshipTypeId);
}
// TODO: controllablePolicy is set to FALSE and at least one policy is provided
// TODO: controllableACL is set to FALSE and at least one ACE is provided
// TODO: at least one of the permissions is used in an ACE provided which is not supported by the repository
}
public void testCreatePolicy() throws Exception
{
String policyTypeId = getAndAssertPolicyTypeId();
if (policyTypeId != null)
{
String policyId = null;
try
{
policyId = createAndAssertPolicy();
}
catch (Exception e)
{
fail(e.toString());
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), policyId, false, null));
}
else
{
LOGGER.info("testCreatePolicy was skipped: Policy type is not found");
}
}
public void testCreatePolicyConstraintsObservance() throws Exception
{
String policyTypeId = getAndAssertPolicyTypeId();
if (policyTypeId != null)
{
try
{
createAndAssertPolicy(generateTestPolicyName(), getAndAssertFolderTypeId(), null, getAndAssertRootFolderId());
fail("No Exception was thrown during Policy creation with typeId is not an Object-Type whose baseType is Policy");
}
catch (Exception e)
{
assertTrue("Invalid exception was thrown during Policy creation with typeId is not an Object-Type whose baseType is Policy", e instanceof CmisFaultType
&& ((CmisFaultType) e).getType().equals(EnumServiceException.constraint));
}
CmisTypeDefinitionType typeDef = getAndAssertTypeDefinition(getAndAssertPolicyTypeId());
CmisPropertyStringDefinitionType propertyDefinition = null;
for (CmisPropertyStringDefinitionType propDef : typeDef.getPropertyStringDefinition())
{
if (null != propDef.getMaxLength() && propDef.getMaxLength().longValue() > 0)
{
propertyDefinition = propDef;
break;
}
}
if (null != propertyDefinition)
{
StringBuilder largeAppender = new StringBuilder("");
long boundary = propertyDefinition.getMaxLength().longValue();
for (long i = 0; i <= (boundary + 5); i++)
{
largeAppender.append("A");
}
CmisPropertiesType properties = new CmisPropertiesType();
properties.setPropertyString(new CmisPropertyString[] { new CmisPropertyString(propertyDefinition.getId(), null, null, null, new String[] { largeAppender
.toString() }) });
if (!propertyDefinition.getId().equals(PROP_NAME))
{
CmisPropertyString cmisPropertyString = new CmisPropertyString();
cmisPropertyString.setPropertyDefinitionId(PROP_NAME);
cmisPropertyString.setValue(new String[] { generateTestPolicyName() });
properties.setPropertyString(new CmisPropertyString[] { cmisPropertyString });
}
CmisPropertyId idProperty = new CmisPropertyId();
idProperty.setPropertyDefinitionId(PROP_OBJECT_TYPE_ID);
idProperty.setValue(new String[] { getAndAssertPolicyTypeId() });
properties.setPropertyId(new CmisPropertyId[] { idProperty });
try
{
createAndAssertPolicy(null, null, properties, getAndAssertRootFolderId());
fail("No Exception was thrown during Policy creation with '" + propertyDefinition.getId() + "' value length greater than MAX length");
}
catch (Exception e)
{
assertTrue("Invalid exception was thrown during Policy creation with '" + propertyDefinition.getId() + "' value length greater than MAX length",
e instanceof CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.constraint));
}
}
String customFolderTypeId = searchAndAssertFolderFromNotBaseType();
CmisPropertiesType properties = new CmisPropertiesType();
properties
.setPropertyId(new CmisPropertyId[] { new CmisPropertyId(PROP_ALLOWED_CHILD_OBJECT_TYPE_IDS, null, null, null, new String[] { getAndAssertDocumentTypeId() }) });
String folderId = createAndAssertFolder(generateTestFolderName(), customFolderTypeId, getAndAssertRootFolderId(), properties);
try
{
createAndAssertPolicy(generateTestPolicyName(), getAndAssertPolicyTypeId(), null, folderId);
fail("No Exception was thrown during Policy creation with 'typeId' value not in the list of AllowedChildObjectTypeIds of the parent-folder specified by folderId");
}
catch (Exception e)
{
assertTrue(
"Invalid exception was thrown during Policy creation with 'typeId' value not in the list of AllowedChildObjectTypeIds of the parent-folder specified by folderId",
e instanceof CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.constraint));
}
}
else
{
LOGGER.info("testCreatePolicy was skipped: Policy type is not found");
}
// TODO: controllablePolicy is set to FALSE and at least one policy is provided
// TODO: controllableACL is set to FALSE and at least one ACE is provided
// TODO: at least one of the permissions is used in an ACE provided which is not supported by the repository
}
public void testGetAllowableActions() throws Exception
{
GetAllowableActionsResponse response = null;
try
{
LOGGER.info("[ObjectService->getAllowableActions]");
response = getServicesFactory().getObjectService().getAllowableActions(new GetAllowableActions(getAndAssertRepositoryId(), getAndAssertRootFolderId(), null));
}
catch (Exception e)
{
fail(e.toString());
}
assertNotNull("No allowable actions were returned", response);
assertNotNull("Action 'getProperties' not defined for an object", response.getAllowableActions().getCanGetProperties());
}
public void testGetPropertiesDefault() throws Exception
{
GetPropertiesResponse response = null;
try
{
LOGGER.info("[ObjectService->getProperties]");
response = getServicesFactory().getObjectService().getProperties(new GetProperties(getAndAssertRepositoryId(), getAndAssertRootFolderId(), "*", null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("No properties were returned", response != null && response.getProperties() != null);
assertNotNull("No 'Name' property was returned", getStringProperty(response.getProperties(), PROP_NAME));
}
public void testGetPropertiesFiltered() throws Exception
{
GetPropertiesResponse response = null;
try
{
String filter = PROP_NAME + "," + PROP_OBJECT_ID;
LOGGER.info("[ObjectService->getProperties]");
response = getServicesFactory().getObjectService().getProperties(new GetProperties(getAndAssertRepositoryId(), getAndAssertRootFolderId(), filter, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("No properties were returned", response != null && response.getProperties() != null);
CmisPropertiesType properties = response.getProperties();
assertNull("Not expected properties were returned", properties.getPropertyBoolean());
assertNull("Not expected properties were returned", properties.getPropertyDecimal());
assertNull("Not expected properties were returned", properties.getPropertyHtml());
assertNull("Not expected properties were returned", properties.getPropertyInteger());
assertNull("Not expected properties were returned", properties.getPropertyUri());
assertNull("Not expected properties were returned", properties.getPropertyDateTime());
assertNotNull("Expected properties were not returned", properties.getPropertyId());
assertNotNull("Expected properties were not returned", properties.getPropertyString());
assertNotNull("Expected property was not returned", getIdProperty(properties, PROP_OBJECT_ID));
assertNotNull("Expected property was not returned", getStringProperty(properties, PROP_NAME));
}
public void testGetObject() throws Exception
{
GetObjectResponse response = null;
try
{
LOGGER.info("[ObjectService->getObject]");
response = getServicesFactory().getObjectService().getObject(
new GetObject(getAndAssertRepositoryId(), getAndAssertRootFolderId(), "*", true, EnumIncludeRelationships.none, null, null, null, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("No properties were returned", response != null && response.getObject() != null && response.getObject().getProperties() != null);
assertNotNull("No 'Name' property was returned", getStringProperty(response.getObject().getProperties(), PROP_NAME));
}
public void testGetObjectIncludeRenditions() throws Exception
{
if (EnumCapabilityRendition.read.equals(getAndAssertCapabilities().getCapabilityRenditions()))
{
String documentId = createAndAssertDocument();
List<RenditionData> testRenditions = getTestRenditions(documentId);
if (testRenditions != null)
{
for (RenditionData testRendition : testRenditions)
{
LOGGER.info("[ObjectService->getObject]");
GetObjectResponse response = getServicesFactory().getObjectService()
.getObject(
new GetObject(getAndAssertRepositoryId(), documentId, PROP_OBJECT_ID, false, EnumIncludeRelationships.none, testRendition.getFilter(), null,
null, null));
assertTrue("Response is empty", response != null && response.getObject() != null);
assertRenditions(response.getObject(), testRendition.getFilter(), testRendition.getExpectedKinds(), testRendition.getExpectedMimetypes());
}
}
else
{
LOGGER.info("testGetObjectIncludeRenditions was skipped: No renditions found for document type");
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
}
else
{
LOGGER.info("testGetObjectIncludeRenditions was skipped: Renditions are not supported");
}
}
public void testGetObjectIncludeAllowableActionsAndRelationships() throws Exception
{
GetObjectResponse response = null;
try
{
LOGGER.info("[ObjectService->getObject]");
response = getServicesFactory().getObjectService().getObject(
new GetObject(getAndAssertRepositoryId(), getAndAssertRootFolderId(), PROP_NAME, true, EnumIncludeRelationships.none, null, null, null, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue(PROPERTIES_NOT_RETURNED_MESSAGE, response != null && response.getObject() != null && response.getObject().getProperties() != null);
assertNotNull("Allowable actions were not returned", response.getObject().getAllowableActions());
assertNotNull("No action 'getProperties' was returned", response.getObject().getAllowableActions().getCanGetProperties());
String sourceId = createRelationshipSourceObject(getAndAssertRootFolderId());
String relationshipId = createAndAssertRelationship(sourceId, null);
try
{
LOGGER.info("[ObjectService->getObject]");
response = getServicesFactory().getObjectService().getObject(
new GetObject(getAndAssertRepositoryId(), sourceId, PROP_NAME, false, EnumIncludeRelationships.both, null, null, null, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue(PROPERTIES_NOT_RETURNED_MESSAGE, response != null && response.getObject() != null && response.getObject().getProperties() != null);
assertTrue("Relationships were not returned", response.getObject().getRelationship() != null && response.getObject().getRelationship().length >= 1);
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), relationshipId, false, null));
}
public void testGetObjectByPath() throws Exception
{
String folder1Id = null;
String folder2Id = null;
try
{
String folder1Name = generateTestFolderName("_1");
String folder2Name = generateTestFolderName("_2");
folder1Id = createAndAssertFolder(folder1Name, getAndAssertFolderTypeId(), getAndAssertRootFolderId(), null);
folder2Id = createAndAssertFolder(folder2Name, getAndAssertFolderTypeId(), folder1Id, null);
assertNotNull("Folder was not created", folder1Id);
assertNotNull("Folder was not created", folder2Id);
String pathToFolder1 = "/" + folder1Name;
String pathToFolder2 = "/" + folder1Name + "/" + folder2Name;
LOGGER.info("[ObjectService->getFolderByPath]");
GetObjectByPathResponse response = getServicesFactory().getObjectService().getObjectByPath(
new GetObjectByPath(getAndAssertRepositoryId(), pathToFolder1, "*", false, null, null, null, null, null));
assertTrue("Folder was not found", response != null && response.getObject() != null && response.getObject().getProperties() != null);
assertEquals("Wrong folder was found", folder1Id, getIdProperty(response.getObject().getProperties(), PROP_OBJECT_ID));
LOGGER.info("[ObjectService->getFolderByPath]");
response = getServicesFactory().getObjectService().getObjectByPath(
new GetObjectByPath(getAndAssertRepositoryId(), pathToFolder2, "*", false, null, null, null, null, null));
assertTrue("Folder was not found", response != null && response.getObject() != null && response.getObject().getProperties() != null);
assertEquals("Wrong folder was found", folder2Id, getIdProperty(response.getObject().getProperties(), PROP_OBJECT_ID));
}
catch (Exception e)
{
fail(e.toString());
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folder2Id, false, null));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folder1Id, false, null));
}
public void testGetContentStream() throws Exception
{
if (isContentStreamAllowed())
{
GetContentStreamResponse response = null;
String documentId = createAndAssertDocument();
try
{
LOGGER.info("[ObjectService->getContentStream]");
response = getServicesFactory().getObjectService().getContentStream(new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null));
}
catch (Exception e)
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
fail(e.toString());
}
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
assertTrue("Invalid content stream was returned", Arrays.equals(TEST_CONTENT.getBytes(), response.getContentStream().getStream()));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
}
else
{
LOGGER.info("testGetContentStream was skipped: Content stream isn't allowed");
}
}
public void testGetContentStreamForRenditions() throws Exception
{
if (isContentStreamAllowed())
{
if (getAndAssertCapabilities().getCapabilityRenditions().equals(EnumCapabilityRendition.read))
{
String documentId = createAndAssertDocument();
CmisRenditionType[] renditionTypes = null;
LOGGER.info("[ObjectService->getRenditions]");
renditionTypes = getServicesFactory().getObjectService().getRenditions(
new GetRenditions(getAndAssertRepositoryId(), documentId, "*", BigInteger.valueOf(1), BigInteger.valueOf(0), null));
CmisObjectType cmisObject = new CmisObjectType();
cmisObject.setRendition(renditionTypes);
assertNotNull("No Renditions were returned", renditionTypes);
assertRenditions(cmisObject, "*", null, null);
for (CmisRenditionType cmisRendition : renditionTypes)
{
GetContentStreamResponse response = null;
try
{
LOGGER.info("[ObjectService->getContentStream]");
response = getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, cmisRendition.getStreamId(), null, null, null));
}
catch (Exception e)
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
fail(e.toString());
}
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
}
else
{
LOGGER.info("testGetRenditions was skipped: Renditions aren't supported");
}
}
else
{
LOGGER.info("testGetContentStream was skipped: Content stream isn't allowed");
}
}
public void testGetContentStreamPortioned() throws Exception
{
if (isContentStreamAllowed())
{
GetContentStreamResponse response = null;
String documentId = createAndAssertDocument();
byte[] byteContent = TEST_CONTENT.getBytes();
// firstPortion offset=2, length=7
byte[] firstPortion = new byte[7];
System.arraycopy(byteContent, 2, firstPortion, 0, 7);
// secondPortion offset=content.length-5
byte[] secondPortion = new byte[6];
System.arraycopy(byteContent, byteContent.length - 6, secondPortion, 0, 6);
try
{
LOGGER.info("[ObjectService->getContentStream]");
response = getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", BigInteger.valueOf(0), null, null));
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
assertTrue("Invalid range of content was returned", Arrays.equals(byteContent, response.getContentStream().getStream()));
response = getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", BigInteger.valueOf(2), BigInteger.valueOf(7), null));
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
assertTrue("Invalid range of content was returned", Arrays.equals(firstPortion, response.getContentStream().getStream()));
response = getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", BigInteger.valueOf(byteContent.length - 6), BigInteger.valueOf(10), null));
assertTrue("No content stream was returned", response != null && response.getContentStream() != null);
assertTrue("Invalid range of content was returned", Arrays.equals(secondPortion, response.getContentStream().getStream()));
}
catch (Exception e)
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
fail(e.toString());
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
}
else
{
LOGGER.info("testGetContentStream was skipped: Content stream isn't allowed");
}
}
public void testGetContentStreamConstraintsObservance() throws Exception
{
String docTypeWithNoContentAllowed = searchAndAssertDocumentTypeWithNoContentAlowed();
if (docTypeWithNoContentAllowed != null && !docTypeWithNoContentAllowed.equals(""))
{
String documentId = createAndAssertDocument(generateTestFileName(), docTypeWithNoContentAllowed, getAndAssertRootFolderId(), null, null, null);
try
{
LOGGER.info("[ObjectService->getContentStream]");
getServicesFactory().getObjectService().getContentStream(new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null));
fail("Either expected 'constraint' Exception, or no Exception at all was thrown during getting content stream for object which does NOT have a content stream");
}
catch (Exception e)
{
assertException("Trying to get content stream for object which does NOT have a content stream", e, EnumServiceException.constraint);
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
}
public void testUpdateProperties() throws Exception
{
String documentName = generateTestFileName();
String documentId = createAndAssertDocument(documentName, getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.none);
String documentNameNew = generateTestFileName("_new");
try
{
CmisPropertiesType properties = fillProperties(documentNameNew, null);
LOGGER.info("[ObjectService->updateProperties]");
documentId = getServicesFactory().getObjectService().updateProperties(new UpdateProperties(getAndAssertRepositoryId(), documentId, null, properties, null))
.getObjectId();
}
catch (Exception e)
{
fail(e.toString());
}
String receivedPropertyName = getStringProperty(documentId, PROP_NAME);
assertTrue("Properties was not updated", documentNameNew.equals(receivedPropertyName));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
}
public void testMoveObjectDefault() throws Exception
{
String documentName = generateTestFileName();
String documentId = createAndAssertDocument(documentName, getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.none);
String folderId = createAndAssertFolder();
try
{
LOGGER.info("[ObjectService->moveObject]");
getServicesFactory().getObjectService().moveObject(new MoveObject(getAndAssertRepositoryId(), documentId, folderId, getAndAssertRootFolderId(), null));
}
catch (Exception e)
{
fail(e.toString());
}
assertFalse("Object was not removed from source folder", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
assertTrue("Object was not added to target folder", isDocumentInFolder(documentId, folderId));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folderId, false, null));
}
// FIXME: Maybe cd06 specification have missed notion about un-filling in context of this operation (when sourceFolderId is required)
/*
* public void testMoveObjectUnfiled() throws Exception { if (getAndAssertCapabilities().isCapabilityUnfiling()) { String folderId = createAndAssertFolder(); String documentId
* = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), null, null, null, null); try { LOGGER.info("[ObjectService->moveObject]");
* getServicesFactory().getObjectService().moveObject(new MoveObject(getAndAssertRepositoryId(), documentId, folderId, null, null));
* fail("No Exception was thrown during moving unfiled object"); } catch (Exception e) { assertTrue("Invalid exception was thrown during moving unfiled object", e instanceof
* CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.notSupported)); } LOGGER.info("[ObjectService->deleteObject]");
* getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, false, null)); LOGGER.info("[ObjectService->deleteObject]");
* getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folderId, false, null)); } else {
* LOGGER.info("testMoveObjectUnfiled was skipped: Unfiling isn't supported"); } }
*/
public void testMoveObjectMultiFiled() throws Exception
{
if (getAndAssertCapabilities().isCapabilityMultifiling())
{
String documentId = createAndAssertDocument();
String folderId = createAndAssertFolder();
String folder2Id = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), documentId, folderId, null, null));
try
{
LOGGER.info("[ObjectService->moveObject]");
getServicesFactory().getObjectService().moveObject(new MoveObject(getAndAssertRepositoryId(), documentId, folder2Id, folderId, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertFalse("Object was not removed from source folder", isDocumentInFolder(documentId, folderId));
assertTrue("Object was removed from not source folder", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
assertTrue("Object was not added to target folder", isDocumentInFolder(documentId, folder2Id));
LOGGER.info("[ObjectService->deleteTree]");
getServicesFactory().getObjectService().deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.delete, true, null));
}
}
// FIXME: It is NECESSARY test 'versionSeries' existent and test tries for requesting properties etc of some object from 'versionSeries'
// FIXME: It is NECESSARY test 'getPropertiesOfLatestVersion' service's method call after deleting current document
public void testDeleteObject() throws Exception
{
String documentId = createAndAssertDocument();
try
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertFalse("Object was not removed", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
}
public void testDeleteFolderWithChild() throws Exception
{
String folderId = createAndAssertFolder();
String folder2Id = createAndAssertFolder(generateTestFolderName("1"), getAndAssertFolderTypeId(), folderId, null);
try
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folderId, false, null));
fail("No Exception was thrown during deleting folder with child");
}
catch (Exception e)
{
assertTrue("Invalid exception was thrown during deleting folder with child", e instanceof CmisFaultType);
}
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folder2Id, false, null));
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), folderId, false, null));
}
public void testDeleteMultiFiledObject() throws Exception
{
if (getAndAssertCapabilities().isCapabilityMultifiling())
{
String documentId = createAndAssertDocument();
String folderId = createAndAssertFolder();
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), documentId, folderId, null, null));
try
{
// TODO works not correct in Alfresco
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertFalse("Object was not removed", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
assertFalse("Object was not removed", isDocumentInFolder(documentId, folderId));
LOGGER.info("[ObjectService->deleteTree]");
getServicesFactory().getObjectService().deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.delete, true, null));
}
}
public void testDeletePWC() throws Exception
{
if (isVersioningAllowed())
{
String documentId = createAndAssertDocument();
LOGGER.info("[VersioningService->checkOut]");
String checkedOutId = getServicesFactory().getVersioningService().checkOut(new CheckOut(getAndAssertRepositoryId(), documentId, null)).getObjectId();
try
{
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), checkedOutId, false, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertFalse("Private working copy was not deleted", getBooleanProperty(documentId, PROP_IS_VERSION_SERIES_CHECKED_OUT));
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
else
{
LOGGER.info("testDeletePWC was skipped: Versioning isn't supported");
}
}
public void testDeleteTreeDefault() throws Exception
{
DeleteTreeResponse response = null;
String folderId = createAndAssertFolder();
createAndAssertDocument();
createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
try
{
LOGGER.info("[ObjectService->deleteTree]");
response = getServicesFactory().getObjectService().deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.delete, false, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Objects tree was not deleted", response == null || response.getFailedToDelete() == null || response.getFailedToDelete().getObjectIds() == null
|| response.getFailedToDelete().getObjectIds().length == 0);
}
public void testDeleteTreeUnfileNonfolderObjects() throws Exception
{
if (getAndAssertCapabilities().isCapabilityMultifiling())
{
DeleteTreeResponse response = null;
String folderId = createAndAssertFolder();
String documentId = createAndAssertDocument();
String folder2Id = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
String document2Id = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), folderId, null, TEST_CONTENT, EnumVersioningState.major);
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), documentId, folderId, true, null));
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), document2Id, folder2Id, true, null));
try
{
LOGGER.info("[ObjectService->deleteTree]");
response = getServicesFactory().getObjectService().deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.delete, true, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Objects tree was not deleted", response == null || response.getFailedToDelete() == null || response.getFailedToDelete().getObjectIds() == null
|| response.getFailedToDelete().getObjectIds().length == 0);
assertFalse("Multifiled document was not removed", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
folderId = createAndAssertFolder();
documentId = createAndAssertDocument();
folder2Id = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
document2Id = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), folderId, null, TEST_CONTENT, EnumVersioningState.major);
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), documentId, folderId, true, null));
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), document2Id, folder2Id, true, null));
try
{
LOGGER.info("[ObjectService->deleteTree]");
response = getServicesFactory().getObjectService().deleteTree(
new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.deletesinglefiled, false, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Objects tree was not deleted", response == null || response.getFailedToDelete() == null || response.getFailedToDelete().getObjectIds() == null
|| response.getFailedToDelete().getObjectIds().length == 0);
assertTrue("Multifiled document was removed", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
if (getAndAssertCapabilities().isCapabilityUnfiling())
{
folderId = createAndAssertFolder();
documentId = createAndAssertDocument();
folder2Id = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
document2Id = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), folderId, null, TEST_CONTENT, EnumVersioningState.major);
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), documentId, folderId, true, null));
LOGGER.info("[MultiFilingService->addObjectToFolder]");
getServicesFactory().getMultiFilingServicePort().addObjectToFolder(new AddObjectToFolder(getAndAssertRepositoryId(), document2Id, folder2Id, true, null));
try
{
LOGGER.info("[ObjectService->deleteTree]");
response = getServicesFactory().getObjectService().deleteTree(new DeleteTree(getAndAssertRepositoryId(), folderId, true, EnumUnfileObject.unfile, false, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Objects tree was not deleted", response == null || response.getFailedToDelete() == null || response.getFailedToDelete().getObjectIds() == null
|| response.getFailedToDelete().getObjectIds().length == 0);
assertFalse("Multifiled document not unfiled", isDocumentInFolder(documentId, getAndAssertRootFolderId()));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), document2Id, true, null));
}
}
}
public void testDeleteTreeWithAllVersions() throws Exception
{
if (isVersioningAllowed())
{
assertDeleteTreeAllVersions(true);
}
else
{
LOGGER.info("testDeleteTreeWithAllVersions was skipped: Versioning isn't supported");
}
}
public void testDeleteTreeWithoutAllVersions() throws Exception
{
if (isVersioningAllowed())
{
assertDeleteTreeAllVersions(false);
}
else
{
LOGGER.info("testDeleteTreeWithoutAllVersions was skipped: Versioning isn't supported");
}
}
private void assertDeleteTreeAllVersions(boolean deleteAllVersion) throws Exception
{
String folderId = createAndAssertFolder();
String folder2Id = createAndAssertFolder(generateTestFolderName(), getAndAssertFolderTypeId(), folderId, null);
String documentId = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), folderId, null, TEST_CONTENT, EnumVersioningState.major);
String document2Id = createAndAssertDocument(generateTestFileName(), getAndAssertDocumentTypeId(), folder2Id, null, TEST_CONTENT, EnumVersioningState.major);
for (int i = 0; i < 2; ++i)
{
VersioningServicePortBindingStub versioningService = getServicesFactory().getVersioningService();
LOGGER.info("[VersioningService->checkOut]");
CheckOutResponse checkOutResponse = versioningService.checkOut(new CheckOut(getAndAssertRepositoryId(), documentId, null));
LOGGER.info("[VersioningService->checkIn]");
CheckInResponse checkInResponse = versioningService.checkIn(new CheckIn(getAndAssertRepositoryId(), checkOutResponse.getObjectId(), true, new CmisPropertiesType(),
new CmisContentStreamType(BigInteger.valueOf(12), "text/plain", generateTestFileName(), "Test content".getBytes(), null), "", null, null, null, null));
documentId = checkInResponse.getObjectId();
}
LOGGER.info("[VersioningService->getAllVersions]");
CmisObjectType[] response = getServicesFactory().getVersioningService().getAllVersions(new GetAllVersions(getAndAssertRepositoryId(), documentId, null, null, null));
List<String> versionsIds = new ArrayList<String>();
for (CmisObjectType cmisObjectType : response)
{
if (cmisObjectType.getProperties() != null)
{
versionsIds.add(getIdProperty(cmisObjectType.getProperties(), PROP_OBJECT_ID));
}
}
DeleteTreeResponse deleteTreeResponse = null;
try
{
LOGGER.info("[ObjectService->deleteTree]");
deleteTreeResponse = getServicesFactory().getObjectService().deleteTree(
new DeleteTree(getAndAssertRepositoryId(), folderId, deleteAllVersion, EnumUnfileObject.delete, true, null));
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Objects tree was not deleted", deleteTreeResponse == null || deleteTreeResponse.getFailedToDelete() == null
|| deleteTreeResponse.getFailedToDelete().getObjectIds() == null || deleteTreeResponse.getFailedToDelete().getObjectIds().length == 0);
for (String versionId : versionsIds)
{
if (deleteAllVersion)
{
assertObjectNotExist(versionId);
}
else
{
assertObjectExist(versionId);
}
}
assertObjectNotExist(folderId);
assertObjectNotExist(folder2Id);
assertObjectNotExist(documentId);
assertObjectNotExist(document2Id);
}
private void assertObjectExist(String objectId) throws Exception
{
GetPropertiesResponse propResponse = null;
try
{
LOGGER.info("[ObjectService->getProperties]");
propResponse = getServicesFactory().getObjectService().getProperties(new GetProperties(getAndAssertRepositoryId(), objectId, "*", null));
assertTrue("Version was removed while flag deleteAllVersions is FALSE", propResponse != null && propResponse.getProperties() != null
&& propResponse.getProperties().getPropertyId().length > 0);
}
catch (Exception e)
{
}
assertTrue("Object does not exist", propResponse != null && propResponse.getProperties() != null && propResponse.getProperties().getPropertyId().length > 0);
}
private void assertObjectNotExist(String objectId) throws Exception
{
GetPropertiesResponse propResponse = null;
try
{
LOGGER.info("[ObjectService->getProperties]");
propResponse = getServicesFactory().getObjectService().getProperties(new GetProperties(getAndAssertRepositoryId(), objectId, "*", null));
assertTrue("Version was removed while flag deleteAllVersions is FALSE", propResponse != null && propResponse.getProperties() != null
&& propResponse.getProperties().getPropertyId().length > 0);
}
catch (Exception e)
{
}
assertTrue("Object exists", propResponse == null || propResponse.getProperties() == null);
}
public void testSetContentStream() throws Exception
{
if (isContentStreamAllowed())
{
String documentName = generateTestFileName();
String documentId = createAndAssertDocument(documentName, getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.none);
String newTestCOntent = TEST_CONTENT + System.currentTimeMillis();
try
{
LOGGER.info("[ObjectService->setContentStream]");
documentId = getServicesFactory().getObjectService().setContentStream(
new SetContentStream(getAndAssertRepositoryId(), documentId, true, null, new CmisContentStreamType(BigInteger.valueOf(newTestCOntent.length()),
MIMETYPE_TEXT_PLAIN, documentName, newTestCOntent.getBytes(ENCODING), null), null)).getObjectId();
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Content stream was not updated", Arrays.equals(newTestCOntent.getBytes(), getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null)).getContentStream().getStream()));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
else
{
LOGGER.info("testSetContentStream was skipped: Content stream isn't allowed");
}
}
public void testSetContentStreamOverwriteFlag() throws Exception
{
if (isContentStreamAllowed())
{
String documentName = generateTestFileName();
String documentId = createAndAssertDocument(documentName, getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.none);
String newTestCOntent = TEST_CONTENT + System.currentTimeMillis();
try
{
LOGGER.info("[ObjectService->setContentStream]");
documentId = getServicesFactory().getObjectService().setContentStream(
new SetContentStream(getAndAssertRepositoryId(), documentId, false, null, new CmisContentStreamType(BigInteger.valueOf(newTestCOntent.length()),
MIMETYPE_TEXT_PLAIN, documentName, newTestCOntent.getBytes(ENCODING), null), null)).getObjectId();
fail("No Exception was thrown during setting content stream while input parameter overwriteFlag is FALSE and the Object already has a content-stream");
}
catch (Exception e)
{
assertTrue("Invalid exception was thrown during setting content stream while input parameter overwriteFlag is FALSE and the Object already has a content-stream",
e instanceof CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.contentAlreadyExists));
}
try
{
LOGGER.info("[ObjectService->setContentStream]");
documentId = getServicesFactory().getObjectService().setContentStream(
new SetContentStream(getAndAssertRepositoryId(), documentId, true, null, new CmisContentStreamType(BigInteger.valueOf(newTestCOntent.length()),
MIMETYPE_TEXT_PLAIN, documentName, newTestCOntent.getBytes(ENCODING), null), null)).getObjectId();
}
catch (Exception e)
{
fail(e.toString());
}
assertTrue("Content stream was not updated", Arrays.equals(newTestCOntent.getBytes(), getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null)).getContentStream().getStream()));
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
else
{
LOGGER.info("testSetContentStreamOverwriteFlag was skipped: Content stream isn't allowed");
}
}
public void testSetContentStreamNotAllowed() throws Exception
{
String documentTypeId = searchAndAssertDocumentTypeWithContentNotAllowed();
if (documentTypeId != null)
{
String documentId = createAndAssertDocument(generateTestFileName(), documentTypeId, getAndAssertRootFolderId(), null, null, EnumVersioningState.major);
try
{
LOGGER.info("[ObjectService->setContentStream]");
getServicesFactory().getObjectService().setContentStream(
new SetContentStream(getAndAssertRepositoryId(), documentId, true, null, new CmisContentStreamType(BigInteger.valueOf(TEST_CONTENT.length()),
MIMETYPE_TEXT_PLAIN, generateTestFileName(), TEST_CONTENT.getBytes(ENCODING), null), null)).getObjectId();
fail("No Exception was thrown during setting content stream while Object-Type definition specified by the typeId parameters contentStreamAllowed attribute is set to not allowed");
}
catch (Exception e)
{
// TODO according to specification 2 types of exceptions SHOULD be thrown
assertTrue(
"Invalid exception was thrown during setting content stream while Object-Type definition specified by the typeId parameters contentStreamAllowed attribute is set to not allowed",
e instanceof CmisFaultType
&& (((CmisFaultType) e).getType().equals(EnumServiceException.constraint) || ((CmisFaultType) e).getType().equals(
EnumServiceException.streamNotSupported)));
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
}
public void testDeleteContentStream() throws Exception
{
if (isContentStreamAllowed())
{
String documentName = generateTestFileName();
String documentId = createAndAssertDocument(documentName, getAndAssertDocumentTypeId(), getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.none);
try
{
LOGGER.info("[ObjectService->deleteContentStream]");
DeleteContentStreamResponse response = getServicesFactory().getObjectService().deleteContentStream(
new DeleteContentStream(getAndAssertRepositoryId(), documentId, null, null));
assertNotNull("DeleteContentStream response is NULL", response);
assertNotNull("DeleteContentStream response is empty", response.getObjectId());
documentId = response.getObjectId();
}
catch (Exception e)
{
fail(e.toString());
}
try
{
GetContentStreamResponse contentStreamResponse = getServicesFactory().getObjectService().getContentStream(
new GetContentStream(getAndAssertRepositoryId(), documentId, "", null, null, null));
assertTrue("Content stream was not deleted", contentStreamResponse == null || contentStreamResponse.getContentStream() == null
|| contentStreamResponse.getContentStream().getStream() == null);
}
catch (Exception e)
{
assertTrue("Invalid exception was thrown", e instanceof CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.constraint));
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
else
{
LOGGER.info("testDeleteContentStream was skipped: Content stream isn't allowed");
}
}
public void testDeleteContentStreamRequired() throws Exception
{
String documentTypeId = searchAndAssertDocumentTypeWithContentRequired();
if (documentTypeId != null)
{
String documentId = createAndAssertDocument(generateTestFileName(), documentTypeId, getAndAssertRootFolderId(), null, TEST_CONTENT, EnumVersioningState.major);
try
{
LOGGER.info("[ObjectService->deleteContentStream]");
getServicesFactory().getObjectService().deleteContentStream(new DeleteContentStream(getAndAssertRepositoryId(), documentId, null, null));
fail("No Exception was thrown during deleting content stream while Objects Object-Type definition contentStreamAllowed attribute is set to required");
}
catch (Exception e)
{
assertTrue(
"Invalid exception was thrown during deleting content stream while Objects Object-Type definition contentStreamAllowed attribute is set to required",
e instanceof CmisFaultType && ((CmisFaultType) e).getType().equals(EnumServiceException.constraint));
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
}
public void testGetRenditions() throws Exception
{
if (getAndAssertCapabilities().getCapabilityRenditions().equals(EnumCapabilityRendition.read))
{
String documentId = createAndAssertDocument();
CmisRenditionType[] renditionTypes = null;
try
{
LOGGER.info("[ObjectService->getRenditions]");
renditionTypes = getServicesFactory().getObjectService().getRenditions(
new GetRenditions(getAndAssertRepositoryId(), documentId, "*", BigInteger.valueOf(1), BigInteger.valueOf(0), null));
assertNotNull("No Renditions were returned", renditionTypes);
CmisObjectType cmisObject = new CmisObjectType();
cmisObject.setRendition(renditionTypes);
assertRenditions(cmisObject, "*", null, null);
}
catch (Exception e)
{
fail(e.toString());
}
LOGGER.info("[ObjectService->deleteObject]");
getServicesFactory().getObjectService().deleteObject(new DeleteObject(getAndAssertRepositoryId(), documentId, true, null));
}
else
{
LOGGER.info("testGetRenditions was skipped: Renditions aren't supported");
}
}
}
| lgpl-3.0 |
qwc/adis | src/to/mmo/adis/SearchValue.java | 660 | package to.mmo.adis;
public class SearchValue {
private EntityValue entity;
private int maxEntries;
private boolean error;
public SearchValue() {
}
public SearchValue(EntityValue entity, int maxentries) {
this();
this.entity = entity;
maxEntries = maxentries;
}
public EntityValue getEntity() {
return entity;
}
public void setEntity(EntityValue entity) {
this.entity = entity;
}
public int getMaxEntries() {
return maxEntries;
}
public void setMaxEntries(int maxEntries) {
this.maxEntries = maxEntries;
}
public boolean isError() {
return error;
}
public void setError(boolean error) {
this.error = error;
}
}
| lgpl-3.0 |
fcarsten/portal-core | src/main/java/org/auscope/portal/core/services/responses/csw/AbstractCSWOnlineResource.java | 4148 | package org.auscope.portal.core.services.responses.csw;
import java.net.URL;
import org.auscope.portal.core.services.csw.CSWRecordsFilterVisitor;
/**
* Represents a <gmd:CI_OnlineResource> element in a CSW response.
*
* @author vot002
*
*/
public abstract class AbstractCSWOnlineResource {
/**
* A simplification of the protocol.
*
* @author vot002
*
*/
public enum OnlineResourceType {
/**
* The type couldn't be determined or is unsupported.
*/
Unsupported,
/**
* OGC Web Coverage Service.
*/
WCS,
/**
* OGC Web Map Service.
*/
WMS,
/**
* OGC Web Feature Service.
*/
WFS,
/**
* OpenDAP.
*/
OPeNDAP,
/**
* A FTP (File Transfer Protocol) link
*/
FTP,
/**
* A generic web link.
*/
WWW,
/**
* A SOS Service
*/
SOS,
/**
* IRIS Web Service
*/
IRIS,
/**
* A CSW Service. e.g. a GeoNetwork /csw endpoint. Can be used a dummy resource for when you don't want to cache all CSW records on load.
*/
CSWService,
/**
* A NetCDF Subset Service.
*/
NCSS
}
/**
* Gets the URL location of this online resource.
*
* @return
*/
public abstract URL getLinkage();
/**
* Gets the protocol of this online resource.
*
* @return
*/
public abstract String getProtocol();
/**
* Gets the name of this online resource.
*
* @return
*/
public abstract String getName();
/**
* Gets a description of this online resource.
*
* @return
*/
public abstract String getDescription();
/**
* Gets the application profile (if available) of this online resource.
*
* @return
*/
public abstract String getApplicationProfile();
/**
* provide the protocol version if possible. eg WMS 1.1.1 vs 1.3.0
*
* @return version if possible
*/
public abstract String getVersion();
/**
* provide the protocol request if possible
*
* @return protocol request if possible
*/
public abstract String getProtocolRequest();
/**
* Gets a simplification of the protocol that this online resource represents.
*
* @return
*/
public OnlineResourceType getType() {
String lowerProtocol = getProtocol();
if (lowerProtocol == null) {
return OnlineResourceType.Unsupported;
}
lowerProtocol = lowerProtocol.toLowerCase();
if (lowerProtocol.contains("wfs")) {
return OnlineResourceType.WFS;
} else if (lowerProtocol.contains("wms")) {
return OnlineResourceType.WMS;
} else if (lowerProtocol.contains("wcs")) {
return OnlineResourceType.WCS;
} else if (lowerProtocol.contains("www:link-1.0-http--link")
|| lowerProtocol.contains("www:download-1.0-http--download")) {
//Dap is currently hacked in
String name = getDescription();
if ((name != null) && name.equals("HACK-OPENDAP")) {
return OnlineResourceType.OPeNDAP;
}
return OnlineResourceType.WWW;
} else if (lowerProtocol.contains("ogc:sos-")) {
return OnlineResourceType.SOS;
} else if (lowerProtocol.contains("www:download-1.0-ftp--download")) {
return OnlineResourceType.FTP;
} else if (lowerProtocol.contains("iris")) {
return OnlineResourceType.IRIS;
} else if (lowerProtocol.contains("cswservice")) {
return OnlineResourceType.CSWService;
} else if (lowerProtocol.contains("ncss")) {
return OnlineResourceType.NCSS;
}
return OnlineResourceType.Unsupported;
}
public boolean accept(CSWRecordsFilterVisitor visitor) {
return visitor.visit(this);
}
}
| lgpl-3.0 |
adrienlauer/kernel | core/src/main/java/io/nuun/kernel/core/internal/KernelGuiceModuleInternal.java | 11488 | /**
* Copyright (C) 2013-2014 Kametic <epo.jemba@kametic.com>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* or any later version
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.nuun.kernel.core.internal;
import static org.reflections.ReflectionUtils.withAnnotation;
import io.nuun.kernel.api.di.UnitModule;
import io.nuun.kernel.api.plugin.context.Context;
import io.nuun.kernel.core.KernelException;
import io.nuun.kernel.core.internal.context.ContextInternal;
import io.nuun.kernel.core.internal.context.InitContextInternal;
import io.nuun.kernel.spi.Concern;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.AbstractModule;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.matcher.Matchers;
import com.google.inject.util.Providers;
/**
* Bootstrap Plugin needed to initialize an application. Propose
*
* @author ejemba
*/
public class KernelGuiceModuleInternal extends AbstractModule
{
private Logger logger = LoggerFactory.getLogger(KernelGuiceModuleInternal.class);
private final InitContextInternal currentContext;
private boolean overriding = false;
public KernelGuiceModuleInternal(InitContextInternal kernelContext)
{
currentContext = kernelContext;
}
public KernelGuiceModuleInternal overriding()
{
overriding = true;
return this;
}
@Override
protected final void configure()
{
// All bindings will be needed explicitly.
// this simple line makes the framework bullet-proof !
binder().requireExplicitBindings();
// We ContextInternal as implementation of Context
bind(Context.class).to(ContextInternal.class);
// Bind Types, Subtypes from classpath
// ===================================
bindFromClasspath();
// Start Plugins
}
@SuppressWarnings({
"unchecked", "rawtypes"
})
private void bindFromClasspath()
{
List<Installable> installableList = new ArrayList<Installable>();
Map<Class<?>, Object> classesWithScopes = currentContext.classesWithScopes();
if (! overriding )
{
Collection<Class<?>> classes = currentContext.classesToBind();
for (Object o : classes)
{
installableList.add(new Installable(o));
}
for (Object o : currentContext.moduleResults())
{
installableList.add(new Installable(o));
}
}
else
{
logger.info("Installing overriding modules");
for (Object o : currentContext.moduleOverridingResults())
{
installableList.add(new Installable(o));
}
}
Collections.sort(installableList , Collections.reverseOrder());
Provider nullProvider = Providers.of(null);
// We install modules and bind class in the right orders
for (Installable installable : installableList)
{
Object installableInner = installable.inner;
// Checking for Module
if (UnitModule.class.isAssignableFrom(installableInner.getClass()) )
{ // install module
Object moduleObject = UnitModule.class.cast(installableInner).nativeModule();
if (Module.class.isAssignableFrom( moduleObject.getClass()) )
{
logger.info("installing module {}", moduleObject);
install(Module.class.cast(moduleObject));
}
else
{
throw new KernelException("Can not install " + moduleObject +". It is not a Guice Module");
}
}
// Checking for class
if (installableInner instanceof Class)
{ // bind object
Class<?> classpathClass = Class.class.cast(installableInner);
Object scope = classesWithScopes.get(classpathClass);
if (!(classpathClass.isInterface() && withAnnotation(Nullable.class).apply(classpathClass)))
{
if (scope == null)
{
logger.info("binding {} with no scope.", classpathClass.getName());
bind(classpathClass);
}
else
{
logger.info("binding {} in scope {}.", classpathClass.getName() , scope.toString());
bind(classpathClass).in((Scope) scope);
}
}
else
{
bind(classpathClass).toProvider(nullProvider);
}
}
}
}
class Installable implements Comparable<Installable>
{
Object inner;
Installable (Object inner)
{
this.inner = inner;
}
@Override
public int compareTo(Installable anInstallable)
{
Class<?> toCompare;
Class<?> innerClass;
// to compare inner is a class to bind
if (anInstallable.inner instanceof Class)
{
toCompare = (Class<?>) anInstallable.inner;
}
else if (Module.class.isAssignableFrom(anInstallable.inner.getClass()))
// inner is a module annotated
{
toCompare = anInstallable.inner.getClass();
}
else if (UnitModule.class.isAssignableFrom(anInstallable.inner.getClass()))
// inner is a UnitModule, we get the class of the wrapper
{
toCompare = UnitModule.class.cast(anInstallable.inner).nativeModule().getClass();
}
else
{
throw new IllegalStateException("Object to compare is not a class nor a Module " + anInstallable);
}
// inner is a class to bind
if (inner instanceof Class)
{
innerClass = (Class<?>) inner;
}
else if (Module.class.isAssignableFrom(inner.getClass()))
// inner is a module annotated
{
innerClass = inner.getClass();
}
else if (UnitModule.class.isAssignableFrom(inner.getClass()))
// inner is a UnitModule, we get the class of the wrapper
{
innerClass = UnitModule.class.cast(inner).nativeModule().getClass();
}
else
{
throw new IllegalStateException("Object to compare is not a class nor a Module " + this);
}
return computeOrder(innerClass).compareTo( computeOrder(toCompare) ) ;
}
@Override
public String toString()
{
return inner.toString();
}
}
Long computeOrder (Class<?> moduleCläss) {
Long finalOrder = 0l;
boolean reachAtLeastOnce = false;
for(Annotation annotation : moduleCläss.getAnnotations())
{
if ( Matchers.annotatedWith(Concern.class).matches(annotation.annotationType()) )
{
reachAtLeastOnce = true;
Concern concern = annotation.annotationType().getAnnotation(Concern.class);
switch (concern.priority())
{
case HIGHEST:
finalOrder += (3L << 32) + concern.order();
break;
case HIGHER:
finalOrder += (2L << 32) + concern.order();
break;
case HIGH:
finalOrder += (1L << 32) + concern.order();
break;
case NORMAL:
finalOrder = (long)concern.order();
break;
case LOW:
finalOrder -= (1L << 32) + concern.order();
break;
case LOWER:
finalOrder -= (2L << 32) + concern.order();
break;
case LOWEST:
finalOrder -= (3L << 32) + concern.order();
break;
default:
break;
}
break;
}
}
if (! reachAtLeastOnce) {
finalOrder = (long) 0;
}
return finalOrder;
}
public static boolean hasAnnotationDeep(Class<?> memberDeclaringClass, Class<? extends Annotation> klass)
{
if (memberDeclaringClass.equals(klass))
{
return true;
}
for (Annotation anno : memberDeclaringClass.getAnnotations())
{
Class<? extends Annotation> annoClass = anno.annotationType();
if (!annoClass.getPackage().getName().startsWith("java.lang") && hasAnnotationDeep(annoClass, klass))
{
return true;
}
}
return false;
}
// private void configureProperties()
// {
//
// // find all properties classes in the classpath
// Collection<String> propertiesFiles = this.currentContext.propertiesFiles();
//
// // add properties from plugins
// CompositeConfiguration configuration = new CompositeConfiguration();
// for (String propertiesFile : propertiesFiles)
// {
// logger.info("adding {} to module", propertiesFile);
// configuration.addConfiguration(configuration(propertiesFile));
// }
// install(new ConfigurationGuiceModule(configuration));
// }
// protected void bindSubTypesOf(Class<?> cläss)
// {
// this.currentContext.parentTypesClasses.add(cläss);
// }
//
// protected void bindAnnotationClass(Class<? extends Annotation> cläss)
// {
// this.currentContext.annotationTypes.add(cläss);
// }
//
// protected void bindAnnotationName(String className)
// {
// this.currentContext.annotationNames.add(className);
// }
}
| lgpl-3.0 |
ds84182/OpenGX | src/main/java/ds/mods/opengx/gx/tier1/GXMap.java | 914 | package ds.mods.opengx.gx.tier1;
import com.google.common.io.ByteArrayDataInput;
public class GXMap
{
public short width;
public short height;
public short x;
public short y;
public short tileOffset;
public int color;
public short[] data;
public boolean finished = false;
public int dataidx = 0;
public GXMap(short w, short h, ByteArrayDataInput fifo)
{
width = w;
height = h;
data = new short[w*h];
color = 0xFFFFFFFF;
if (fifo != null)
feed(fifo);
else
finished = true;
}
public void feed(ByteArrayDataInput fifo) {
short damnt = fifo.readShort();
for (int i=0; i<damnt; i++)
{
data[dataidx++] = (short) (fifo.readByte() & 0xFF); //make it unsigned
}
finished = dataidx<data.length;
}
public short getTile(short x, short y)
{
return (short) (data[(y*width)+x]+tileOffset);
}
public void setTile(short x, short y, short t)
{
data[(y*width)+x] = t;
}
} | lgpl-3.0 |
sfera-labs/sfera | src/main/java/cc/sferalabs/sfera/time/Scheduler.java | 8440 | /*-
* +======================================================================+
* Sfera
* ---
* Copyright (C) 2015 - 2016 Sfera Labs S.r.l.
* ---
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* -======================================================================-
*/
package cc.sferalabs.sfera.time;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
import java.util.ArrayList;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.GroupMatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cc.sferalabs.sfera.core.services.AutoStartService;
import cc.sferalabs.sfera.events.Node;
/**
*
* @author Giampiero Baggiani
*
* @version 1.0.0
*
*/
public class Scheduler extends Node implements AutoStartService {
private static final Logger logger = LoggerFactory.getLogger(Scheduler.class);
private static final AtomicLong counter = new AtomicLong(0);
private static org.quartz.Scheduler quartzScheduler;
private static Scheduler instance;
/**
*
*/
public Scheduler() {
super("scheduler");
instance = this;
}
/**
* @return the Scheduler instance
*/
public static Scheduler getInstance() {
return instance;
}
@Override
public void init() throws Exception {
// The quartz scheduler is only initialized when the first job is
// scheduled (see getScheduler()).
// This is an AutoStartService just because we need to add the
// "scheduler" node, which is done in the constructor.
}
@Override
public void quit() throws Exception {
destroy();
if (quartzScheduler != null) {
quartzScheduler.shutdown();
}
instance = null;
}
/**
*
* @return
*/
private static org.quartz.Scheduler getScheduler() {
if (quartzScheduler != null) {
return quartzScheduler;
}
synchronized (instance) {
if (quartzScheduler == null) {
try {
SchedulerFactory schedFact = new StdSchedulerFactory();
quartzScheduler = schedFact.getScheduler();
quartzScheduler.start();
} catch (SchedulerException e) {
logger.error("Error instantiating Scheduler", e);
}
}
return quartzScheduler;
}
}
/**
*
* @param trigger
* @throws SchedulerException
*/
private static void scheduleEvent(Trigger trigger) throws SchedulerException {
JobDetail eventJob = newJob(TriggerEventJob.class).build();
getScheduler().scheduleJob(eventJob, trigger);
}
/**
*
* @param id
* @param value
* @return
*/
private static TriggerBuilder<Trigger> newEventTrigger(String id, String value) {
return newTrigger().withIdentity(Long.toString(counter.getAndIncrement()), id).usingJobData("id", id)
.usingJobData("val", value);
}
/**
* Schedules an event to be triggered with the specified delay after this
* method has been called.
*
* @param id
* ID of the event to trigger
* @param value
* value of the event to trigger
* @param delay
* delay in milliseconds after which the event will be triggered
* @throws SchedulerException
* if an error occurs
*/
public void delay(String id, String value, int delay) throws SchedulerException {
Trigger trigger = newEventTrigger(id, value).startAt(futureDate(delay, IntervalUnit.MILLISECOND)).build();
scheduleEvent(trigger);
}
/**
* Schedules a set of events to be triggered with an initial delay from this
* method call and a regular interval between events. Events will continue
* until explicitly {@link #cancel(String) cancelled}.
*
* @param id
* ID of the event to trigger
* @param value
* value of the event to trigger
* @param initialDelay
* delay in milliseconds after which the first event will be
* triggered
* @param interval
* interval in milliseconds of the subsequent events
* @throws SchedulerException
* if an error occurs
*/
public void repeat(String id, String value, int initialDelay, int interval) throws SchedulerException {
Trigger trigger = newEventTrigger(id, value).startAt(futureDate(initialDelay, IntervalUnit.MILLISECOND))
.withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).repeatForever()).build();
scheduleEvent(trigger);
}
/**
* Schedules a fixed number of events to be triggered with an initial delay
* from this method call and a regular interval between events. Events will
* continue until the specified number of events have been triggered or
* explicitly {@link #cancel(String) cancelled}.
*
* @param id
* ID of the event to trigger
* @param value
* value of the event to trigger
* @param initialDelay
* delay in milliseconds after which the first event will be
* triggered
* @param interval
* interval in milliseconds of the subsequent events
* @param times
* number of triggered events
* @throws SchedulerException
* if an error occurs
*/
public void repeat(String id, String value, int initialDelay, int interval, int times) throws SchedulerException {
Trigger trigger = newEventTrigger(id, value).startAt(futureDate(initialDelay, IntervalUnit.MILLISECOND))
.withSchedule(simpleSchedule().withIntervalInMilliseconds(interval).withRepeatCount(times - 1)).build();
scheduleEvent(trigger);
}
/**
* Schedules events to be triggered following a cron expression.
* <p>
* The {@code cronExpression} String shall have the following format: <br>
* {@code
* "<seconds> <minutes> <hours> <day-of-month> <month> <day-of-week> <year>"
* }
* <p>
* The fields are separated by spaces, the {@code <year>} field is optional.
* <p>
* Examples:<br>
*
* Every 5 minutes: {@code "0 0/5 * * * ?"}<br>
* Every 5 minutes, at 10 seconds after the minute (e.g. 10:00:10 am,
* 10:05:10 am, etc.): {@code "10 0/5 * * * ?"}<br>
* At 10:30, 11:30, 12:30, and 13:30, on every Wednesday and Friday:
* {@code "0 30 10-13 ? * WED,FRI"}<br>
* Every half hour between the hours of 8 am and 10 am on the 5th and 20th
* of every month: {@code "0 0/30 8-9 5,20 * ?"}<br>
*
* @param cronExpression
* cron expression
* @param id
* ID of the event to trigger
* @param value
* value of the event to trigger
* @throws SchedulerException
* if an error occurs
* @see <a href=
* "http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html">http://www.quartz-scheduler.org/documentation/quartz-2.x/tutorials/crontrigger.html</a>
*/
public void addCronRule(String cronExpression, String id, String value) throws SchedulerException {
Trigger trigger = newEventTrigger(id, value).withSchedule(cronSchedule(cronExpression)).build();
scheduleEvent(trigger);
}
/**
* Cancel the previously scheduled events with the specified ID.
*
* @param id
* ID of the event(s) to cancel
*/
public void cancel(String id) {
try {
org.quartz.Scheduler sched = getScheduler();
Set<TriggerKey> keys = sched.getTriggerKeys(GroupMatcher.groupEquals(id));
sched.unscheduleJobs(new ArrayList<TriggerKey>(keys));
} catch (SchedulerException e) {
logger.error("Error canceling event jobs: " + id, e);
}
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicateTest.java | 1827 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.ce.task.projectanalysis.duplication;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import static org.assertj.core.api.Assertions.assertThat;
public class DuplicateTest {
@Test
public void duplicate_implementations_are_not_equals_to_each_other_even_if_TextBlock_is_the_same() {
TextBlock textBlock = new TextBlock(1, 2);
InnerDuplicate innerDuplicate = new InnerDuplicate(textBlock);
InProjectDuplicate inProjectDuplicate = new InProjectDuplicate(ReportComponent.builder(Component.Type.FILE, 1).build(), textBlock);
CrossProjectDuplicate crossProjectDuplicate = new CrossProjectDuplicate("file key", textBlock);
assertThat(innerDuplicate.equals(inProjectDuplicate)).isFalse();
assertThat(innerDuplicate.equals(crossProjectDuplicate)).isFalse();
assertThat(inProjectDuplicate.equals(crossProjectDuplicate)).isFalse();
}
}
| lgpl-3.0 |
RockBottomGame/API | src/main/java/de/ellpeck/rockbottom/api/render/engine/IDisposable.java | 1030 | /*
* This file ("IDisposable.java") is part of the RockBottomAPI by Ellpeck.
* View the source code at <https://github.com/RockBottomGame/>.
* View information on the project at <https://rockbottom.ellpeck.de/>.
*
* The RockBottomAPI is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The RockBottomAPI 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with the RockBottomAPI. If not, see <http://www.gnu.org/licenses/>.
*
* © 2018 Ellpeck
*/
package de.ellpeck.rockbottom.api.render.engine;
public interface IDisposable {
void dispose();
}
| lgpl-3.0 |
cismet/watergis-client | src/main/java/de/cismet/watergis/broker/listener/DrawingCountChangedEvent.java | 791 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package de.cismet.watergis.broker.listener;
import java.util.EventObject;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class DrawingCountChangedEvent extends EventObject {
//~ Constructors -----------------------------------------------------------
/**
* Creates a new SelectionModeChangedEvent object.
*
* @param source DOCUMENT ME!
*/
public DrawingCountChangedEvent(final Object source) {
super(source);
}
}
| lgpl-3.0 |
skltp-incubator/axel | riv-shs/bridge/src/main/java/se/inera/axel/riv/internal/FileNameProcessor.java | 1523 | package se.inera.axel.riv.internal;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Processor;
import org.apache.camel.spi.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.inera.axel.riv.RivShsMappingService;
import se.inera.axel.shs.processor.ShsHeaders;
public class FileNameProcessor implements Processor {
private static final Logger log = LoggerFactory.getLogger(FileNameProcessor.class);
private static final String DEFAULT_FILENAME = "req-.xml";
final static String HEADER_FILENAME = String.format("req-${in.header.%s}.xml", RivShsMappingService.HEADER_RIV_CORRID);
@Override
public void process(Exchange exchange) throws Exception {
CamelContext context = exchange.getContext();
Language language = context.resolveLanguage("simple");
String value;
String fileNameTemplate = exchange.getProperty(ShsHeaders.X_SHS_FILETEMPLATE, String.class);
if(fileNameTemplate == null || fileNameTemplate.length()==0)
value = DEFAULT_FILENAME;
else {
Expression expression;
try {
expression = language.createExpression(fileNameTemplate);
value = expression.evaluate(exchange, String.class);
} catch (RuntimeException e) {
log.warn("Can not parse filename template {}. Will use default name. Error is {}", fileNameTemplate, e.getMessage());
value = DEFAULT_FILENAME;
}
}
exchange.getIn().setHeader(ShsHeaders.DATAPART_FILENAME, value);
}
} | lgpl-3.0 |
Godin/sonar | plugins/sonar-xoo-plugin/src/main/java/org/sonar/xoo/scm/XooIgnoreCommand.java | 2037 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.xoo.scm;
import java.io.File;
import java.nio.file.Path;
import org.apache.commons.io.FilenameUtils;
import org.sonar.api.batch.scm.IgnoreCommand;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
/**
* To ignore a file simply add an empty file with the same name as the file to ignore with a .ignore suffix.
* E.g. to ignore src/foo.xoo create the file src/foo.xoo.ignore
*/
public class XooIgnoreCommand implements IgnoreCommand {
static final String IGNORE_FILE_EXTENSION = ".ignore";
private static final Logger LOG = Loggers.get(XooIgnoreCommand.class);
private boolean isInit;
@Override
public boolean isIgnored(Path path) {
if (!isInit) {
throw new IllegalStateException("Called init() first");
}
String fullPath = FilenameUtils.getFullPath(path.toAbsolutePath().toString());
File scmIgnoreFile = new File(fullPath, path.getFileName() + IGNORE_FILE_EXTENSION);
return scmIgnoreFile.exists();
}
@Override
public void init(Path baseDir) {
isInit = true;
LOG.debug("Init IgnoreCommand on dir '{}'");
}
@Override
public void clean() {
LOG.debug("Clean IgnoreCommand");
}
}
| lgpl-3.0 |
fuinorg/kickstart4j | src/main/java/org/fuin/kickstart4j/InvalidConfigException.java | 1567 | /**
* Copyright (C) 2009 Future Invent Informationsmanagement GmbH. All rights
* reserved. <http://www.fuin.org/>
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later version.
*
* This library 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fuin.kickstart4j;
import java.net.URL;
/**
* A configuration is invalid.
*/
public final class InvalidConfigException extends Exception {
private static final long serialVersionUID = 1L;
/**
* Constructor with message.
*
* @param msg
* Message.
*/
public InvalidConfigException(final String msg) {
super(msg);
}
/**
* Constructor with URL and cause.
*
* @param url
* URL with the XML config.
* @param cause
* Cause for the problem.
*/
public InvalidConfigException(final URL url, final Throwable cause) {
super("Error parsing configuration '" + url + "'!", cause);
}
}
| lgpl-3.0 |
MinecraftModArchive/Runes-And-Silver | src/main/java/Runes/ForestTreeLog.java | 6099 | /*
* Copyright (c) 2014 Silas Otoko.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option) any
* later 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, see <http://www.gnu.org/licenses>.
*/
package runes.Runes;
import java.util.List;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.BlockRotatedPillar;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ForestTreeLog extends BlockRotatedPillar
{
/* * The type of tree this log came from. */
public static final String[] woodType = new String[] {"Rune"};
@SideOnly(Side.CLIENT)
private Icon[] field_111052_c;
@SideOnly(Side.CLIENT)
private Icon[] tree_top;
protected ForestTreeLog(int par1, int par2)
{
super(par1, Material.wood);
this.setCreativeTab(RunesAndSilver.tabRunesMod);
}
@SideOnly(Side.CLIENT)
/**
* The icon for the side of the block.
*/
protected Icon getSideIcon(int par1)
{
return this.field_111052_c[par1];
}
@SideOnly(Side.CLIENT)
/**
* The icon for the tops and bottoms of the block.
*/
protected Icon getEndIcon(int par1)
{
return this.tree_top[par1];
}
@SideOnly(Side.CLIENT)
/**
* When this method is called, your block should register all the icons it needs with the given IconRegister. This
* is the only chance you get to register icons.
*/
public void registerIcons(IconRegister par1IconRegister)
{
this.field_111052_c = new Icon[woodType.length];
this.tree_top = new Icon[woodType.length];
for (int i = 0; i < this.field_111052_c.length; ++i)
{
this.field_111052_c[i] = par1IconRegister.registerIcon(RunesAndSilver.modid + ":log_" + woodType[i]);
this.tree_top[i] = par1IconRegister.registerIcon(RunesAndSilver.modid + ":log_" + woodType[i] + "_top");
}
}
/**
* The type of render function that is called for this block
*/
public int getRenderType()
{
return 31;
}
/**
* Returns the quantity of items to drop on block destruction.
*/
public int quantityDropped(Random par1Random)
{
return 1;
}
/**
* Returns the ID of the items to drop on destruction.
*/
public int idDropped(int par1, Random par2Random, int par3)
{
return this.blockID;
}
/**
* ejects contained items into the world, and notifies neighbours of an update, as appropriate
*/
public void breakBlock(World par1World, int par2, int par3, int par4, int par5, int par6)
{
byte b0 = 4;
int j1 = b0 + 1;
if (par1World.checkChunksExist(par2 - j1, par3 - j1, par4 - j1, par2 + j1, par3 + j1, par4 + j1))
{
for (int k1 = -b0; k1 <= b0; ++k1)
{
for (int l1 = -b0; l1 <= b0; ++l1)
{
for (int i2 = -b0; i2 <= b0; ++i2)
{
int j2 = par1World.getBlockId(par2 + k1, par3 + l1, par4 + i2);
if (Block.blocksList[j2] != null)
{
Block.blocksList[j2].beginLeavesDecay(par1World, par2 + k1, par3 + l1, par4 + i2);
}
}
}
}
}
}
/**
* Called when a block is placed using its ItemBlock. Args: World, X, Y, Z, side, hitX, hitY, hitZ, block metadata
*/
public int onBlockPlaced(World par1World, int par2, int par3, int par4, int par5, float par6, float par7, float par8, int par9)
{
int j1 = par9 & 3;
byte b0 = 0;
switch (par5)
{
case 0:
case 1:
b0 = 0;
break;
case 2:
case 3:
b0 = 8;
break;
case 4:
case 5:
b0 = 4;
}
return j1 | b0;
}
@SideOnly(Side.CLIENT)
/**
* Determines the damage on the item the block drops. Used in cloth and wood.
*/
public int damageDropped(int par1)
{
return par1 & 3;
}
/**
* returns a number between 0 and 3
*/
public static int limitToValidMetadata(int par0)
{
return par0 & 3;
}
@SideOnly(Side.CLIENT)
/**
* returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks)
*/
public void getSubBlocks(int par1, CreativeTabs par2CreativeTabs, List par3List)
{
par3List.add(new ItemStack(par1, 1, 0));
}
/**
* Returns an item stack containing a single instance of the current block type. 'i' is the block's subtype/damage
* and is ignored for blocks which do not support subtypes. Blocks which cannot be harvested should return null.
*/
protected ItemStack createStackedBlock(int par1)
{
return new ItemStack(this.blockID, 1, limitToValidMetadata(par1));
}
@Override
public boolean canSustainLeaves(World world, int x, int y, int z)
{
return true;
}
@Override
public boolean isWood(World world, int x, int y, int z)
{
return true;
}
}
| lgpl-3.0 |
hea3ven/BuildCraft | common/buildcraft/builders/BlockMarker.java | 4795 | /**
* Copyright (c) 2011-2015, SpaceToad and the BuildCraft Team
* http://www.mod-buildcraft.com
*
* BuildCraft is distributed under the terms of the Minecraft Mod Public
* License 1.0, or MMPL. Please check the contents of the license located in
* http://www.mod-buildcraft.com/MMPL-1.0.txt
*/
package buildcraft.builders;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import buildcraft.BuildCraftCore;
import buildcraft.api.items.IMapLocation;
import buildcraft.core.BCCreativeTab;
import buildcraft.core.lib.block.BlockBuildCraft;
public class BlockMarker extends BlockBuildCraft {
public BlockMarker() {
super(Material.circuits);
setLightLevel(0.5F);
setHardness(0.0F);
setCreativeTab(BCCreativeTab.get("main"));
}
public static boolean canPlaceTorch(World world, int x, int y, int z, ForgeDirection side) {
Block block = world.getBlock(x, y, z);
return block != null && (block.renderAsNormalBlock() && block.isOpaqueCube() || block.isSideSolid(world, x, y, z, side));
}
private AxisAlignedBB getBoundingBox(int meta) {
double w = 0.15;
double h = 0.65;
ForgeDirection dir = ForgeDirection.getOrientation(meta);
switch (dir) {
case DOWN:
return AxisAlignedBB.getBoundingBox(0.5F - w, 1F - h, 0.5F - w, 0.5F + w, 1F, 0.5F + w);
case UP:
return AxisAlignedBB.getBoundingBox(0.5F - w, 0F, 0.5F - w, 0.5F + w, h, 0.5F + w);
case SOUTH:
return AxisAlignedBB.getBoundingBox(0.5F - w, 0.5F - w, 0F, 0.5F + w, 0.5F + w, h);
case NORTH:
return AxisAlignedBB.getBoundingBox(0.5F - w, 0.5F - w, 1 - h, 0.5F + w, 0.5F + w, 1);
case EAST:
return AxisAlignedBB.getBoundingBox(0F, 0.5F - w, 0.5F - w, h, 0.5F + w, 0.5F + w);
default:
return AxisAlignedBB.getBoundingBox(1 - h, 0.5F - w, 0.5F - w, 1F, 0.5F + w, 0.5F + w);
}
}
@Override
public AxisAlignedBB getSelectedBoundingBoxFromPool(World world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
AxisAlignedBB bBox = getBoundingBox(meta);
bBox.offset(x, y, z);
return bBox;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
AxisAlignedBB bb = getBoundingBox(meta);
setBlockBounds((float) bb.minX, (float) bb.minY, (float) bb.minZ, (float) bb.maxX, (float) bb.maxY, (float) bb.maxZ);
}
@Override
public int getRenderType() {
return BuildCraftCore.markerModel;
}
@Override
public TileEntity createNewTileEntity(World world, int metadata) {
return new TileMarker();
}
@Override
public boolean onBlockActivated(World world, int i, int j, int k, EntityPlayer entityplayer, int par6, float par7, float par8, float par9) {
if (super.onBlockActivated(world, i, j, k, entityplayer, par6, par7, par8, par9)) {
return true;
}
if (entityplayer.inventory.getCurrentItem() != null
&& entityplayer.inventory.getCurrentItem().getItem() instanceof IMapLocation) {
return false;
}
if (entityplayer.isSneaking()) {
return false;
}
TileEntity tile = world.getTileEntity(i, j, k);
if (tile instanceof TileMarker) {
((TileMarker) tile).tryConnection();
return true;
}
return false;
}
@Override
public AxisAlignedBB getCollisionBoundingBoxFromPool(World world, int i, int j, int k) {
return null;
}
@Override
public boolean isOpaqueCube() {
return false;
}
@Override
public boolean renderAsNormalBlock() {
return false;
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, Block block) {
TileEntity tile = world.getTileEntity(x, y, z);
if (tile instanceof TileMarker) {
((TileMarker) tile).updateSignals();
}
dropTorchIfCantStay(world, x, y, z);
}
@Override
public boolean canPlaceBlockOnSide(World world, int x, int y, int z, int side) {
ForgeDirection dir = ForgeDirection.getOrientation(side);
return canPlaceTorch(world, x - dir.offsetX, y - dir.offsetY, z - dir.offsetZ, dir);
}
@Override
public int onBlockPlaced(World world, int x, int y, int z, int side, float par6, float par7, float par8, int meta) {
return side;
}
@Override
public void onBlockAdded(World world, int x, int y, int z) {
super.onBlockAdded(world, x, y, z);
dropTorchIfCantStay(world, x, y, z);
}
private void dropTorchIfCantStay(World world, int x, int y, int z) {
int meta = world.getBlockMetadata(x, y, z);
if (!canPlaceBlockOnSide(world, x, y, z, meta)) {
dropBlockAsItem(world, x, y, z, 0, 0);
world.setBlockToAir(x, y, z);
}
}
}
| lgpl-3.0 |
premium-minds/billy | billy-france/src/test/java/com/premiumminds/billy/france/test/util/FRBusinessTestUtil.java | 4006 | /*
* Copyright (C) 2017 Premium Minds.
*
* This file is part of billy france (FR Pack).
*
* billy france (FR Pack) is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* billy france (FR Pack) 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 Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with billy france (FR Pack). If not, see <http://www.gnu.org/licenses/>.
*/
package com.premiumminds.billy.france.test.util;
import java.net.MalformedURLException;
import javax.persistence.NoResultException;
import com.google.inject.Injector;
import com.premiumminds.billy.core.services.UID;
import com.premiumminds.billy.france.persistence.dao.DAOFRBusiness;
import com.premiumminds.billy.france.persistence.entities.FRBusinessEntity;
import com.premiumminds.billy.france.services.entities.FRAddress;
import com.premiumminds.billy.france.services.entities.FRApplication;
import com.premiumminds.billy.france.services.entities.FRBusiness;
import com.premiumminds.billy.france.services.entities.FRContact;
import com.premiumminds.billy.france.services.entities.FRRegionContext;
import com.premiumminds.billy.france.util.Contexts;
public class FRBusinessTestUtil {
private static final String NAME = "Business";
private static final String FINANCIAL_ID = "829128768";
private static final String WEBSITE = "http://business.com";
protected static final String FR_COUNTRY_CODE = "FR";
private Injector injector;
private FRApplicationTestUtil application;
private FRContactTestUtil contact;
private FRAddressTestUtil address;
private FRRegionContext context;
public FRBusinessTestUtil(Injector injector) {
this.injector = injector;
this.application = new FRApplicationTestUtil(injector);
this.contact = new FRContactTestUtil(injector);
this.address = new FRAddressTestUtil(injector);
this.context = new Contexts(injector).france().allRegions();
}
public FRBusinessEntity getBusinessEntity() {
return this.getBusinessEntity(new UID().toString());
}
public FRBusinessEntity getBusinessEntity(String uid) {
FRBusinessEntity business = null;
try {
business = this.injector.getInstance(DAOFRBusiness.class).get(new UID(uid));
} catch (NoResultException e) {
business = (FRBusinessEntity) this.getBusinessBuilder().build();
business.setUID(new UID(uid));
this.injector.getInstance(DAOFRBusiness.class).create(business);
}
return business;
}
public FRBusiness.Builder getBusinessBuilder() {
FRBusiness.Builder businessBuilder = this.injector.getInstance(FRBusiness.Builder.class);
FRApplication.Builder applicationBuilder = null;
try {
applicationBuilder = this.application.getApplicationBuilder();
} catch (MalformedURLException e) {
e.printStackTrace();
}
FRContact.Builder contactBuilder = this.contact.getContactBuilder();
FRAddress.Builder addressBuilder = this.address.getAddressBuilder();
businessBuilder.addApplication(applicationBuilder).addContact(contactBuilder, true).setAddress(addressBuilder)
.setBillingAddress(addressBuilder).setCommercialName(FRBusinessTestUtil.NAME)
.setFinancialID(FRBusinessTestUtil.FINANCIAL_ID, FRBusinessTestUtil.FR_COUNTRY_CODE)
.setOperationalContextUID(this.context.getUID()).setWebsite(FRBusinessTestUtil.WEBSITE)
.setName(FRBusinessTestUtil.NAME);
return businessBuilder;
}
}
| lgpl-3.0 |
jplot2d/jplot2d | jplot2d-core/src/main/java/org/jplot2d/element/TextComponent.java | 2607 | /*
* Copyright 2010 Jingjing Li.
*
* This file is part of jplot2d.
*
* jplot2d is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* jplot2d 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with jplot2d. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jplot2d.element;
import org.jplot2d.annotation.Property;
import org.jplot2d.annotation.PropertyGroup;
/**
* A component who represent a text string. The text string can be a math element.
*
* @author Jingjing Li
*/
@PropertyGroup("Text")
public interface TextComponent extends PComponent {
/**
* Returns the text string.
*
* @return a String
*/
@Property(order = 0, description = "Can be TeX math string", styleable = false)
String getText();
/**
* Defines the text to be displayed. The text can be multi-line, splited by \n.
* The string of every line can be in TeX-like syntax. A pair of "$" mark into math mode and out math mode.
* In math mode, Greek letter can be inputed as \alpha, \beta, etc.
* Superscripts (up high) and subscripts (down low) can be inputed by using "^" and "_".
* Notice that ^ and _ apply only to the next single character.
* If you want several things to be superscripted or subscripted, just enclose them in braces. eg:
* "plain text $x_\alpha^{2y}$".
*
* @param text the text to be displayed
*/
void setText(String text);
/**
* @return the horizontal alignment.
*/
@Property(order = 1)
HAlign getHAlign();
/**
* Set the horizontal alignment. The alignment can be LEFT, CENTER, or RIGHT.
* eg, LEFT means the title is on the left of the base point.
*
* @param hAlign the horizontal alignment.
*/
void setHAlign(HAlign hAlign);
/**
* @return the vertical alignment or null if not set.
*/
@Property(order = 2)
VAlign getVAlign();
/**
* Set the vertical alignment. The alignment can be TOP, MIDDLE, or BOTTOM.
* eg, TOP means the title is on the top of the base point
*
* @param vAlign the vertical alignment.
*/
void setVAlign(VAlign vAlign);
}
| lgpl-3.0 |
jussenadv/ij1Android | src/ij/plugin/BatchProcesser.java | 12735 | package ij.plugin;
import ij.*;
import ij.process.*;
import ij.gui.*;
import ij.util.Tools;
import ij.io.OpenDialog;
import ij.macro.Interpreter;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Vector;
/** This plugin implements the File/Batch/Macro and File/Batch/Virtual Stack commands. */
public class BatchProcesser implements PlugIn, ActionListener, ItemListener, Runnable {
private static final String MACRO_FILE_NAME = "BatchMacro.ijm";
private static final String[] formats = {"TIFF", "8-bit TIFF", "JPEG", "GIF", "PNG", "PGM", "BMP", "FITS", "Text Image", "ZIP", "Raw"};
private static String format = Prefs.get("batch.format", formats[0]);
private static final String[] code = {
"[Select from list]",
"Add Border",
"Convert to RGB",
"Crop",
"Gaussian Blur",
"Invert",
"Label",
"Timestamp",
"Max Dimension",
"Measure",
"Resize",
"Scale",
"Show File Info",
"Unsharp Mask",
};
private String macro = "";
private int testImage;
private Button input, output, open, save, test;
private TextField inputDir, outputDir;
private GenericDialog gd;
private Thread thread;
private ImagePlus virtualStack;
public void run(String arg) {
if (arg.equals("stack")) {
virtualStack = IJ.getImage();
if (virtualStack.getStackSize()==1) {
error("This command requires a stack or virtual stack.");
return;
}
}
String macroPath = IJ.getDirectory("macros")+MACRO_FILE_NAME;
macro = IJ.openAsString(macroPath);
if (macro==null || macro.startsWith("Error: ")) {
IJ.showStatus(macro.substring(7) + ": "+macroPath);
macro = "";
}
if (!showDialog()) return;
String inputPath = null;
if (virtualStack==null) {
inputPath = inputDir.getText();
if (inputPath.equals("")) {
error("Please choose an input folder");
return;
}
inputPath = addSeparator(inputPath);
File f1 = new File(inputPath);
if (!f1.exists() || !f1.isDirectory()) {
error("Input does not exist or is not a folder\n \n"+inputPath);
return;
}
}
String outputPath = outputDir.getText();
outputPath = addSeparator(outputPath);
File f2 = new File(outputPath);
if (!outputPath.equals("") && (!f2.exists() || !f2.isDirectory())) {
error("Output does not exist or is not a folder\n \n"+outputPath);
return;
}
if (macro.equals("")) {
error("There is no macro code in the text area");
return;
}
ImageJ ij = IJ.getInstance();
if (ij!=null) ij.getProgressBar().setBatchMode(true);
IJ.resetEscape();
if (virtualStack!=null)
processVirtualStack(outputPath);
else
processFolder(inputPath, outputPath);
IJ.showProgress(1,1);
if (virtualStack==null)
Prefs.set("batch.input", inputDir.getText());
Prefs.set("batch.output", outputDir.getText());
Prefs.set("batch.format", format);
macro = gd.getTextArea1().getText();
if (!macro.equals(""))
IJ.saveString(macro, IJ.getDirectory("macros")+MACRO_FILE_NAME);
}
boolean showDialog() {
validateFormat();
gd = new NonBlockingGenericDialog("Batch Process");
addPanels(gd);
gd.setInsets(15, 0, 5);
gd.addChoice("Output Format:", formats, format);
gd.setInsets(0, 0, 5);
gd.addChoice("Add Macro Code:", code, code[0]);
gd.setInsets(15, 10, 0);
Dimension screen = IJ.getScreenSize();
gd.addTextAreas(macro, null, screen.width<=600?10:15, 60);
addButtons(gd);
gd.setOKLabel("Process");
Vector choices = gd.getChoices();
Choice choice = (Choice)choices.elementAt(1);
choice.addItemListener(this);
gd.showDialog();
format = gd.getNextChoice();
macro = gd.getNextText();
return !gd.wasCanceled();
}
void processVirtualStack(String outputPath) {
ImageStack stack = virtualStack.getStack();
int n = stack.getSize();
int index = 0;
for (int i=1; i<=n; i++) {
if (IJ.escapePressed()) break;
IJ.showProgress(i, n);
ImageProcessor ip = stack.getProcessor(i);
if (ip==null) return;
ImagePlus imp = new ImagePlus("", ip);
if (!macro.equals("")) {
if (!runMacro("i="+(index++)+";"+macro, imp))
break;
}
if (!outputPath.equals("")) {
if (format.equals("8-bit TIFF") || format.equals("GIF")) {
if (imp.getBitDepth()==24)
IJ.run(imp, "8-bit Color", "number=256");
else
IJ.run(imp, "8-bit", "");
}
IJ.saveAs(imp, format, outputPath+pad(i));
}
imp.close();
}
if (outputPath!=null && !outputPath.equals(""))
IJ.run("Image Sequence...", "open=[" + outputPath + "]"+" use");
}
String pad(int n) {
String str = ""+n;
while (str.length()<5)
str = "0" + str;
return str;
}
void processFolder(String inputPath, String outputPath) {
String[] list = (new File(inputPath)).list();
int index = 0;
for (int i=0; i<list.length; i++) {
if (IJ.escapePressed()) break;
String path = inputPath + list[i];
if (IJ.debugMode) IJ.log(i+": "+path);
if ((new File(path)).isDirectory())
continue;
if (list[i].startsWith(".")||list[i].endsWith(".avi")||list[i].endsWith(".AVI"))
continue;
IJ.showProgress(i+1, list.length);
ImagePlus imp = IJ.openImage(path);
if (imp==null) continue;
if (!macro.equals("")) {
if (!runMacro("i="+(index++)+";"+macro, imp))
break;
}
if (!outputPath.equals("")) {
if (format.equals("8-bit TIFF") || format.equals("GIF")) {
if (imp.getBitDepth()==24)
IJ.run(imp, "8-bit Color", "number=256");
else
IJ.run(imp, "8-bit", "");
}
IJ.saveAs(imp, format, outputPath+list[i]);
}
imp.close();
}
}
private boolean runMacro(String macro, ImagePlus imp) {
WindowManager.setTempCurrentImage(imp);
Interpreter interp = new Interpreter();
try {
interp.runBatchMacro(macro, imp);
} catch(Throwable e) {
interp.abortMacro();
String msg = e.getMessage();
if (!(e instanceof RuntimeException && msg!=null && e.getMessage().equals(Macro.MACRO_CANCELED)))
IJ.handleException(e);
return false;
}
return true;
}
String addSeparator(String path) {
if (path.equals("")) return path;
if (!(path.endsWith("/")||path.endsWith("\\")))
path = path + File.separator;
return path;
}
void validateFormat() {
boolean validFormat = false;
for (int i=0; i<formats.length; i++) {
if (format.equals(formats[i])) {
validFormat = true;
break;
}
}
if (!validFormat) format = formats[0];
}
void addPanels(GenericDialog gd) {
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
if (virtualStack==null) {
input = new Button("Input...");
input.addActionListener(this);
p.add(input);
inputDir = new TextField(Prefs.get("batch.input", ""), 45);
p.add(inputDir);
gd.addPanel(p);
}
p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
output = new Button("Output...");
output.addActionListener(this);
p.add(output);
outputDir = new TextField(Prefs.get("batch.output", ""), 45);
p.add(outputDir);
gd.addPanel(p);
}
void addButtons(GenericDialog gd) {
Panel p = new Panel();
p.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 0));
test = new Button("Test");
test.addActionListener(this);
p.add(test);
open = new Button("Open...");
open.addActionListener(this);
p.add(open);
save = new Button("Save...");
save.addActionListener(this);
p.add(save);
gd.addPanel(p);
}
public void itemStateChanged(ItemEvent e) {
Choice choice = (Choice)e.getSource();
String item = choice.getSelectedItem();
String code = null;
if (item.equals("Convert to RGB"))
code = "run(\"RGB Color\");\n";
else if (item.equals("Measure"))
code = "run(\"Measure\");\n";
else if (item.equals("Resize"))
code = "run(\"Size...\", \"width=512 height=512 interpolation=Bicubic\");\n";
else if (item.equals("Scale"))
code = "scale=1.5;\nw=getWidth*scale; h=getHeight*scale;\nrun(\"Size...\", \"width=w height=h interpolation=Bilinear\");\n";
else if (item.equals("Label"))
code = "setFont(\"SansSerif\", 18, \"antialiased\");\nsetColor(\"red\");\ndrawString(\"Hello\", 20, 30);\n";
else if (item.equals("Timestamp"))
code = openMacroFromJar("TimeStamp.ijm");
else if (item.equals("Crop"))
code = "makeRectangle(getWidth/4, getHeight/4, getWidth/2, getHeight/2);\nrun(\"Crop\");\n";
else if (item.equals("Add Border"))
code = "border=25;\nw=getWidth+border*2; h=getHeight+border*2;\nrun(\"Canvas Size...\", \"width=w height=h position=Center zero\");\n";
else if (item.equals("Invert"))
code = "run(\"Invert\");\n";
else if (item.equals("Gaussian Blur"))
code = "run(\"Gaussian Blur...\", \"sigma=2\");\n";
else if (item.equals("Unsharp Mask"))
code = "run(\"Unsharp Mask...\", \"radius=1 mask=0.60\");\n";
else if (item.equals("Show File Info"))
code = "path=File.directory+File.name;\ndate=File.dateLastModified(path);\nsize=File.length(path);\nprint(i+\", \"+getTitle+\", \"+date+\", \"+size);\n";
else if (item.equals("Max Dimension"))
code = "max=2048;\nw=getWidth; h=getHeight;\nsize=maxOf(w,h);\nif (size>max) {\n scale = max/size;\n w*=scale; h*=scale;\n run(\"Size...\", \"width=w height=h interpolation=Bicubic average\");\n}";
if (code!=null) {
TextArea ta = gd.getTextArea1();
ta.insert(code, ta.getCaretPosition());
if (IJ.isMacOSX()) ta.requestFocus();
}
}
String openMacroFromJar(String name) {
ImageJ ij = IJ.getInstance();
Class c = ij!=null?ij.getClass():(new ImageStack()).getClass();
String macro = null;
try {
InputStream is = c .getResourceAsStream("/macros/"+name);
if (is==null) return null;
InputStreamReader isr = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
char [] b = new char [8192];
int n;
while ((n = isr.read(b)) > 0)
sb.append(b,0, n);
macro = sb.toString();
}
catch (IOException e) {
return null;
}
return macro;
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source==input) {
String path = IJ.getDirectory("Input Folder");
if (path==null) return;
inputDir.setText(path);
if (IJ.isMacOSX())
{gd.setVisible(false); gd.setVisible(true);}
} else if (source==output) {
String path = IJ.getDirectory("Output Folder");
if (path==null) return;
outputDir.setText(path);
if (IJ.isMacOSX())
{gd.setVisible(false); gd.setVisible(true);}
} else if (source==test) {
thread = new Thread(this, "BatchTest");
thread.setPriority(Math.max(thread.getPriority()-2, Thread.MIN_PRIORITY));
thread.start();
} else if (source==open)
open();
else if (source==save)
save();
}
void open() {
String text = IJ.openAsString("");
if (text==null) return;
if (text.startsWith("Error: "))
error(text.substring(7));
else {
if (text.length()>30000)
error("File is too large");
else
gd.getTextArea1().setText(text);
}
}
void save() {
macro = gd.getTextArea1().getText();
if (!macro.equals(""))
IJ.saveString(macro, "");
}
void error(String msg) {
IJ.error("Batch Processer", msg);
}
public void run() {
TextArea ta = gd.getTextArea1();
//ta.selectAll();
String macro = ta.getText();
if (macro.equals("")) {
error("There is no macro code in the text area");
return;
}
ImagePlus imp = null;
if (virtualStack!=null)
imp = getVirtualStackImage();
else
imp = getFolderImage();
if (imp==null) return;
runMacro("i=0;"+macro, imp);
Point loc = new Point(10, 30);
if (testImage!=0) {
ImagePlus imp2 = WindowManager.getImage(testImage);
if (imp2!=null) {
ImageWindow win = imp2.getWindow();
if (win!=null) loc = win.getLocation();
imp2.changes=false;
imp2.close();
}
}
imp.show();
ImageWindow iw = imp.getWindow();
if (iw!=null) iw.setLocation(loc);
testImage = imp.getID();
}
ImagePlus getVirtualStackImage() {
ImagePlus imp = virtualStack.createImagePlus();
imp.setProcessor("", virtualStack.getProcessor().duplicate());
return imp;
}
ImagePlus getFolderImage() {
String inputPath = inputDir.getText();
inputPath = addSeparator(inputPath);
File f1 = new File(inputPath);
if (!f1.exists() || !f1.isDirectory()) {
error("Input does not exist or is not a folder\n \n"+inputPath);
return null;
}
String[] list = (new File(inputPath)).list();
String name = list[0];
if (name.startsWith(".")&&list.length>1) name = list[1];
String path = inputPath + name;
setDirAndName(path);
return IJ.openImage(path);
}
void setDirAndName(String path) {
File f = new File(path);
OpenDialog.setLastDirectory(f.getParent()+File.separator);
OpenDialog.setLastName(f.getName());
}
}
| lgpl-3.0 |
simonstey/SecureLinkedData | src/main/java/infobiz/wu/ac/at/sld/datatier/db/util/ObjectKeySerializer.java | 9598 | package infobiz.wu.ac.at.sld.datatier.db.util;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import org.mapdb.DBException;
import org.mapdb.DataIO;
import org.mapdb.Fun;
import org.mapdb.Serializer;
public class ObjectKeySerializer extends Serializer<Object[]>{
private static final long serialVersionUID = 998929894238939892L;
protected final int tsize;
protected final Comparator[] comparators;
protected final Serializer[] serializers;
protected final Comparator comparator;
private static Comparator[] nComparableComparators(int length) {
Comparator[] comparators = new Comparator[length];
for(int i=0;i<comparators.length;i++){
comparators[i] = Fun.COMPARATOR;
}
return comparators;
}
public ObjectKeySerializer(Comparator[] comparators, Serializer[] serializers) {
if(comparators.length!=serializers.length){
throw new IllegalArgumentException("array sizes do not match");
}
this.tsize = comparators.length;
this.comparators = comparators;
this.serializers = serializers;
this.comparator = new Fun.ArrayComparator(comparators);
}
@Override
public void serialize(DataOutput out, Object[] keys) throws IOException {
int[] counts = new int[tsize-1];
//$DELAY$
for(int i=0;i<keys.length;i+=tsize){
for(int j=0;j<tsize-1;j++){
//$DELAY$
if(counts[j]==0){
Object orig = keys[i+j];
serializers[j].serialize(out,orig);
counts[j]=1;
while(i+j+counts[j]*tsize<keys.length &&
comparators[j].compare(orig,keys[i+j+counts[j]*tsize])==0){
counts[j]++;
}
DataIO.packInt(out,counts[j]);
}
}
//write last value from tuple
serializers[serializers.length-1].serialize(out,keys[i+tsize-1]);
//decrement all
//$DELAY$
for(int j=counts.length-1;j>=0;j--){
counts[j]--;
}
}
}
@Override
public Object[] deserialize(DataInput in, int nodeSize) throws IOException {
Object[] ret = new Object[tsize];
Object[] curr = new Object[tsize];
int[] counts = new int[tsize-1];
//$DELAY$
for(int i=0;i<ret.length;i+=tsize){
for(int j=0;j<tsize-1;j++){
if(counts[j]==0){
//$DELAY$
curr[j] = serializers[j].deserialize(in,-1);
counts[j] = DataIO.unpackInt(in);
}
}
curr[tsize-1] = serializers[tsize-1].deserialize(in,-1);
System.arraycopy(curr,0,ret,i,tsize);
//$DELAY$
for(int j=counts.length-1;j>=0;j--){
counts[j]--;
}
}
for(int j:counts){
if(j!=0)
throw new DBException.DataCorruption("inconsistent counts");
}
return ret;
}
// @Override
// public int compare(Object[] keys, int pos1, int pos2) {
// pos1 *=tsize;
// pos2 *=tsize;
// int res;
// //$DELAY$
// for(Comparator c:comparators){
// //$DELAY$
// res = c.compare(keys[pos1++],keys[pos2++]);
// if(res!=0) {
// return res;
// }
// }
// return 0;
// }
//
// @Override
// public int compare(Object[] keys, int pos, Object[] tuple) {
// pos*=tsize;
// int len = Math.min(tuple.length, tsize);
// int r;
// //$DELAY$
// for(int i=0;i<len;i++){
// Object tval = tuple[i];
// if(tval==null)
// return -1;
// //$DELAY$
// r = comparators[i].compare(keys[pos++],tval);
// if(r!=0)
// return r;
// }
// return Fun.compareInt(tsize, tuple.length);
// }
//
// @Override
// public Object[] getKey(Object[] keys, int pos) {
// pos*=tsize;
// return Arrays.copyOfRange(keys,pos,pos+tsize);
// }
//
// @Override
// public Comparator<Object[]> comparator() {
// return comparator;
// }
//
// @Override
// public Object[] emptyKeys() {
// return new Object[0];
// }
//
// @Override
// public int length(Object[] objects) {
// return objects.length/tsize;
// }
//
// @Override
// public Object[] putKey(Object[] keys, int pos, Object[] newKey) {
// if(newKey.length!=tsize)
// throw new DBException.DataCorruption("inconsistent size");
// pos*=tsize;
// Object[] ret = new Object[keys.length+tsize];
// System.arraycopy(keys, 0, ret, 0, pos);
// //$DELAY$
// System.arraycopy(newKey,0,ret,pos,tsize);
// //$DELAY$
// System.arraycopy(keys,pos,ret,pos+tsize,keys.length-pos);
// return ret;
// }
//
// @Override
// public Object[] arrayToKeys(Object[] keys) {
// Object[] ret = new Object[keys.length*tsize];
// int pos=0;
// //$DELAY$
// for(Object o:keys){
// if(((Object[])o).length!=tsize)
// throw new DBException.DataCorruption("keys have wrong size");
// System.arraycopy(o,0,ret,pos,tsize);
// //$DELAY$
// pos+=tsize;
// }
// return ret;
// }
//
// @Override
// public Object[] copyOfRange(Object[] keys, int from, int to) {
// from*=tsize;
// to*=tsize;
// return Arrays.copyOfRange(keys,from,to);
// }
//
// @Override
// public Object[] deleteKey(Object[] keys, int pos) {
// pos*=tsize;
// Object[] ret = new Object[keys.length-tsize];
// System.arraycopy(keys,0,ret,0,pos);
// //$DELAY$
// System.arraycopy(keys,pos+tsize,ret,pos,ret.length-pos);
// return ret;
// }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ObjectKeySerializer that = (ObjectKeySerializer) o;
//$DELAY$
if (tsize != that.tsize) return false;
if (!Arrays.equals(comparators, that.comparators)) return false;
//$DELAY$
return Arrays.equals(serializers, that.serializers);
}
@Override
public int hashCode() {
int result = tsize;
result = 31 * result + Arrays.hashCode(comparators);
result = 31 * result + Arrays.hashCode(serializers);
return result;
}
@Override
public boolean isTrusted() {
for(Serializer s:serializers){
if(!s.isTrusted())
return false;
}
return true;
}
public int compare(Object[] keys, int pos1, int pos2) {
pos1 *=tsize;
pos2 *=tsize;
int res;
//$DELAY$
for(Comparator c:comparators){
//$DELAY$
res = c.compare(keys[pos1++],keys[pos2++]);
if(res!=0) {
return res;
}
}
return 0;
}
public int compare(Object[] keys, int pos, Object[] tuple) {
pos*=tsize;
int len = Math.min(tuple.length, tsize);
int r;
//$DELAY$
for(int i=0;i<len;i++){
Object tval = tuple[i];
if(tval==null)
return -1;
//$DELAY$
r = comparators[i].compare(keys[pos++],tval);
if(r!=0)
return r;
}
return Fun.compareInt(tsize, tuple.length);
}
public Object[] getKey(Object[] keys, int pos) {
pos*=tsize;
return Arrays.copyOfRange(keys,pos,pos+tsize);
}
public Comparator<Object[]> comparator() {
return comparator;
}
public Object[] emptyKeys() {
return new Object[0];
}
public int length(Object[] objects) {
return objects.length/tsize;
}
public Object[] putKey(Object[] keys, int pos, Object[] newKey) {
if(newKey.length!=tsize)
throw new DBException.DataCorruption("inconsistent size");
pos*=tsize;
Object[] ret = new Object[keys.length+tsize];
System.arraycopy(keys, 0, ret, 0, pos);
//$DELAY$
System.arraycopy(newKey,0,ret,pos,tsize);
//$DELAY$
System.arraycopy(keys,pos,ret,pos+tsize,keys.length-pos);
return ret;
}
public Object[] arrayToKeys(Object[] keys) {
Object[] ret = new Object[keys.length*tsize];
int pos=0;
//$DELAY$
for(Object o:keys){
if(((Object[])o).length!=tsize)
throw new DBException.DataCorruption("keys have wrong size");
System.arraycopy(o,0,ret,pos,tsize);
//$DELAY$
pos+=tsize;
}
return ret;
}
public Object[] copyOfRange(Object[] keys, int from, int to) {
from*=tsize;
to*=tsize;
return Arrays.copyOfRange(keys,from,to);
}
public Object[] deleteKey(Object[] keys, int pos) {
pos*=tsize;
Object[] ret = new Object[keys.length-tsize];
System.arraycopy(keys,0,ret,0,pos);
//$DELAY$
System.arraycopy(keys,pos+tsize,ret,pos,ret.length-pos);
return ret;
}
}
| lgpl-3.0 |
ismb/it.ismb.pert.osgi.dal.web-apis | src/it/ismb/pert/dal/web/apis/rest/pojos/InvokeRequest.java | 530 | package it.ismb.pert.dal.web.apis.rest.pojos;
/**
* Pojo representing an Invoke Request from a client
* @author Ivan Grimaldi (grimaldi@ismb.it)
*
*/
public class InvokeRequest {
private String operation;
private Argument[] arguments;
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
public Argument[] getArguments() {
return arguments;
}
public void setArguments(Argument[] arguments) {
this.arguments = arguments;
}
}
| lgpl-3.0 |
loftuxab/community-edition-old | projects/repository/source/java/org/alfresco/repo/admin/patch/AbstractPatch.java | 25792 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.admin.patch;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.alfresco.error.AlfrescoRuntimeException;
import org.springframework.extensions.surf.util.I18NUtil;
import org.alfresco.repo.batch.BatchProcessWorkProvider;
import org.alfresco.repo.batch.BatchProcessor;
import org.alfresco.repo.batch.BatchProcessor.BatchProcessWorker;
import org.alfresco.repo.node.integrity.IntegrityChecker;
import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.tenant.Tenant;
import org.alfresco.repo.tenant.TenantAdminService;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.admin.PatchException;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.search.SearchService;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
/**
* Base implementation of the patch. This class ensures that the patch is thread- and transaction-safe.
*
* @author Derek Hulley
*/
public abstract class AbstractPatch implements Patch, ApplicationEventPublisherAware
{
/**
* I18N message when properties not set.
* <ul>
* <li>{0} = property name</li>
* <li>{1} = patch instance</li>
* </ul>
*/
public static final String ERR_PROPERTY_NOT_SET = "patch.general.property_not_set";
private static final String MSG_PROGRESS = "patch.progress";
private static final String MSG_DEFERRED = "patch.genericBootstrap.result.deferred";
private static final long RANGE_10 = 1000 * 60 * 90;
private static final long RANGE_5 = 1000 * 60 * 60 * 4;
private static final long RANGE_2 = 1000 * 60 * 90 * 10;
private static Log logger = LogFactory.getLog(AbstractPatch.class);
private static Log progress_logger = LogFactory.getLog(PatchExecuter.class);
private String id;
private int fixesFromSchema;
private int fixesToSchema;
private int targetSchema;
private boolean force;
private String description;
private boolean ignored;
/** a list of patches that this one depends on */
private List<Patch> dependsOn;
/** a list of patches that, if already present, mean that this one should be ignored */
private List<Patch> alternatives;
/** flag indicating if the patch was successfully applied */
private boolean applied;
private boolean applyToTenants;
/** track completion * */
int percentComplete = 0;
/** start time * */
long startTime;
private boolean deferred = false;
// Does the patch require an enclosing transaction?
private boolean requiresTransaction = true;
/** the service to register ourselves with */
private PatchService patchService;
/** used to ensure a unique transaction per execution */
protected TransactionService transactionService;
/** Use this helper to ensure that patches can execute even on a read-only system */
protected RetryingTransactionHelper transactionHelper;
protected NamespaceService namespaceService;
protected NodeService nodeService;
protected SearchService searchService;
protected AuthenticationContext authenticationContext;
protected TenantAdminService tenantAdminService;
/** Publishes batch event notifications for JMX viewing */
protected ApplicationEventPublisher applicationEventPublisher;
public AbstractPatch()
{
this.fixesFromSchema = -1;
this.fixesToSchema = -1;
this.targetSchema = -1;
this.force = false;
this.applied = false;
this.applyToTenants = true; // by default, apply to each tenant, if tenant service is enabled
this.dependsOn = Collections.emptyList();
this.alternatives = Collections.emptyList();
this.ignored = false;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder(256);
sb.append("Patch")
.append("[ id=").append(id)
.append(", description=").append(description)
.append(", fixesFromSchema=").append(fixesFromSchema)
.append(", fixesToSchema=").append(fixesToSchema)
.append(", targetSchema=").append(targetSchema)
.append(", ignored=").append(ignored)
.append("]");
return sb.toString();
}
/**
* Set the service that this patch will register with for execution.
*/
public void setPatchService(PatchService patchService)
{
this.patchService = patchService;
}
/**
* Set the transaction provider so that each execution can be performed within a transaction
*/
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
this.transactionHelper = transactionService.getRetryingTransactionHelper();
this.transactionHelper.setForceWritable(true);
}
public void setNamespaceService(NamespaceService namespaceService)
{
this.namespaceService = namespaceService;
}
public void setNodeService(NodeService nodeService)
{
this.nodeService = nodeService;
}
public void setSearchService(SearchService searchService)
{
this.searchService = searchService;
}
public void setAuthenticationContext(AuthenticationContext authenticationContext)
{
this.authenticationContext = authenticationContext;
}
public void setTenantAdminService(TenantAdminService tenantAdminService)
{
this.tenantAdminService = tenantAdminService;
}
/**
* Set automatically
*/
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher)
{
this.applicationEventPublisher = applicationEventPublisher;
}
/**
* This ensures that this bean gets registered with the appropriate {@link PatchService service}.
*/
public void init()
{
if (patchService == null)
{
throw new AlfrescoRuntimeException("Mandatory property not set: patchService");
}
if(false == isIgnored())
{
patchService.registerPatch(this);
}
}
public String getId()
{
return id;
}
/**
* @param id
* the unique ID of the patch. This dictates the order in which patches are applied.
*/
public void setId(String id)
{
this.id = id;
}
public int getFixesFromSchema()
{
return fixesFromSchema;
}
public void setRequiresTransaction(boolean requiresTransaction)
{
this.requiresTransaction = requiresTransaction;
}
public boolean requiresTransaction()
{
return requiresTransaction;
}
/**
* Set the smallest schema number that this patch may be applied to.
*
* @param version
* a schema number not smaller than 0
*/
public void setFixesFromSchema(int version)
{
if (version < 0)
{
throw new IllegalArgumentException("The 'fixesFromSchema' property may not be less than 0");
}
this.fixesFromSchema = version;
// auto-adjust the to version
if (fixesToSchema < fixesFromSchema)
{
setFixesToSchema(this.fixesFromSchema);
}
}
public int getFixesToSchema()
{
return fixesToSchema;
}
/**
* Set the largest schema version number that this patch may be applied to.
*
* @param version
* a schema version number not smaller than the {@link #setFixesFromSchema(int) from version} number.
*/
public void setFixesToSchema(int version)
{
if (version < fixesFromSchema)
{
throw new IllegalArgumentException("'fixesToSchema' must be greater than or equal to 'fixesFromSchema'");
}
this.fixesToSchema = version;
}
public int getTargetSchema()
{
return targetSchema;
}
/**
* Set the schema version that this patch attempts to take the existing schema to. This is for informational
* purposes only, acting as an indicator of intention rather than having any specific effect.
*
* @param version
* a schema version number that must be greater than the {@link #fixesToSchema max fix schema number}
*/
public void setTargetSchema(int version)
{
if (version <= fixesToSchema)
{
throw new IllegalArgumentException("'targetSchema' must be greater than 'fixesToSchema'");
}
this.targetSchema = version;
}
/**
* {@inheritDoc}
*/
public boolean isForce()
{
return force;
}
/**
* Set the flag that forces the patch to be forcefully applied. This allows patches to be overridden to induce execution
* regardless of the upgrade or installation versions, or even if the patch has been executed before.
*
* @param force <tt>true</tt> to force the patch to be applied
*/
public void setForce(boolean force)
{
this.force = force;
}
public String getDescription()
{
return description;
}
/**
* @param description
* a thorough description of the patch
*/
public void setDescription(String description)
{
this.description = description;
}
/**
* @return the ignored
*/
public boolean isIgnored()
{
return ignored;
}
/**
* @param ignored the ignored to set
*/
public void setIgnored(boolean ignored)
{
this.ignored = ignored;
}
public List<Patch> getDependsOn()
{
return this.dependsOn;
}
/**
* Set all the dependencies for this patch. It should not be executed before all the dependencies have been applied.
*
* @param dependsOn
* a list of dependencies
*/
public void setDependsOn(List<Patch> dependsOn)
{
this.dependsOn = dependsOn;
}
public List<Patch> getAlternatives()
{
return alternatives;
}
/**
* Set all anti-dependencies. If any of the patches in the list have already been executed, then
* this one need not be.
*
* @param alternatives a list of alternative patches
*/
public void setAlternatives(List<Patch> alternatives)
{
this.alternatives = alternatives;
}
public boolean applies(int version)
{
return ((this.fixesFromSchema <= version) && (version <= fixesToSchema));
}
/**
* Performs a null check on the supplied value.
*
* @param value
* value to check
* @param name
* name of the property to report
*/
protected final void checkPropertyNotNull(Object value, String name)
{
if (value == null)
{
throw new PatchException(ERR_PROPERTY_NOT_SET, name, this);
}
}
public void setApplyToTenants(boolean applyToTenants)
{
this.applyToTenants = applyToTenants;
}
/**
* Check that the schema version properties have been set appropriately. Derived classes can override this method to
* perform their own validation provided that this method is called by the derived class.
*/
protected void checkProperties()
{
// check that the necessary properties have been set
checkPropertyNotNull(id, "id");
checkPropertyNotNull(description, "description");
checkPropertyNotNull(transactionService, "transactionService");
checkPropertyNotNull(transactionHelper, "transactionHelper");
checkPropertyNotNull(namespaceService, "namespaceService");
checkPropertyNotNull(nodeService, "nodeService");
checkPropertyNotNull(searchService, "searchService");
checkPropertyNotNull(authenticationContext, "authenticationContext");
checkPropertyNotNull(tenantAdminService, "tenantAdminService");
checkPropertyNotNull(applicationEventPublisher, "applicationEventPublisher");
if (fixesFromSchema == -1 || fixesToSchema == -1 || targetSchema == -1)
{
throw new AlfrescoRuntimeException(
"Patch properties 'fixesFromSchema', 'fixesToSchema' and 'targetSchema' " +
"have not all been set on this patch: \n"
+ " patch: " + this);
}
}
private String applyWithTxns() throws Exception
{
if(logger.isDebugEnabled())
{
logger.debug("call applyInternal for main context id:" + id);
}
RetryingTransactionCallback<String> patchWork = new RetryingTransactionCallback<String>()
{
public String execute() throws Exception
{
// downgrade integrity checking
IntegrityChecker.setWarnInTransaction();
return applyInternal();
}
};
StringBuilder sb = new StringBuilder(128);
if (requiresTransaction())
{
// execute in a transaction
String temp = this.transactionHelper.doInTransaction(patchWork, false, true);
sb.append(temp);
}
else
{
String temp = applyInternal();
sb.append(temp);
}
if ((tenantAdminService != null) && tenantAdminService.isEnabled() && applyToTenants)
{
if(logger.isDebugEnabled())
{
logger.debug("call applyInternal for all tennants");
}
final List<Tenant> tenants = tenantAdminService.getAllTenants();
BatchProcessWorkProvider<Tenant> provider = new BatchProcessWorkProvider<Tenant>()
{
Iterator<Tenant> i = tenants.iterator();
@Override
public int getTotalEstimatedWorkSize()
{
return tenants.size();
}
@Override
public Collection<Tenant> getNextWork()
{
// return chunks of 10 tenants
ArrayList<Tenant> chunk = new ArrayList<Tenant>(100);
while(i.hasNext() && chunk.size() <= 100)
{
chunk.add(i.next());
}
return chunk;
}
};
BatchProcessor<Tenant> batchProcessor = new BatchProcessor<Tenant>(
"AbstractPatch Processor for " + id,
transactionHelper,
provider, // collection of tenants
10, // worker threads,
100, // batch size 100,
applicationEventPublisher,
logger,
1000);
BatchProcessWorker<Tenant> worker = new BatchProcessWorker<Tenant>()
{
@Override
public String getIdentifier(Tenant entry)
{
return entry.getTenantDomain();
}
@Override
public void beforeProcess() throws Throwable
{
}
@Override
public void process(Tenant entry) throws Throwable
{
String tenantDomain = entry.getTenantDomain();
@SuppressWarnings("unused")
String tenantReport = AuthenticationUtil.runAs(new RunAsWork<String>()
{
public String doWork() throws Exception
{
return applyInternal();
}
}, tenantAdminService.getDomainUser(AuthenticationUtil.getSystemUserName(), tenantDomain));
}
@Override
public void afterProcess() throws Throwable
{
}
};
// Now do the work
@SuppressWarnings("unused")
int numberOfInvocations = batchProcessor.process(worker, true);
if (logger.isDebugEnabled())
{
logger.debug("batch worker finished processing id:" + id);
}
if (batchProcessor.getTotalErrors() > 0)
{
sb.append("\n" + " and failure during update of tennants total success: " + batchProcessor.getSuccessfullyProcessedEntries() + " number of errors: " +batchProcessor.getTotalErrors() + " lastError" + batchProcessor.getLastError());
}
else
{
sb.append("\n" + " and successful batch update of " + batchProcessor.getTotalResults() + "tennants");
}
}
// Done
return sb.toString();
}
/**
* Apply the patch, regardless of the deferred flag. So if the patch has not run due to it being deferred earlier
* then this will run it now. Also ignores the "applied" lock. So the patch can be executed many times.
*
* @return the patch report
* @throws PatchException if the patch failed to be applied
*/
public String applyAsync() throws PatchException
{
return apply(true);
}
/**
* Sets up the transaction and ensures thread-safety.
*
* @see #applyInternal()
*/
public synchronized String apply() throws PatchException
{
return apply(false);
}
private String apply(boolean async)
{
if (!async)
{
// Do we bug out of patch execution
if (deferred)
{
return I18NUtil.getMessage(MSG_DEFERRED);
}
// ensure that this has not been executed already
if (applied)
{
throw new AlfrescoRuntimeException("The patch has already been executed: \n" + " patch: " + this);
}
}
// check properties
checkProperties();
if (logger.isDebugEnabled())
{
logger.debug("\n" + "Patch will be applied: \n" + " patch: " + this);
}
try
{
AuthenticationUtil.RunAsWork<String> applyPatchWork = new AuthenticationUtil.RunAsWork<String>()
{
public String doWork() throws Exception
{
return applyWithTxns();
}
};
startTime = System.currentTimeMillis();
String report = AuthenticationUtil.runAs(applyPatchWork, AuthenticationUtil.getSystemUserName());
// the patch was successfully applied
applied = true;
// done
if (logger.isDebugEnabled())
{
logger.debug("\n" + "Patch successfully applied: \n" + " patch: " + this + "\n" + " report: " + report);
}
return report;
}
catch (PatchException e)
{
// no need to extract the exception
throw e;
}
catch (Throwable e)
{
// check whether there is an embedded patch exception
Throwable cause = e.getCause();
if (cause != null && cause instanceof PatchException)
{
throw (PatchException) cause;
}
// need to generate a message from the exception
String report = makeReport(e);
// generate the correct exception
throw new PatchException(report);
}
}
/**
* Dumps the error's full message and trace to the String
*
* @param e
* the throwable
* @return Returns a String representative of the printStackTrace method
*/
private String makeReport(Throwable e)
{
StringWriter stringWriter = new StringWriter(1024);
PrintWriter printWriter = new PrintWriter(stringWriter, true);
try
{
e.printStackTrace(printWriter);
return stringWriter.toString();
}
finally
{
printWriter.close();
}
}
/**
* This method does the work. All transactions and thread-safety will be taken care of by this class. Any exception
* will result in the transaction being rolled back. Integrity checks are downgraded for the duration of the
* transaction.
*
* @return Returns the report (only success messages).
* @see #apply()
* @throws Exception
* anything can be thrown. This must be used for all failures.
*/
protected abstract String applyInternal() throws Exception;
/**
* Support to report patch completion and estimated completion time.
*
* @param estimatedTotal
* @param currentInteration
*/
protected void reportProgress(long estimatedTotal, long currentInteration)
{
if (progress_logger.isDebugEnabled())
{
progress_logger.debug(currentInteration + "/" + estimatedTotal);
}
if (currentInteration == 0)
{
// No point reporting the start - we have already done that elsewhere ....
percentComplete = 0;
}
else if (currentInteration * 100l / estimatedTotal > percentComplete)
{
int previous = percentComplete;
percentComplete = (int) (currentInteration * 100l / estimatedTotal);
if (percentComplete < 100)
{
// conditional report
long currentTime = System.currentTimeMillis();
long timeSoFar = currentTime - startTime;
long timeRemaining = timeSoFar * (100 - percentComplete) / percentComplete;
int report = -1;
if (timeRemaining > 60000)
{
int reportInterval = getReportingInterval(timeSoFar, timeRemaining);
for (int i = previous + 1; i <= percentComplete; i++)
{
if (i % reportInterval == 0)
{
report = i;
}
}
if (report > 0)
{
Date end = new Date(currentTime + timeRemaining);
String msg = I18NUtil.getMessage(MSG_PROGRESS, getId(), report, end);
progress_logger.info(msg);
}
}
}
}
}
/**
* Should the patch be deferred? And not run at bootstrap.
* @param deferred
*/
public void setDeferred(boolean deferred)
{
this.deferred = deferred;
}
/*
*
*/
public boolean isDeferred()
{
return deferred;
}
private int getReportingInterval(long soFar, long toGo)
{
long total = soFar + toGo;
if (total < RANGE_10)
{
return 10;
}
else if (total < RANGE_5)
{
return 5;
}
else if (total < RANGE_2)
{
return 2;
}
else
{
return 1;
}
}
}
| lgpl-3.0 |
christopher-worley/common-app | core-commonapp-model-jpa/src/main/java/core/data/model/jpa/task/TaskRoleJpaImpl.java | 5471 | /**
* Copyright 2009 Core Information Solutions LLC
*
* This file is part of Core CommonApp Framework.
*
* Core CommonApp Framework is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Core CommonApp Framework 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 Core CommonApp Framework. If not, see <http://www.gnu.org/licenses/>.
*
*/
package core.data.model.jpa.task;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import core.data.model.jpa.party.PartyJpaImpl;
import core.data.model.jpa.party.RoleTypeJpaImpl;
import core.data.model.party.Party;
import core.data.model.party.RoleType;
import core.data.model.task.Task;
import core.data.model.task.TaskRole;
import core.data.model.util.DataUtil;
@Entity
@Table (name="task_role")
public class TaskRoleJpaImpl implements TaskRole
{
@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column (name="task_role_id", nullable=false)
private Integer taskRoleId;
@ManyToOne (cascade = CascadeType.MERGE, targetEntity=TaskJpaImpl.class)
@JoinColumn (name="task_id")
private Task task;
@ManyToOne (targetEntity=PartyJpaImpl.class)
@JoinColumn (name="party_id")
private Party party;
@ManyToOne (targetEntity=RoleTypeJpaImpl.class)
@JoinColumn (name="role_type_id")
private RoleType roleType;
@Column (name="from_date")
private Date fromDate;
@Column (name="thru_date")
private Date thruDate;
/**
* Getter for fromDate
*
* @return the fromDate
*/
public Date getFromDate()
{
return fromDate;
}
public Integer getId()
{
return getTaskRoleId();
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#getParty()
*/
public Party getParty()
{
return party;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#getRoleType()
*/
public RoleType getRoleType()
{
return roleType;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#getTask()
*/
public Task getTask()
{
return task;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#getTaskRoleId()
*/
public Integer getTaskRoleId()
{
return taskRoleId;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#getThruDate()
*/
public Date getThruDate()
{
return thruDate;
}
public boolean isEquivalent(Object object)
{
TaskRole role = (TaskRole) object;
return DataUtil.equals(getTaskRoleId(), role.getTaskRoleId())
&& DataUtil.isEquivalent(getTask(), role.getTask())
&& DataUtil.isEquivalent(getParty(), role.getParty())
&& DataUtil.isEquivalent(getRoleType(), role.getRoleType())
&& DataUtil.equals(getFromDate(), role.getFromDate())
&& DataUtil.equals(getThruDate(), role.getThruDate());
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setFromDate(java.sql.Date)
*/
public void setFromDate(Date fromDate)
{
this.fromDate = fromDate;
}
public void setId(Integer id)
{
setTaskRoleId(id);
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setParty(core.data.model.party.Party)
*/
public void setParty(Party party)
{
this.party = party;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setRoleType(core.data.model.party.RoleType)
*/
public void setRoleType(RoleType roleType)
{
this.roleType = roleType;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setTask(core.data.model.task.Task)
*/
public void setTask(Task task)
{
this.task = task;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setTaskRoleId(java.lang.Integer)
*/
public void setTaskRoleId(Integer taskRoleId)
{
this.taskRoleId = taskRoleId;
}
/* (non-Javadoc)
* @see core.data.model.task.TaskRole#setThruDate(java.sql.Date)
*/
public void setThruDate(Date thruDate)
{
this.thruDate = thruDate;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return "TaskRole("
+ "taskRoleId="
+ getTaskRoleId()
+ ",task="
+ DataUtil.getId(getTask())
+ ",party="
+ DataUtil.getId(getParty())
+ ",roleType="
+ getRoleType()
+ ",fromDate="
+ getFromDate()
+ ",thruDate="
+ getThruDate()
+ ")";
}
}
| lgpl-3.0 |
SafetyCulture/DroidText | app/src/main/java/bouncycastle/repack/org/bouncycastle/jce/provider/symmetric/XTEA.java | 1182 | package repack.org.bouncycastle.jce.provider.symmetric;
import repack.org.bouncycastle.crypto.CipherKeyGenerator;
import repack.org.bouncycastle.crypto.engines.XTEAEngine;
import repack.org.bouncycastle.jce.provider.JCEBlockCipher;
import repack.org.bouncycastle.jce.provider.JCEKeyGenerator;
import repack.org.bouncycastle.jce.provider.JDKAlgorithmParameters;
import java.util.HashMap;
public final class XTEA
{
private XTEA()
{
}
public static class ECB
extends JCEBlockCipher
{
public ECB()
{
super(new XTEAEngine());
}
}
public static class KeyGen
extends JCEKeyGenerator
{
public KeyGen()
{
super("XTEA", 128, new CipherKeyGenerator());
}
}
public static class AlgParams
extends JDKAlgorithmParameters.IVAlgorithmParameters
{
protected String engineToString()
{
return "XTEA IV";
}
}
public static class Mappings
extends HashMap
{
public Mappings()
{
put("Cipher.XTEA", "org.bouncycastle.jce.provider.symmetric.XTEA$ECB");
put("KeyGenerator.XTEA", "org.bouncycastle.jce.provider.symmetric.XTEA$KeyGen");
put("AlgorithmParameters.XTEA", "org.bouncycastle.jce.provider.symmetric.XTEA$AlgParams");
}
}
}
| lgpl-3.0 |
berisd/VirtualFile | src/test/java/at/beris/virtualfile/filter/DefaultFilterTest.java | 3807 | /*
* This file is part of VirtualFile.
*
* Copyright 2016 by Bernd Riedl <bernd.riedl@gmail.com>
*
* Licensed under GNU Lesser General Public License 3.0 or later.
* Some rights reserved. See COPYING, AUTHORS.
*/
package at.beris.virtualfile.filter;
import at.beris.virtualfile.TestHelper;
import at.beris.virtualfile.UrlFileManager;
import at.beris.virtualfile.VirtualFile;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
public class DefaultFilterTest {
private static final String TEST_DIRECTORY = "testdir/";
private static VirtualFile testDirectory;
private static UrlFileManager fileManager;
@BeforeClass
public static void setUp() throws Exception {
fileManager = TestHelper.createFileManager();
TestFilterHelper.createFiles(fileManager, TEST_DIRECTORY);
testDirectory = fileManager.resolveLocalFile(TEST_DIRECTORY);
}
@AfterClass
public static void tearDown() {
testDirectory.delete();
}
@Test
public void filterBetween() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().between(640L, 816L));
Assert.assertEquals(2, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("testfile2.txt"));
Assert.assertTrue(filteredFileNameList.contains("testfile2.txt"));
}
@Test
public void filterGreaterThan() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().greaterThan(640L));
Assert.assertEquals(2, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("testfile2.txt"));
Assert.assertTrue(filteredFileNameList.contains("goodmovie.avi"));
}
@Test
public void filterGreaterThanOrEqual() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().greaterThanOrEqualTo(640L));
Assert.assertEquals(3, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("testfile1.txt"));
Assert.assertTrue(filteredFileNameList.contains("testfile2.txt"));
Assert.assertTrue(filteredFileNameList.contains("goodmovie.avi"));
}
@Test
public void filterIn() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().in(640L, 800L));
Assert.assertEquals(2, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("testfile1.txt"));
Assert.assertTrue(filteredFileNameList.contains("testfile2.txt"));
}
@Test
public void filterLessThan() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().lessThan(640L));
Assert.assertEquals(1, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("subdir"));
}
@Test
public void filterLessThanOrEqual() {
List<VirtualFile> filteredList = testDirectory.find(new FileSizeFilter().lessThanOrEqualTo(640L));
Assert.assertEquals(2, filteredList.size());
List<String> filteredFileNameList = TestFilterHelper.getNameListFromFileList(filteredList);
Assert.assertTrue(filteredFileNameList.contains("testfile1.txt"));
Assert.assertTrue(filteredFileNameList.contains("subdir"));
}
} | lgpl-3.0 |
vorburger/mSara | saraswathi-gae-xmpp/src/main/java/ch/vorburger/gaexmpp/http/HTTPForwardingXMPPIncomingMessageHandler.java | 1045 | package ch.vorburger.gaexmpp.http;
import java.net.URI;
import ch.vorburger.gaexmpp.XMPPIncomingMessageHandler;
import ch.vorburger.gaexmpp.XMPPMessage;
import ch.vorburger.gaexmpp.http.OutgoingHTTPRequestMessage.Verb;
public class HTTPForwardingXMPPIncomingMessageHandler implements XMPPIncomingMessageHandler {
private OutgoingHTTPService httpService = new GAEOutgoingHTTPService();
@Override
public String handleIncoming(XMPPMessage message) {
OutgoingHTTPRequestMessage httpRequest = new OutgoingHTTPRequestMessage();
// TODO remove hard-coding, read from a configurable Repository instead
httpRequest.uri = URI.create("http://localhost:5000/sms/twilio");
httpRequest.verb = Verb.POST;
httpRequest.body = null; // TODO transform XMPPMessage message to JSON, hard-coded via GSON for now, via TBD DiStructConversionService later
OutgoingHTTPRequestResponseMessage response = httpService.request(httpRequest);
// TODO check for HTTP error status, and throw Exception if any
return response.getBodyAsText();
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.java | 6196 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.ce.task.projectanalysis.scm;
import org.junit.Test;
import org.sonar.db.protobuf.DbFileSources;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.server.source.index.FileSourceTesting.newFakeData;
public class DbScmInfoTest {
@Test
public void create_scm_info_with_some_changesets() {
ScmInfo scmInfo = DbScmInfo.create(newFakeData(10).build().getLinesList(), 10, "hash").get();
assertThat(scmInfo.getAllChangesets()).hasSize(10);
}
@Test
public void return_changeset_for_a_given_line() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
addLine(fileDataBuilder, 1, "john", 123456789L, "rev-1");
addLine(fileDataBuilder, 2, "henry", 1234567810L, "rev-2");
addLine(fileDataBuilder, 3, "henry", 1234567810L, "rev-2");
addLine(fileDataBuilder, 4, "john", 123456789L, "rev-1");
fileDataBuilder.build();
ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 4, "hash").get();
assertThat(scmInfo.getAllChangesets()).hasSize(4);
Changeset changeset = scmInfo.getChangesetForLine(4);
assertThat(changeset.getAuthor()).isEqualTo("john");
assertThat(changeset.getDate()).isEqualTo(123456789L);
assertThat(changeset.getRevision()).isEqualTo("rev-1");
}
@Test
public void return_same_changeset_objects_for_lines_with_same_fields() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(65L).setLine(1);
fileDataBuilder.addLinesBuilder().setScmRevision("rev2").setScmDate(6541L).setLine(2);
fileDataBuilder.addLinesBuilder().setScmRevision("rev1").setScmDate(6541L).setLine(3);
fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(65L).setLine(4);
ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 4, "hash").get();
assertThat(scmInfo.getAllChangesets()).hasSize(4);
assertThat(scmInfo.getChangesetForLine(1)).isSameAs(scmInfo.getChangesetForLine(4));
}
@Test
public void return_latest_changeset() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
addLine(fileDataBuilder, 1, "john", 123456789L, "rev-1");
// Older changeset
addLine(fileDataBuilder, 2, "henry", 1234567810L, "rev-2");
addLine(fileDataBuilder, 3, "john", 123456789L, "rev-1");
fileDataBuilder.build();
ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 3, "hash").get();
Changeset latestChangeset = scmInfo.getLatestChangeset();
assertThat(latestChangeset.getAuthor()).isEqualTo("henry");
assertThat(latestChangeset.getDate()).isEqualTo(1234567810L);
assertThat(latestChangeset.getRevision()).isEqualTo("rev-2");
}
@Test
public void return_absent_dsm_info_when_no_changeset() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
fileDataBuilder.addLinesBuilder().setLine(1);
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 1, "hash")).isNotPresent();
}
@Test
public void should_support_some_lines_not_having_scm_info() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(543L).setLine(1);
fileDataBuilder.addLinesBuilder().setLine(2);
fileDataBuilder.build();
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2);
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(1)).isTrue();
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(2)).isFalse();
}
@Test
public void filter_out_entries_without_date() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(555L).setLine(1);
fileDataBuilder.addLinesBuilder().setScmRevision("rev-1").setLine(2);
fileDataBuilder.build();
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2);
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getChangesetForLine(1).getRevision()).isEqualTo("rev");
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(2)).isFalse();
}
@Test
public void should_support_having_no_author() {
DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder();
// gets filtered out
fileDataBuilder.addLinesBuilder().setScmAuthor("John").setLine(1);
fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(555L).setLine(2);
fileDataBuilder.build();
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2);
assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getChangesetForLine(2).getAuthor()).isNull();
}
private static void addLine(DbFileSources.Data.Builder dataBuilder, Integer line, String author, Long date, String revision) {
dataBuilder.addLinesBuilder()
.setLine(line)
.setScmAuthor(author)
.setScmDate(date)
.setScmRevision(revision);
}
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/PreferencesQueryRqTypeDescriptor.java | 7693 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: PreferencesQueryRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.PreferencesQueryRqType;
/**
* Class PreferencesQueryRqTypeDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $
*/
public class PreferencesQueryRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public PreferencesQueryRqTypeDescriptor() {
super();
_xmlName = "PreferencesQueryRqType";
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _requestID
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
PreferencesQueryRqType target = (PreferencesQueryRqType) object;
return target.getRequestID();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
PreferencesQueryRqType target = (PreferencesQueryRqType) object;
target.setRequestID( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _requestID
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _preferencesQuery
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.PreferencesQuery.class, "_preferencesQuery", "-error-if-this-is-used-", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
PreferencesQueryRqType target = (PreferencesQueryRqType) object;
return target.getPreferencesQuery();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
PreferencesQueryRqType target = (PreferencesQueryRqType) object;
target.setPreferencesQuery( (org.chocolate_milk.model.PreferencesQuery) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return new org.chocolate_milk.model.PreferencesQuery();
}
};
desc.setSchemaType("org.chocolate_milk.model.PreferencesQuery");
desc.setHandler(handler);
desc.setContainer(true);
desc.setClassDescriptor(new org.chocolate_milk.model.descriptors.PreferencesQueryDescriptor());
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _preferencesQuery
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.PreferencesQueryRqType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
Glydar/Glydar.next | ParaGlydar/src/main/java/org/glydar/paraglydar/configuration/serialization/SerializableAs.java | 1116 | package org.glydar.paraglydar.configuration.serialization;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Represents an "alias" that a {@link ConfigurationSerializable} may be stored as.
* If this is not present on a {@link ConfigurationSerializable} class, it will use the
* fully qualified name of the class.
* <p/>
* This value will be stored in the configuration so that the configuration deserialization
* can determine what type it is.
* <p/>
* Using this annotation on any other class than a {@link ConfigurationSerializable} will
* have no effect.
*
* @see ConfigurationSerialization#registerClass(Class, String)
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SerializableAs {
/**
* This is the name your class will be stored and retrieved as.
* <p/>
* This name MUST be unique. We recommend using names such as "MyPluginThing" instead of
* "Thing".
*
* @return Name to serialize the class as.
*/
public String value();
}
| lgpl-3.0 |
qiaolugithub/myshop | src/main/java/net/jeeshop/thirdParty/miaodiyun/huiDiao/entity/MoNoticeResp.java | 246 | package net.jeeshop.thirdParty.miaodiyun.huiDiao.entity;
public class MoNoticeResp
{
private String respCode;
public String getRespCode()
{
return respCode;
}
public void setRespCode(String respCode)
{
this.respCode = respCode;
}
}
| lgpl-3.0 |
DeanAaron/Projects | ExtendPackageTest/src/com/bean/dbutils/DBUtilsTest.java | 7454 | package com.bean.dbutils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.KeyedHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Before;
import org.junit.Test;
import com.bean.dbutils.DBURL.DBType;
public class DBUtilsTest {
private static final String user = "root";
private static final String password = "root";
private static Connection connection;
@Test
public void DBTest() {
try {
BeanListHandler<Users> beanListHandler = new BeanListHandler<Users>(Users.class);
QueryRunner queryRunner = new QueryRunner();
List<Users> userList = queryRunner.query(connection, "select * from users", beanListHandler);
for (Users user : userList) {
System.out.println(user.toString());
}
DbUtils.close(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void query() throws SQLException {
/**
*ArrayHandler:把结果集中的第一行数据转成对象数组。
*ArrayListHandler:把结果集中的每一行数据都转成一个对象数组,再存放到List中。
*BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
*BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
*ColumnListHandler:将结果集中某一列的数据存放到List中。
*KeyedHandler:将结果集中的每一行数据都封装到一个Map里,然后再根据指定的key把每个Map再存放到一个Map里。
*MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
*MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List。
*ScalarHandler:将结果集中某一条记录的其中某一列的数据存成Object。
*/
//采用MapHandler存储方式查询
MapHandler handler = new MapHandler();
QueryRunner runner = new QueryRunner();
try {
Map<String, Object> query = runner.query(connection,"select * from users where id = ?", handler, new Object[]{"5"});
System.out.println(query.get("name"));
} catch (SQLException e) {
e.printStackTrace();
}
//采用MapListHandler存储方式查询
MapListHandler mapListHandler = new MapListHandler();
try {
List<Map<String, Object>> query = runner.query(connection, "select * from users where id = ?", mapListHandler, new Object[]{"5"});
for (int i = 0; i < query.size(); i++) {
Map<String, Object> map = query.get(i);
System.out.println(map.get("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
//采用BeanHandler存储方式查询
BeanHandler<Users> beanHandler = new BeanHandler<Users>(Users.class);
Users users = runner.query(connection, "select * from users where id = ?", beanHandler, new Object[]{"5"});
System.out.println(users.getName());
//BeanListHandler存储方式查询
BeanListHandler<Users> beanListHandler = new BeanListHandler<Users>(Users.class);
List<Users> list = runner.query(connection, "select * from users where age > ?", beanListHandler, new Object[]{"1007"});
for (Users user : list) {
System.out.println(user.getAge());
}
//ArrayHandler存储方式查询,返回一个对象的值,有多个对象则只返第一个对象值
ArrayHandler arrayHandler = new ArrayHandler();
Object[] objects = runner.query(connection, "select * from users where age > ?", arrayHandler, new Object[]{"1005"});
for (Object object : objects) {
System.out.println(object.toString());
}
//ArrayListHandler存储方式查询
ArrayListHandler arrayListHandler = new ArrayListHandler();
List<Object[]> query = runner.query(connection, "select * from users where age > ?", arrayListHandler, new Object[]{"1005"});
for (Object[] objects2 : query) {
System.out.println(objects2[1].toString());
}
//ScalarHandler存储方式查询
ScalarHandler<String> scalarHandler = new ScalarHandler<String>("name");
String query2 = runner.query(connection, "select * from users where age > ?", scalarHandler, new Object[]{"1005"});
System.out.println(query2);
//KeyedHandler存储方式查询
KeyedHandler<String> keyedHandler = new KeyedHandler<String>("name");
Map<String, Map<String, Object>> map = runner.query(connection, "select * from users where age > ?", keyedHandler, new Object[]{"1005"});
Map<String, Object> ob = map.get("users996");
System.out.println(ob.get("name").toString());
}
@Test
public void insert() {
//TODO update和insert都可以插入数据还是insert是另外的用途?
QueryRunner runner = new QueryRunner();
try {
/*int update = runner.update(connection, "insert into users(name, age,sex) values(?,?,?)", new Object[]{"aaa", 250, "男"});
System.out.println(update);*/
//不知为何这里做了插入,数据也放进去了,但是返回结果是空的
BeanHandler<Users> beanHandler = new BeanHandler<Users>(Users.class);
Users user = runner.insert(connection, "insert into users(name, age,sex) values(?,?,?)", beanHandler, new Object[]{"aa", 25, "女"});
connection.commit();
System.out.println(user.getName());
} catch (SQLException e) {
e.printStackTrace();
}
}
//修改数据
@Test
public void update() {
QueryRunner runner = new QueryRunner();
try {
int update = runner.update(connection, "update users set name = ?, age = ? where id = ?", new Object[]{"aaa","28","1"});
//需要注意在初始化连接的时候是否允许自动提交
connection.commit();
System.out.println(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
public void delete() {
QueryRunner runner = new QueryRunner();
try {
int update = runner.update(connection, "delete from users where id = ?", new Object[]{"1"});
connection.commit();
System.out.println(update);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Before
public void getInstance() throws SQLException {
//加载数据库驱动
DbUtils.loadDriver(DBDriver.MYSQL);
//获取链接
if (null == connection) {
connection = DriverManager.getConnection(DBURL.getURL(DBType.MYSQL, "localhost", "3306", "testdb", DBURL.UTF8), user, password);
}
try {
//关闭自动提交,以可以在发生错误时进行回滚操作
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
} | lgpl-3.0 |
tchegito/zildo | zildo/src/main/java/zildo/monde/dialog/DialogManagement.java | 9196 | /**
* The Land of Alembrum
* Copyright (C) 2006-2016 Evariste Boussaton
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later 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, see <http://www.gnu.org/licenses/>.
*
*/
package zildo.monde.dialog;
import java.util.ArrayList;
import java.util.List;
import zildo.fwk.ZUtils;
import zildo.fwk.net.TransferObject;
import zildo.fwk.script.model.ZSSwitch;
import zildo.fwk.script.xml.element.TriggerElement;
import zildo.fwk.ui.UIText;
import zildo.monde.dialog.WaitingDialog.CommandDialog;
import zildo.monde.quest.actions.BuyingAction;
import zildo.monde.sprites.persos.Perso;
import zildo.monde.sprites.persos.PersoPlayer;
import zildo.server.EngineZildo;
import zildo.server.state.ClientState;
public class DialogManagement {
List<WaitingDialog> dialogQueue;
private boolean currentSentenceFullDisplayed;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
public DialogManagement() {
dialogQueue=new ArrayList<WaitingDialog>();
}
///////////////////////////////////////////////////////////////////////////////////////
// launchDialog
///////////////////////////////////////////////////////////////////////////////////////
// IN : p_zildo :
// persoToTalk :
///////////////////////////////////////////////////////////////////////////////////////
/**
* Launch an interaction between Zildo and a character, or ingame event: <ul>
* <li>if <code>p_persoToTalk</code> is not null, starts a dialog with him.</li>
* <li>if <code>p_actionDialog</code> is not null, displays text and launch delegate action.</li>
* </ul>
* @param p_client Zildo who's talking
* @param p_persoToTalk perso to talk with (NULL if there's from an automatic behavior)
* @param p_actionDialog
*/
public void launchDialog(ClientState p_client, Perso persoToTalk, ActionDialog p_actionDialog ) {
if (persoToTalk != null) {
// Need to be done early because ZSSwitch need to know who is speaking
p_client.zildo.setDialoguingWith(persoToTalk);
}
WaitingDialog even = createWaitingDialog(p_client, persoToTalk, p_actionDialog);
if (even != null) {
p_client.dialogState.setContinuing(even.sentence.indexOf("@") != -1);
even.sentence = even.sentence.trim().replaceAll("@", "");
even.sentence = even.sentence;
dialogQueue.add(even);
if (persoToTalk == null && p_client.zildo.getDialoguingWith() != null) {
// Zildo is talking with someone, and an automatic behavior happens (he takes an item).
// After this automatic dialog, he should get back to the conversation.
p_client.dialogState.setContinuing(true);
}
p_client.dialogState.setDialoguing(true);
if (p_client.zildo.getDialoguingWith() == null && even.who != null) {
Perso character = EngineZildo.persoManagement.getNamedPerso(even.who);
p_client.zildo.setDialoguingWith(character);
}
} else {
// Character has nothing to say
p_client.zildo.setDialoguingWith(null);
}
}
private String getPeopleName(String p_name) {
String result = null;
if (p_name != null) {
// 1) Look for mapping
String name = EngineZildo.scriptManagement.getReplacedPersoName(p_name);
// 2) Look for translation
result = UIText.getGameText("people."+name);
if (result.startsWith("people.")) {
result = name; // Nothing found in translation
}
result = ZUtils.capitalize(result);
}
return result;
}
/**
* Returns a WaitingDialog object, ready to be added to the dialog queue.
* @param p_client
* @param persoToTalk (can't be null)
* @return WaitingDialog
*/
private WaitingDialog createWaitingDialog(ClientState p_client,
Perso persoToTalk, ActionDialog actionDialog) {
MapDialog dialogs = EngineZildo.mapManagement.getCurrentMap().getMapDialog();
String sentence = null;
String keySentence = null;
currentSentenceFullDisplayed = false;
String whoSpeaking = null;
if (persoToTalk != null) {
// Dialog with character
Behavior behav = dialogs.getBehaviors().get(persoToTalk.getName());
if (behav == null) {
// This perso can't talk, but trigger this although
TriggerElement trig = TriggerElement.createDialogTrigger(persoToTalk.getName(), 1);
EngineZildo.scriptManagement.trigger(trig);
return null;
}
int compteDial = persoToTalk.getCompte_dialogue();
// Dialog switch : adjust sentence according to quest elements
// Do not evaluate if we're in a continuing sentence
if (persoToTalk.getDialogSwitch() != null && !p_client.dialogState.isContinuing()) {
ZSSwitch swi = ZSSwitch.parseForDialog(persoToTalk.getDialogSwitch());
int posSentence = swi.evaluateInt();
if (posSentence > compteDial) {
compteDial = posSentence;
}
}
keySentence = dialogs.getSentence(behav, compteDial);
sentence = UIText.getGameText(keySentence);
// Update perso about next sentence he(she) will say
int posSharp = sentence.indexOf("#");
int posDollar = sentence.indexOf("$sell(");
if (posSharp != -1) {
// La phrase demande explicitement de rediriger vers une autre
persoToTalk.setCompte_dialogue(sentence.charAt(posSharp + 1) - 48);
sentence = sentence.substring(0, posSharp);
} else if (posDollar != -1) {
// This sentence leads to a buying phase
String sellDescription = sentence.substring(posDollar+6, sentence.indexOf(")"));
sentence = sentence.substring(0, posDollar);
p_client.dialogState.actionDialog = new BuyingAction(p_client.zildo, persoToTalk, sellDescription);
} else if (compteDial < 9 && behav.replique[compteDial + 1] != 0) {
// On passe à la suivante, puisqu'elle existe
persoToTalk.setCompte_dialogue(compteDial + 1);
}
// Adventure trigger
TriggerElement trig = TriggerElement.createDialogTrigger(persoToTalk.getName(), compteDial);
EngineZildo.scriptManagement.trigger(trig);
// Set the dialoguing states for each Perso
persoToTalk.setDialoguingWith(p_client.zildo);
whoSpeaking = persoToTalk.getName();
} else if (actionDialog != null) {
// persoToTalk == null
// Ingame event
keySentence = actionDialog.key;
sentence = UIText.getGameText(keySentence);
whoSpeaking = actionDialog.who;
p_client.dialogState.actionDialog = actionDialog;
}
whoSpeaking = getPeopleName(whoSpeaking);
// Dialog history
String mapName = EngineZildo.mapManagement.getCurrentMap().getName();
EngineZildo.game.recordDialog(keySentence, whoSpeaking, mapName);
return new WaitingDialog(whoSpeaking, sentence, null, false, p_client == null ? null
: p_client.location);
}
public void continueDialog(ClientState p_client) {
WaitingDialog even = createWaitingDialog(p_client, p_client.zildo.getDialoguingWith(), null);
boolean continuing = false;
if (even != null) {
continuing = even.sentence.indexOf("@") != -1;
even.sentence = even.sentence.trim();
even.action = CommandDialog.CONTINUE;
dialogQueue.add(even);
}
p_client.dialogState.setContinuing(continuing);
}
/**
* Stop a dialog, when user press key, or brutally when zildo gets hurt.
* @param p_client
* @param p_brutal TRUE=Zildo leaves brutally his interlocutor
*/
public void stopDialog(ClientState p_client, boolean p_brutal) {
p_client.dialogState.setDialoguing(false);
PersoPlayer zildo=p_client.zildo;
Perso perso=p_client.zildo.getDialoguingWith();
zildo.setDialoguingWith(null);
if (perso != null) {
perso.setDialoguingWith(null);
}
ActionDialog actionDialog=p_client.dialogState.actionDialog;
if( p_brutal) {
actOnDialog(p_client.location, CommandDialog.STOP);
} else if (actionDialog != null) {
actionDialog.launchAction(p_client);
p_client.dialogState.actionDialog=null;
}
}
public void goOnDialog(ClientState p_client) {
if (p_client.dialogState.isContinuing() && currentSentenceFullDisplayed) {
continueDialog(p_client);
} else {
actOnDialog(p_client.location, CommandDialog.ACTION);
}
}
public void actOnDialog(TransferObject p_location, CommandDialog p_actionDialog) {
dialogQueue.add(new WaitingDialog(null, null, p_actionDialog, false, p_location));
}
public void writeConsole(String p_sentence) {
dialogQueue.add(new WaitingDialog(null, p_sentence, null, true, null));
}
public List<WaitingDialog> getQueue() {
return dialogQueue;
}
public void resetQueue() {
dialogQueue.clear();
}
public void setFullSentenceDisplayed() {
currentSentenceFullDisplayed = true;
}
} | lgpl-3.0 |
peerkar/liferay-gsearch | liferay-gsearch-workspace/modules/gsearch-rest/src/main/java/fi/soveltia/liferay/gsearch/rest/application/GSearchRestApplication.java | 10032 |
package fi.soveltia.liferay.gsearch.rest.application;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.search.Field;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.LocaleUtil;
import com.liferay.portal.kernel.util.Validator;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.jaxrs.whiteboard.JaxrsWhiteboardConstants;
import fi.soveltia.liferay.gsearch.core.api.GSearch;
import fi.soveltia.liferay.gsearch.core.api.configuration.CoreConfigurationHelper;
import fi.soveltia.liferay.gsearch.core.api.constants.ParameterNames;
import fi.soveltia.liferay.gsearch.core.api.query.context.QueryContext;
import fi.soveltia.liferay.gsearch.core.api.query.context.QueryContextBuilder;
import fi.soveltia.liferay.gsearch.core.api.suggest.GSearchKeywordSuggester;
import fi.soveltia.liferay.gsearch.localization.api.LocalizationHelper;
import fi.soveltia.liferay.gsearch.recommender.api.RecommenderService;
/**
* Liferay GSearch REST API.
*
* @author Petteri Karttunen
*/
@Component(
immediate = true,
property = {
"auth.verifier.auth.verifier.BasicAuthHeaderAuthVerifier.urls.includes=/*",
"auth.verifier.auth.verifier.PortalSessionAuthVerifier.urls.includes=/*",
JaxrsWhiteboardConstants.JAX_RS_APPLICATION_BASE + "=/gsearch-rest",
JaxrsWhiteboardConstants.JAX_RS_NAME + "=Gsearch.Rest"
},
service = Application.class
)
public class GSearchRestApplication extends Application {
@GET
@Path("/recommendations/{languageId}")
@Produces({MediaType.APPLICATION_JSON})
public String getRecommendations(
@Context HttpServletRequest httpServletRequest,
@PathParam("languageId") String languageId,
@QueryParam("assetEntryId") Long[] assetEntryId,
@QueryParam("text") String[] text,
@QueryParam("count") Integer count,
@QueryParam("includeAssetTags") Boolean includeAssetTags,
@QueryParam("includeAssetCategories") Boolean includeAssetCategories,
@QueryParam("includeThumbnail") Boolean includeThumbnail,
@QueryParam("includeUserPortrait") Boolean includeUserPortrait) {
JSONObject results = JSONFactoryUtil.createJSONObject();
if (Validator.isNull(languageId)) {
return results.toString();
}
Locale locale = LocaleUtil.fromLanguageId(languageId);
try {
QueryContext queryContext = _queryContextBuilder.buildQueryContext(
httpServletRequest, locale, null);
queryContext.setPageSize(GetterUtil.getInteger(count, 5));
queryContext.setStart(0);
queryContext.setParameter(ParameterNames.PATH_IMAGE, "/image");
queryContext.setParameter(
ParameterNames.INCLUDE_THUMBNAIL,
GetterUtil.getBoolean(includeThumbnail));
queryContext.setParameter(
ParameterNames.INCLUDE_USER_PORTRAIT,
GetterUtil.getBoolean(includeUserPortrait));
Map<String, Class<?>> additionalResultFields = new HashMap<>();
if (GetterUtil.get(includeAssetCategories, false)) {
additionalResultFields.put(
"assetCategoryTitles_en_US", String[].class);
}
if (GetterUtil.get(includeAssetTags, false)) {
additionalResultFields.put(Field.ASSET_TAG_NAMES, String[].class);
}
additionalResultFields.put(Field.ENTRY_CLASS_NAME, String.class);
additionalResultFields.put(Field.ENTRY_CLASS_PK, String.class);
queryContext.setParameter(
ParameterNames.ADDITIONAL_RESULT_FIELDS,
additionalResultFields);
// Optional recommendation texts for MLT query.
queryContext.setParameter(
ParameterNames.TEXTS, text);
results = _recommenderService.getRecommendationsByAssetEntryIds(
assetEntryId, queryContext);
if (results == null) {
return JSONFactoryUtil.createJSONObject().toString();
}
_localizationHelper.setResultTypeLocalizations(locale, results);
_processResultFacets(locale, results);
}
catch (Exception e) {
e.printStackTrace();
}
return results.toString();
}
@GET
@Path("/search/{languageId}/{keywords}")
@Produces({MediaType.APPLICATION_JSON})
public String getSearchResults(
@Context HttpServletRequest httpServletRequest,
@PathParam("languageId") String languageId,
@PathParam("keywords") String keywords,
@QueryParam("start") Integer start,
@QueryParam("pageSize") Integer pageSize,
@QueryParam("sortField") String sortField,
@QueryParam("sortDirection") String sortDirection,
@QueryParam("groupId") Long groupId,
@QueryParam("includeAssetTags") Boolean includeAssetTags,
@QueryParam("includeAssetCategories") Boolean includeAssetCategories,
@QueryParam("includeThumbnail") Boolean includeThumbnail,
@QueryParam("includeUserPortrait") Boolean includeUserPortrait,
@QueryParam("time") String time,
@QueryParam("dateFormat") String dateFormat,
@QueryParam("timeFrom") String timeFrom,
@QueryParam("timeTo") String timeTo) {
JSONObject results = JSONFactoryUtil.createJSONObject();
if (Validator.isNull(languageId)) {
return results.toString();
}
Locale locale = LocaleUtil.fromLanguageId(languageId);
Map<String, Object> parameters = new HashMap<>();
parameters.put(ParameterNames.LOCALE, locale);
parameters.put(ParameterNames.KEYWORDS, keywords);
if (groupId != null) {
parameters.put(ParameterNames.GROUP_ID, groupId);
}
parameters.put(ParameterNames.START, GetterUtil.get(start, 0));
parameters.put(ParameterNames.SORT_FIELD, sortField);
parameters.put(ParameterNames.SORT_DIRECTION, sortDirection);
if (Validator.isNotNull(time)) {
parameters.put(ParameterNames.TIME, time);
parameters.put(ParameterNames.TIME_FROM, timeFrom);
parameters.put(ParameterNames.TIME_TO, timeTo);
parameters.put(ParameterNames.DATE_FORMAT, dateFormat);
}
try {
QueryContext queryContext = _queryContextBuilder.buildQueryContext(
httpServletRequest, locale, null, null, null, null, null, null, keywords);
queryContext.setPageSize(GetterUtil.get(pageSize, 10));
queryContext.setParameter(ParameterNames.PATH_IMAGE, "/image");
_queryContextBuilder.parseParametersHeadless(queryContext, parameters);
// Process query context contributors.
_queryContextBuilder.processQueryContextContributors(queryContext);
queryContext.setParameter(
ParameterNames.INCLUDE_THUMBNAIL,
GetterUtil.getBoolean(includeThumbnail));
queryContext.setParameter(
ParameterNames.INCLUDE_USER_PORTRAIT,
GetterUtil.getBoolean(includeUserPortrait));
Map<String, Class<?>> additionalResultFields = new HashMap<>();
if (GetterUtil.get(includeAssetCategories, false)) {
additionalResultFields.put(
Field.ASSET_CATEGORY_TITLES, String[].class);
}
if (GetterUtil.get(includeAssetTags, false)) {
additionalResultFields.put(Field.ASSET_TAG_NAMES, String[].class);
}
additionalResultFields.put(Field.ENTRY_CLASS_NAME, String.class);
additionalResultFields.put(Field.ENTRY_CLASS_PK, String.class);
queryContext.setParameter(
ParameterNames.ADDITIONAL_RESULT_FIELDS,
additionalResultFields);
results = _gSearch.getSearchResults(queryContext);
_localizationHelper.setResultTypeLocalizations(locale, results);
_processResultFacets(locale, results);
}
catch (Exception e) {
e.printStackTrace();
}
return results.toString();
}
public Set<Object> getSingletons() {
return Collections.<Object>singleton(this);
}
@GET
@Path("/suggestions/{companyId}/{groupId}/{languageId}/{keywords}")
@Produces({MediaType.APPLICATION_JSON})
public String getSuggestions(
@Context HttpServletRequest httpServletRequest,
@PathParam("companyId") Integer companyId,
@PathParam("groupId") Integer groupId,
@PathParam("languageId") String languageId,
@PathParam("keywords") String keywords) {
JSONArray results = JSONFactoryUtil.createJSONArray();
if (Validator.isNull(companyId) || Validator.isNull(groupId) ||
Validator.isNull(languageId) || Validator.isNull(keywords)) {
return results.toString();
}
try {
Locale locale = LocaleUtil.fromLanguageId(languageId);
QueryContext queryContext =
_queryContextBuilder.buildSuggesterQueryContext(
httpServletRequest, null, groupId, locale, keywords);
results = _gSearchKeywordSuggester.getSuggestions(queryContext);
}
catch (Exception e) {
e.printStackTrace();
}
return results.toString();
}
/**
* Format facets for displaying.
*
* @param locale
* @param responseObject
*/
private void _processResultFacets(Locale locale, JSONObject responseObject) {
JSONArray facets = responseObject.getJSONArray("facets");
if ((facets == null) || (facets.length() == 0)) {
return;
}
for (int i = 0; i < facets.length(); i++) {
JSONObject resultItem = facets.getJSONObject(i);
JSONArray values = resultItem.getJSONArray("values");
for (int j = 0; j < values.length(); j++) {
JSONObject value = values.getJSONObject(j);
value.put(
"text",
_localizationHelper.getLocalization(
locale,
value.getString(
"name"
).toLowerCase()) + " (" + value.getString("frequency") +
")");
}
}
}
@Reference
private CoreConfigurationHelper _coreConfigurationHelper;
@Reference
private GSearch _gSearch;
@Reference
private GSearchKeywordSuggester _gSearchKeywordSuggester;
@Reference
private LocalizationHelper _localizationHelper;
@Reference
private QueryContextBuilder _queryContextBuilder;
@Reference
private RecommenderService _recommenderService;
} | lgpl-3.0 |
vamsirajendra/sonarqube | server/sonar-server/src/main/java/org/sonar/server/computation/taskprocessor/CeTaskProcessor.java | 2487 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.server.computation.taskprocessor;
import java.util.Set;
import javax.annotation.CheckForNull;
import org.sonar.server.computation.queue.CeTask;
import org.sonar.server.computation.queue.CeTaskResult;
/**
* This interface is used to provide the processing code for {@link CeTask}s of one or more type to be called by the
* Compute Engine.
*/
public interface CeTaskProcessor {
/**
* The {@link CeTask#getType()} for which this {@link CeTaskProcessor} provides the processing code.
* <p>
* The match of type is done using {@link String#equals(Object)} and if more than one {@link CeTaskProcessor} declares
* itself had handler for the same {@link CeTask#getType()}, an error will be raised at startup and startup will
* fail.
* </p>
* <p>
* If an empty {@link Set} is returned, the {@link CeTaskProcessor} will be ignored.
* </p>
*/
Set<String> getHandledCeTaskTypes();
/**
* Calls the processing code for a specific {@link CeTask} which will optionally return a {@link CeTaskResult}
* holding information to be persisted in the processing history of the Compute Engine (currently the {@code CE_ACTIVITY} table).
* <p>
* The specified is guaranteed to be non {@code null} and its {@link CeTask#getType()} to be one of the values
* of {@link #getHandledCeTaskTypes()}.
* </p>
*
* @throws RuntimeException when thrown, it will be caught and logged by the Compute Engine and the processing of the
* specified {@link CeTask} will be flagged as failed.
*/
@CheckForNull
CeTaskResult process(CeTask task);
}
| lgpl-3.0 |
Lomeli12/BrewLib | src/main/java/net/lomeli/brewlib/core/ContainerBrewingStand.java | 5647 | package net.lomeli.brewlib.core;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.ICrafting;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.AchievementList;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.lomeli.brewlib.api.PotionRegistry;
import net.lomeli.brewlib.blocks.TileBrewingStand;
public class ContainerBrewingStand extends Container {
private TileBrewingStand tile;
private final Slot theSlot;
private int brewTime;
public ContainerBrewingStand(InventoryPlayer playerInv, TileBrewingStand tile) {
this.tile = tile;
this.addSlotToContainer(new ContainerBrewingStand.Potion(playerInv.player, tile, 0, 56, 46));
this.addSlotToContainer(new ContainerBrewingStand.Potion(playerInv.player, tile, 1, 79, 53));
this.addSlotToContainer(new ContainerBrewingStand.Potion(playerInv.player, tile, 2, 102, 46));
this.theSlot = this.addSlotToContainer(new ContainerBrewingStand.Ingredient(tile, 3, 79, 17));
int i;
for (i = 0; i < 3; ++i) {
for (int j = 0; j < 9; ++j) {
this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i) {
this.addSlotToContainer(new Slot(playerInv, i, 8 + i * 18, 142));
}
}
@Override
public void addCraftingToCrafters(ICrafting listener) {
super.addCraftingToCrafters(listener);
listener.func_175173_a(this, this.tile);
}
@Override
public void detectAndSendChanges() {
super.detectAndSendChanges();
for (int i = 0; i < this.crafters.size(); ++i) {
ICrafting icrafting = (ICrafting) this.crafters.get(i);
if (this.brewTime != this.tile.getField(0))
icrafting.sendProgressBarUpdate(this, 0, this.tile.getField(0));
}
this.brewTime = this.tile.getField(0);
}
@SideOnly(Side.CLIENT)
@Override
public void updateProgressBar(int id, int data) {
this.tile.setField(id, data);
}
@Override
public boolean canInteractWith(EntityPlayer player) {
return tile.isUseableByPlayer(player);
}
@Override
public ItemStack transferStackInSlot(EntityPlayer player, int index) {
ItemStack itemstack = null;
Slot slot = (Slot) this.inventorySlots.get(index);
if (slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if ((index < 0 || index > 2) && index != 3) {
if (!this.theSlot.getHasStack() && this.theSlot.isItemValid(itemstack1)) {
if (!this.mergeItemStack(itemstack1, 3, 4, false))
return null;
} else if (ContainerBrewingStand.Potion.canHoldPotion(itemstack)) {
if (!this.mergeItemStack(itemstack1, 0, 3, false))
return null;
} else if (index >= 4 && index < 31) {
if (!this.mergeItemStack(itemstack1, 31, 40, false))
return null;
} else if (index >= 31 && index < 40) {
if (!this.mergeItemStack(itemstack1, 4, 31, false))
return null;
} else if (!this.mergeItemStack(itemstack1, 4, 40, false))
return null;
} else {
if (!this.mergeItemStack(itemstack1, 4, 40, true))
return null;
slot.onSlotChange(itemstack1, itemstack);
}
if (itemstack1.stackSize == 0)
slot.putStack((ItemStack) null);
else
slot.onSlotChanged();
if (itemstack1.stackSize == itemstack.stackSize)
return null;
slot.onPickupFromSlot(player, itemstack1);
}
return itemstack;
}
static class Ingredient extends Slot {
public Ingredient(IInventory inventory, int slotNum, int x, int y) {
super(inventory, slotNum, x, y);
}
@Override
public boolean isItemValid(ItemStack stack) {
return stack != null ? PotionRegistry.getInstance().isPotionIngredient(stack) : false;
}
@Override
public int getSlotStackLimit() {
return 64;
}
}
static class Potion extends Slot {
private EntityPlayer player;
public Potion(EntityPlayer player, IInventory inventory, int slotNum, int x, int y) {
super(inventory, slotNum, x, y);
this.player = player;
}
@Override
public boolean isItemValid(ItemStack stack) {
return canHoldPotion(stack);
}
@Override
public int getSlotStackLimit() {
return 1;
}
@Override
public void onPickupFromSlot(EntityPlayer playerIn, ItemStack stack) {
if (stack.getItem() instanceof net.minecraft.item.ItemPotion && stack.getMetadata() > 0)
this.player.triggerAchievement(AchievementList.potion);
super.onPickupFromSlot(playerIn, stack);
}
public static boolean canHoldPotion(ItemStack stack) {
return stack != null && PotionRegistry.getInstance().isValidInput(stack);
}
}
}
| lgpl-3.0 |
thorstenwagner/kdtree | src/main/java/de/biomedical_imaging/edu/wlu/cs/levy/CG/KDException.java | 1316 | // KDException.java : general exception class for KD-Tree library
//
// Copyright (C) Simon D. Levy 2014
//
// This code is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This code 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 Lesser General Public License
// along with this code. If not, see <http://www.gnu.org/licenses/>.
// You should also have received a copy of the Parrot Parrot AR.Drone
// Development License and Parrot AR.Drone copyright notice and disclaimer
// and If not, see
// <https://projects.ardrone.org/attachments/277/ParrotLicense.txt>
// and
// <https://projects.ardrone.org/attachments/278/ParrotCopyrightAndDisclaimer.txt>.
package de.biomedical_imaging.edu.wlu.cs.levy.CG;
public class KDException extends Exception {
protected KDException(String s) {
super(s);
}
public static final long serialVersionUID = 1L;
}
| lgpl-3.0 |
galleon1/chocolate-milk | src/org/chocolate_milk/model/descriptors/ToDoAddRqTypeDescriptor.java | 9837 | /*
* This class was automatically generated with
* <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML
* Schema.
* $Id: ToDoAddRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $
*/
package org.chocolate_milk.model.descriptors;
//---------------------------------/
//- Imported classes and packages -/
//---------------------------------/
import org.chocolate_milk.model.ToDoAddRqType;
/**
* Class ToDoAddRqTypeDescriptor.
*
* @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $
*/
public class ToDoAddRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl {
//--------------------------/
//- Class/Member Variables -/
//--------------------------/
/**
* Field _elementDefinition.
*/
private boolean _elementDefinition;
/**
* Field _nsPrefix.
*/
private java.lang.String _nsPrefix;
/**
* Field _nsURI.
*/
private java.lang.String _nsURI;
/**
* Field _xmlName.
*/
private java.lang.String _xmlName;
/**
* Field _identity.
*/
private org.exolab.castor.xml.XMLFieldDescriptor _identity;
//----------------/
//- Constructors -/
//----------------/
public ToDoAddRqTypeDescriptor() {
super();
_xmlName = "ToDoAddRqType";
_elementDefinition = false;
//-- set grouping compositor
setCompositorAsSequence();
org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null;
org.exolab.castor.mapping.FieldHandler handler = null;
org.exolab.castor.xml.FieldValidator fieldValidator = null;
//-- initialize attribute descriptors
//-- _requestID
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ToDoAddRqType target = (ToDoAddRqType) object;
return target.getRequestID();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ToDoAddRqType target = (ToDoAddRqType) object;
target.setRequestID( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("string");
desc.setHandler(handler);
desc.setMultivalued(false);
addFieldDescriptor(desc);
//-- validation code for: _requestID
fieldValidator = new org.exolab.castor.xml.FieldValidator();
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
}
desc.setValidator(fieldValidator);
//-- initialize element descriptors
//-- _toDoAdd
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.ToDoAdd.class, "_toDoAdd", "ToDoAdd", org.exolab.castor.xml.NodeType.Element);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ToDoAddRqType target = (ToDoAddRqType) object;
return target.getToDoAdd();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ToDoAddRqType target = (ToDoAddRqType) object;
target.setToDoAdd( (org.chocolate_milk.model.ToDoAdd) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("org.chocolate_milk.model.ToDoAdd");
desc.setHandler(handler);
desc.setRequired(true);
desc.setMultivalued(false);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _toDoAdd
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(1);
{ //-- local scope
}
desc.setValidator(fieldValidator);
//-- _includeRetElementList
desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeRetElementList", "IncludeRetElement", org.exolab.castor.xml.NodeType.Element);
desc.setImmutable(true);
handler = new org.exolab.castor.xml.XMLFieldHandler() {
@Override
public java.lang.Object getValue( java.lang.Object object )
throws IllegalStateException
{
ToDoAddRqType target = (ToDoAddRqType) object;
return target.getIncludeRetElement();
}
@Override
public void setValue( java.lang.Object object, java.lang.Object value)
throws IllegalStateException, IllegalArgumentException
{
try {
ToDoAddRqType target = (ToDoAddRqType) object;
target.addIncludeRetElement( (java.lang.String) value);
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException {
try {
ToDoAddRqType target = (ToDoAddRqType) object;
target.removeAllIncludeRetElement();
} catch (java.lang.Exception ex) {
throw new IllegalStateException(ex.toString());
}
}
@Override
@SuppressWarnings("unused")
public java.lang.Object newInstance(java.lang.Object parent) {
return null;
}
};
desc.setSchemaType("list");
desc.setComponentType("string");
desc.setHandler(handler);
desc.setMultivalued(true);
addFieldDescriptor(desc);
addSequenceElement(desc);
//-- validation code for: _includeRetElementList
fieldValidator = new org.exolab.castor.xml.FieldValidator();
fieldValidator.setMinOccurs(0);
{ //-- local scope
org.exolab.castor.xml.validators.StringValidator typeValidator;
typeValidator = new org.exolab.castor.xml.validators.StringValidator();
fieldValidator.setValidator(typeValidator);
typeValidator.setWhiteSpace("preserve");
typeValidator.setMaxLength(50);
}
desc.setValidator(fieldValidator);
}
//-----------/
//- Methods -/
//-----------/
/**
* Method getAccessMode.
*
* @return the access mode specified for this class.
*/
@Override()
public org.exolab.castor.mapping.AccessMode getAccessMode(
) {
return null;
}
/**
* Method getIdentity.
*
* @return the identity field, null if this class has no
* identity.
*/
@Override()
public org.exolab.castor.mapping.FieldDescriptor getIdentity(
) {
return _identity;
}
/**
* Method getJavaClass.
*
* @return the Java class represented by this descriptor.
*/
@Override()
public java.lang.Class getJavaClass(
) {
return org.chocolate_milk.model.ToDoAddRqType.class;
}
/**
* Method getNameSpacePrefix.
*
* @return the namespace prefix to use when marshaling as XML.
*/
@Override()
public java.lang.String getNameSpacePrefix(
) {
return _nsPrefix;
}
/**
* Method getNameSpaceURI.
*
* @return the namespace URI used when marshaling and
* unmarshaling as XML.
*/
@Override()
public java.lang.String getNameSpaceURI(
) {
return _nsURI;
}
/**
* Method getValidator.
*
* @return a specific validator for the class described by this
* ClassDescriptor.
*/
@Override()
public org.exolab.castor.xml.TypeValidator getValidator(
) {
return this;
}
/**
* Method getXMLName.
*
* @return the XML Name for the Class being described.
*/
@Override()
public java.lang.String getXMLName(
) {
return _xmlName;
}
/**
* Method isElementDefinition.
*
* @return true if XML schema definition of this Class is that
* of a global
* element or element with anonymous type definition.
*/
public boolean isElementDefinition(
) {
return _elementDefinition;
}
}
| lgpl-3.0 |
iTitus/GimmeStuff | src/main/java/io/github/ititus/gimmestuff/tile/TileInfiniteStuff.java | 3501 | package io.github.ititus.gimmestuff.tile;
import java.util.List;
import com.google.common.collect.Lists;
import io.github.ititus.gimmestuff.util.Utils;
import io.github.ititus.gimmestuff.util.stuff.ModuleConfiguration;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTankInfo;
import net.minecraftforge.fluids.IFluidHandler;
public class TileInfiniteStuff extends TileBase implements ITickable, IFluidHandler {
private final TileEntity[] neighborTiles;
private final ModuleConfiguration configuration;
private boolean updateNeighbors;
public TileInfiniteStuff() {
this.configuration = new ModuleConfiguration();
this.neighborTiles = new TileEntity[EnumFacing.VALUES.length];
this.updateNeighbors = true;
}
public ModuleConfiguration getConfiguration() {
return configuration;
}
@Override
public void readFromCustomNBT(NBTTagCompound compound) {
configuration.deserializeNBT(compound.getCompoundTag("configuration"));
}
@Override
public NBTTagCompound writeToCustomNBT(NBTTagCompound compound) {
compound.setTag("configuration", configuration.serializeNBT());
return compound;
}
@Override
public void update() {
if (!worldObj.isRemote) {
if (!updateNeighbors) {
for (TileEntity tile : neighborTiles) {
if (tile != null && tile.isInvalid()) {
updateNeighbors = true;
}
}
}
if (updateNeighbors) {
doUpdateNeighbors();
}
configuration.update(this);
}
}
private void doUpdateNeighbors() {
if (updateNeighbors && worldObj != null) {
Utils.clear(neighborTiles);
for (EnumFacing facing : EnumFacing.VALUES) {
BlockPos offsetPos = pos.offset(facing);
IBlockState state = worldObj.getBlockState(offsetPos);
if (state.getBlock().hasTileEntity(state)) {
TileEntity offsetTile = worldObj.getTileEntity(offsetPos);
if (offsetTile != null && !offsetTile.isInvalid()) {
neighborTiles[facing.getIndex()] = offsetTile;
}
}
}
updateNeighbors = false;
}
}
public void updateNeighbors() {
if (worldObj == null || !worldObj.isRemote) {
this.updateNeighbors = true;
}
}
public TileEntity[] getNeighborTiles() {
return neighborTiles;
}
@Override
public int fill(EnumFacing from, FluidStack resource, boolean doFill) {
return resource != null && configuration.fill(from, resource, doFill, this) ? resource.amount : 0;
}
@Override
public FluidStack drain(EnumFacing from, FluidStack resource, boolean doDrain) {
return resource != null && configuration.drain(from, resource, doDrain, this) ? resource : null;
}
@Override
public FluidStack drain(EnumFacing from, int maxDrain, boolean doDrain) {
return configuration.drain(from, maxDrain, doDrain, this);
}
@Override
public boolean canFill(EnumFacing from, Fluid fluid) {
return configuration.canFill(from, fluid, this);
}
@Override
public boolean canDrain(EnumFacing from, Fluid fluid) {
return configuration.canDrain(from, fluid, this);
}
@Override
public FluidTankInfo[] getTankInfo(EnumFacing from) {
List<FluidTankInfo> list = Lists.newArrayList();
configuration.addTankInfo(from, list, this);
return list.toArray(new FluidTankInfo[list.size()]);
}
}
| lgpl-3.0 |
deltaforge/nebu-common-java | src/main/java/nl/bitbrains/nebu/common/factories/VirtualMachineFactory.java | 3892 | package nl.bitbrains.nebu.common.factories;
import java.text.ParseException;
import nl.bitbrains.nebu.common.VirtualMachine;
import nl.bitbrains.nebu.common.VirtualMachineBuilder;
import nl.bitbrains.nebu.common.VirtualMachine.Status;
import nl.bitbrains.nebu.common.topology.factory.PhysicalHostFactory;
import nl.bitbrains.nebu.common.topology.factory.PhysicalStoreFactory;
import nl.bitbrains.nebu.common.util.xml.XMLFactory;
import org.jdom2.Attribute;
import org.jdom2.Element;
/**
* Converts {@link VirtualMachine} objects to and from XML.
*
* @author Jesse Donkervliet, Tim Hegeman, and Stefan Hugtenburg
*
*/
public class VirtualMachineFactory extends IdentifiableFactory implements
XMLFactory<VirtualMachine> {
public static final String TAG_ELEMENT_ROOT = "virtualmachine";
public static final String TAG_LIST_ELEMENT_ROOT = "virtualmachines";
public static final String TAG_HOSTNAME = "hostname";
public static final String TAG_STATUS = "status";
public static final String TAG_HOST = PhysicalHostFactory.TAG_ELEMENT_ROOT;
public static final String TAG_DISK = PhysicalStoreFactory.TAG_ELEMENT_ROOT;
private final boolean extensive;
/**
* Empty default constructor.
*/
public VirtualMachineFactory() {
this(true);
}
/**
* @param extensive
* indicates whether or not the full xml should be written/read.
*/
public VirtualMachineFactory(final boolean extensive) {
this.extensive = extensive;
}
/**
* Converts the {@link VirtualMachine} to XML.
*
* @param object
* to convert to XML.
* @return the created XML element.
*/
public final Element toXML(final VirtualMachine object) {
final Element elem = super.createRootXMLElement(object,
VirtualMachineFactory.TAG_ELEMENT_ROOT);
if (this.extensive) {
elem.addContent(new Element(VirtualMachineFactory.TAG_HOSTNAME).addContent(object
.getHostname()));
elem.addContent(new Element(VirtualMachineFactory.TAG_STATUS).addContent(object
.getStatus().toString()));
elem.addContent(new Element(VirtualMachineFactory.TAG_HOST)
.setAttribute(IdentifiableFactory.TAG_ID, object.getHost()));
for (final String store : object.getStores()) {
elem.addContent(new Element(VirtualMachineFactory.TAG_DISK)
.setAttribute(IdentifiableFactory.TAG_ID, store));
}
}
return elem;
}
/**
* Creates a {@link VirtualMachine} from XML.
*
* @param xml
* element to base the object on.
* @return the created {@link VirtualMachine}.
* @throws ParseException
* if XML is not valid.
*/
public final VirtualMachineBuilder fromXML(final Element xml) throws ParseException {
super.throwIfInvalidRoot(xml, VirtualMachineFactory.TAG_ELEMENT_ROOT);
final Attribute idAttribute = super.getAttribute(xml, IdentifiableFactory.TAG_ID);
final VirtualMachineBuilder builder = new VirtualMachineBuilder();
builder.withUuid(idAttribute.getValue());
if (this.extensive) {
builder.withHostname(xml.getChildText(VirtualMachineFactory.TAG_HOSTNAME))
.withStatus(Status.valueOf(xml.getChildText(VirtualMachineFactory.TAG_STATUS)))
.withHost(xml.getChild(VirtualMachineFactory.TAG_HOST)
.getAttributeValue(IdentifiableFactory.TAG_ID));
for (final Element elem : xml.getChildren(VirtualMachineFactory.TAG_DISK)) {
builder.withDisk(elem.getAttributeValue(IdentifiableFactory.TAG_ID));
}
}
return builder;
}
}
| lgpl-3.0 |