answer
stringlengths 17
10.2M
|
|---|
package com.google.sprint1;
import com.metaio.sdk.MetaioDebug;
import com.metaio.tools.io.AssetsManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.nsd.NsdServiceInfo;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Activity to handle the screen between mainmenu and the gamescreen
*
* where players should connect to each other before entering gamemode.
*
*
*/
public class NetworkActivity extends Activity {
Handler mNSDHandler;
//Variable that indicates if user is host
private boolean isHost = false;
public static final String TAG = "NetworkActivity";
private ListView serviceListView;
// Function to set up layout of activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_network);
NetworkState.getState().init(this);
// TODO E/AndroidRuntime(17132): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.google.sprint1/com.google.sprint1.NetworkActivity}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.ListView
serviceListView = (ListView) findViewById(R.id.serviceListView);
serviceListView.setAdapter(NetworkState.getState().getAdapter());
serviceListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
// When clicking on a service, an AlertDialog window pops up
// to allow you to connect to said service.
public void onItemClick(AdapterView parent, View view,
final int pos, long id) {
// Instantiate an AlertDialog.Builder with its
// constructor
AlertDialog.Builder builder = new AlertDialog.Builder(
NetworkActivity.this);
builder.setMessage(
"Connect to "
+ NetworkState.getState().getAdapter().getItem(pos) + "?")
.setTitle("Connect")
.setPositiveButton(R.string.BTN_OK,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
NsdServiceInfo service = null;
//If a service name is clicked and the OK button is pressed,
//a loop will compare all names in the listAdapter with the names from
//the serviceList. If they are the same, the correct service to connect
//to is found
for(int i = 0; i < NetworkState.getState().getServiceList().size(); i++){
if(NetworkState.getState().getAdapter().getItem(pos).equals(NetworkState.getState().getServiceList().get(i).getServiceName())){
service = NetworkState.getState().getServiceList().get(i);
}
}
service = NetworkState.getState().getNsdHelper()
.resolveService(service);
if (service != null) {
Log.d(TAG,
"Connecting to: "
+ service
.getServiceName());
NetworkState.getState().getMobileConnection().connectToPeer(
service.getHost());
//TODO : Go to Lobby
Intent intentlobby = new Intent(NetworkActivity.this, LobbyActivity.class);
startActivity(intentlobby);
} else {
Log.d(TAG,
"No service to connect to!");
}
}
})
.setNegativeButton(R.string.BTN_CANCEL,
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
// TODO Auto-generated method
// stub
}
}).create().show();
}
});
}
/**
* Called when the user clicks the back arrow button
*/
public void backArrow(View view) {
//Unregister if the registration state is true.
if(NetworkState.getState().getNsdHelper().getRegistrationState()
&& NetworkState.getState().getNsdHelper() != null){
NetworkState.getState().getNsdHelper().unregisterService();
}
NetworkState.getState().setNsdHelperToNull();
Intent intentmenu = new Intent(this, MainActivity.class);
startActivity(intentmenu);
}
/**
* Called when the user clicks the Host Game button
*/
public void hostGame(View view){
Context context = getApplicationContext();
CharSequence text = "Game created successfully!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
//If user is not already host and the registration state is false,
//register/host a game
if(!isHost && !NetworkState.getState().getNsdHelper().getRegistrationState())
NetworkState.getState().getNsdHelper().registerService(MobileConnection.SERVER_PORT);
isHost = true;
//TODO: Check if registration is successfull
toast.show();
//if(NetworkState.getState().getNsdHelper().getRegistrationState()){
Intent intentlobby = new Intent(this, LobbyActivity.class);
startActivity(intentlobby);
}
/**
* Called when user minimize the window or clicks home button
*/
@Override
protected void onPause() {
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
//Stops service discovery if mNsdHelper is still initialized.
if (NetworkState.getState().getNsdHelper() != null) {
NetworkState.getState().getNsdHelper().stopDiscovery();
}
super.onPause();
}
/**
* Called when after onStart() when a new instance of NetworkActivity is
* started and when ever the user enters the activity from a paused state
*/
@Override
protected void onResume() {
super.onResume();
//If mNsdHelper is null(which happens if activity return after call to
//onPause() it will create a new NsdHelper and initialize it.
if(NetworkState.getState().getNsdHelper() == null)
NetworkState.getState().initNsdHelper();
//Starts service discovery when when starting activity for the first
//or when returing from a paused state.
if (NetworkState.getState().getNsdHelper() != null)
NetworkState.getState().getNsdHelper().discoverServices();
//Checks if the user is a host and register a service accordingly.
if(isHost)
NetworkState.getState().getNsdHelper().registerService(MobileConnection.SERVER_PORT);
}
/**
* Called when user exits the Activity or pausing and then destroy the app
* by brute force
*/
protected void onDestroy() {
// Check if mNsdHelper is not null(will throw NullPointerException
// otherwise) and stops service discovery.
if (NetworkState.getState().getNsdHelper() != null) {
NetworkState.getState().getNsdHelper().stopDiscovery();
}
//Checks state of mNsdHelper, isHost and registration state to prevent
//crash.
if(NetworkState.getState().getNsdHelper() != null && isHost
&& NetworkState.getState().getNsdHelper().getRegistrationState()){
NetworkState.getState().getNsdHelper().unregisterService();
}
super.onDestroy();
}
}
|
package rtdc.core.service;
import rtdc.core.Bootstrapper;
import rtdc.core.Config;
import rtdc.core.event.ErrorEvent;
import rtdc.core.event.Event;
import rtdc.core.impl.HttpRequest;
import rtdc.core.impl.HttpResponse;
import rtdc.core.json.JSONException;
import rtdc.core.json.JSONObject;
import rtdc.core.model.Action;
import rtdc.core.model.Unit;
import rtdc.core.model.User;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.logging.Logger;
import static rtdc.core.impl.HttpRequest.RequestMethod.*;
public final class Service {
private static final String URL = "http://"+ Config.SERVER_IP+":8888/api/";
private static final Logger logger = Logger.getLogger(Service.class.getCanonicalName());
private Service(){}
public static void authenticateUser(String username, String password){
HttpRequest req = Bootstrapper.FACTORY.newHttpRequest(URL + "authenticate", POST);
req.addParameter("username", username);
req.addParameter("password", password);
executeRequest(req);
}
public static void isAuthTokenValid(){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "authenticate/tokenValid", POST));
}
public static void logout(){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "authenticate/logout", POST));
}
public static void getUnits(){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "units", GET));
}
public static void updateOrSaveUnit(Unit unit){
HttpRequest req = Bootstrapper.FACTORY.newHttpRequest(URL + "units", PUT);
req.addParameter("unit", unit.toString());
executeRequest(req);
}
public static void deleteUnit(int unitId){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "units/" + unitId, DELETE));
}
public static void getUsers(){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "users", GET));
}
public static void updateOrSaveUser(User user, String password){
HttpRequest req = Bootstrapper.FACTORY.newHttpRequest(URL + "users", PUT);
req.addParameter("user", user.toString());
req.addParameter("password", password);
executeRequest(req);
}
public static void deleteUser(int userId){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "users/" + userId, DELETE));
}
public static void getActions(){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "actions", GET));
}
public static void updateOrSaveActions(Action action){
HttpRequest req = Bootstrapper.FACTORY.newHttpRequest(URL + "actions", PUT);
req.addParameter("action", action.toString());
executeRequest(req);
}
public static void deleteAction(int actionId){
executeRequest(Bootstrapper.FACTORY.newHttpRequest(URL + "actions/" + actionId, DELETE));
}
private static void executeRequest(HttpRequest request){
request.setContentType("application/x-www-form-urlencoded");
request.setHeader(HttpHeadersName.AUTH_TOKEN, Bootstrapper.AUTHENTICATION_TOKEN);
request.execute(new AsyncCallback<HttpResponse>() {
@Override
public void onSuccess(HttpResponse resp) {
if(resp.getStatusCode() != 200)
new ErrorEvent("Error code " + resp.getStatusCode() + " " + resp.getContent()).fire();
else {
try {
JSONObject object = new JSONObject(resp.getContent());
Event.fire(object);
} catch (JSONException e) {
new ErrorEvent("Unrecognized output from server " + resp.getContent() + " " + e.getMessage()).fire();
}
}
}
@Override
public void onError(String message) {
new ErrorEvent("Network error " + message).fire();
}
});
}
}
|
package mainpackage;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class PlayerInput implements KeyListener
{
private int gameScreen;
public PlayerInput()
{
}
public void menuOrGame(int gameScreen)
{
this.gameScreen = gameScreen;
}
@Override
public void keyPressed(KeyEvent e)
{
int keyPressed = e.getKeyCode();
if (gameScreen == 0)
{
switch (keyPressed)
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_ENTER:
break;
}
}
else
{
switch (keyPressed)
{
case KeyEvent.VK_LEFT:
break;
case KeyEvent.VK_RIGHT:
break;
case KeyEvent.VK_M:
break;
case KeyEvent.VK_N:
break;
case KeyEvent.VK_B:
break;
case KeyEvent.VK_SPACE:
break;
}
}
}
@Override
public void keyReleased(KeyEvent e)
{
}
@Override
public void keyTyped(KeyEvent e)
{
}
}
|
package ae3.dao;
import ae3.model.*;
import ae3.service.structuredquery.EfvTree;
import ae3.util.AtlasProperties;
import ucar.ma2.ArrayChar;
import ucar.ma2.IndexIterator;
import ucar.ma2.InvalidRangeException;
import ucar.nc2.NetcdfFile;
import ucar.nc2.Variable;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* NetCDF file reader
* @author pashky
*/
public class NetCDFReader {
/**
* Default NetCDF path
*/
final static String DEFAULT_LOCATION = AtlasProperties.getProperty("atlas.netCDFlocation");
/**
* Load experimental data using default path
* @param experimentId experiment id
* @return either constructed object or null, if no data files was found for this id
* @throws IOException if i/o error occurs
*/
public static ExperimentalData loadExperiment(final long experimentId) throws IOException {
return loadExperiment(DEFAULT_LOCATION, experimentId);
}
/**
* Load experimental data using default path
* @param netCdfLocation
* @param experimentId experiment id
* @return either constructed object or null, if no data files was found for this id
* @throws IOException if i/o error occurs
*/
public static ExperimentalData loadExperiment(String netCdfLocation, final long experimentId) throws IOException {
ExperimentalData experiment = null;
for(File file : new File(netCdfLocation).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.matches("^" + experimentId + "_[0-9]+(_ratios)?\\.nc$");
}
})) {
if(experiment == null)
experiment = new ExperimentalData();
loadArrayDesign(file.getAbsolutePath(), experiment);
}
return experiment;
}
/**
* Load one array design from file
* @param filename file name to load from
* @param experiment experimental data object, to add data to
* @throws IOException if i/o error occurs
*/
private static void loadArrayDesign(String filename, ExperimentalData experiment) throws IOException {
final NetcdfFile ncfile = NetcdfFile.open(filename);
final Variable varBDC = ncfile.findVariable("BDC");
final Variable varGN = ncfile.findVariable("GN");
final Variable varEFV = ncfile.findVariable("EFV");
final Variable varEF = ncfile.findVariable("EF");
final Variable varSC = ncfile.findVariable("SC");
final Variable varSCV = ncfile.findVariable("SCV");
final Variable varBS2AS = ncfile.findVariable("BS2AS");
final Variable varBS = ncfile.findVariable("BS");
final String arrayDesignAccession = ncfile.findGlobalAttributeIgnoreCase("ADaccession").getStringValue();
final ArrayDesign arrayDesign = new ArrayDesign(arrayDesignAccession);
final int numSamples = varBS.getDimension(0).getLength();
final int numAssays = varEFV.getDimension(1).getLength();
final Map<String,List<String>> efvs = new HashMap<String,List<String>>();
final ArrayChar efData = (ArrayChar) varEF.read();
ArrayChar.StringIterator efvi = ((ArrayChar)varEFV.read()).getStringIterator();
for(ArrayChar.StringIterator i = efData.getStringIterator(); i.hasNext(); ) {
String efStr = i.next();
String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr;
List<String> efvList = new ArrayList<String>(numAssays);
efvs.put(ef, efvList);
for(int j = 0; j < numAssays; ++j) {
efvi.hasNext();
efvList.add(efvi.next());
}
}
final Map<String,List<String>> scvs = new HashMap<String,List<String>>();
if(varSCV != null && varSC != null) {
ArrayChar.StringIterator scvi = ((ArrayChar)varSCV.read()).getStringIterator();
for(ArrayChar.StringIterator i = ((ArrayChar)varSC.read()).getStringIterator(); i.hasNext(); ) {
String scStr = i.next();
String sc = scStr.startsWith("bs_") ? i.next().substring("bs_".length()) : scStr;
List<String> scvList = new ArrayList<String>(numSamples);
scvs.put(sc, scvList);
for(int j = 0; j < numSamples; ++j) {
scvi.hasNext();
scvList.add(scvi.next());
}
}
}
Sample[] samples = new Sample[numSamples];
int[] sampleIds = (int[])varBS.read().get1DJavaArray(Integer.class);
for(int i = 0; i < numSamples; ++i) {
Map<String,String> scvMap = new HashMap<String,String>();
for(String sc : scvs.keySet())
scvMap.put(sc, scvs.get(sc).get(i));
samples[i] = experiment.addSample(scvMap, sampleIds[i]);
}
Assay[] assays = new Assay[numAssays];
for(int i = 0; i < numAssays; ++i) {
Map<String,String> efvMap = new HashMap<String,String>();
for(String ef : efvs.keySet())
efvMap.put(ef, efvs.get(ef).get(i));
assays[i] = experiment.addAssay(arrayDesign, efvMap, i);
}
/*
* Lazy loading of data, matrix is read only for required elements
*/
experiment.setExpressionMatrix(arrayDesign, new ExpressionMatrix() {
int lastDesignElement = -1;
double [] lastData = null;
public double getExpression(int designElementId, int assayId) {
if(lastData != null && designElementId == lastDesignElement)
return lastData[assayId];
int[] shapeBDC = varBDC.getShape();
int[] originBDC = new int[varBDC.getRank()];
originBDC[0] = designElementId;
shapeBDC[0] = 1;
try {
lastData = (double[])varBDC.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class);
} catch(IOException e) {
throw new RuntimeException("Exception during matrix load", e);
} catch (InvalidRangeException e) {
throw new RuntimeException("Exception during matrix load", e);
}
lastDesignElement = designElementId;
return lastData[assayId];
}
});
final Variable varUEFV = ncfile.findVariable("uEFV");
final Variable varUEFVNUM = ncfile.findVariable("uEFVnum");
final Variable varPVAL = ncfile.findVariable("PVAL");
final Variable varTSTAT = ncfile.findVariable("TSTAT");
/*
* Lazy loading of data, matrix is read only for required elements
*/
if(varUEFV != null && varUEFVNUM != null && varPVAL != null && varTSTAT != null)
experiment.setExpressionStats(arrayDesign, new ExpressionStats() {
private final EfvTree<Integer> efvTree = new EfvTree<Integer>();
private EfvTree<Stat> lastData;
int lastDesignElement = -1;
{
int k = 0;
ArrayChar.StringIterator efvi = ((ArrayChar)varUEFV.read()).getStringIterator();
IndexIterator efvNumi = varUEFVNUM.read().getIndexIteratorFast();
for(ArrayChar.StringIterator efi = efData.getStringIterator(); efi.hasNext() && efvNumi.hasNext(); ) {
String efStr = efi.next();
String ef = efStr.startsWith("ba_") ? efStr.substring("ba_".length()) : efStr;
int efvNum = efvNumi.getIntNext();
for(; efvNum > 0 && efvi.hasNext(); --efvNum) {
String efv = efvi.next();
efvTree.put(ef, efv, k++);
}
}
}
public EfvTree<Stat> getExpressionStats(int designElementId) {
if(lastData != null && designElementId == lastDesignElement)
return lastData;
try {
int[] shapeBDC = varPVAL.getShape();
int[] originBDC = new int[varPVAL.getRank()];
originBDC[0] = designElementId;
shapeBDC[0] = 1;
double[] pvals = (double[])varPVAL.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class);
double[] tstats = (double[])varTSTAT.read(originBDC, shapeBDC).reduce().get1DJavaArray(double.class);
EfvTree<Stat> result = new EfvTree<Stat>();
for(EfvTree.EfEfv<Integer> efefv : efvTree.getNameSortedList()) {
double pvalue = pvals[efefv.getPayload()];
double tstat = tstats[efefv.getPayload()];
if(tstat > 1e-8 || tstat < -1e-8)
result.put(efefv.getEf(), efefv.getEfv(), new Stat(tstat, pvalue));
}
lastDesignElement = designElementId;
lastData = result;
return result;
} catch(IOException e) {
throw new RuntimeException("Exception during pvalue/tstat load", e);
} catch (InvalidRangeException e) {
throw new RuntimeException("Exception during pvalue/tstat load", e);
}
}
});
IndexIterator mappingI = varBS2AS.read().getIndexIteratorFast();
for(int sampleI = 0; sampleI < numSamples; ++sampleI)
for(int assayI = 0; assayI < numAssays; ++assayI)
if(mappingI.hasNext() && mappingI.getIntNext() > 0)
experiment.addSampleAssayMapping(samples[sampleI], assays[assayI]);
final int[] geneIds = (int[])varGN.read().get1DJavaArray(int.class);
experiment.setGeneIds(arrayDesign, geneIds);
}
}
|
package aQute.bnd.build;
import static aQute.bnd.build.Container.toPaths;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import org.osgi.framework.namespace.IdentityNamespace;
import org.osgi.resource.Capability;
import org.osgi.resource.Requirement;
import org.osgi.service.repository.ContentNamespace;
import org.osgi.service.repository.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import aQute.bnd.build.Container.TYPE;
import aQute.bnd.exporter.executable.ExecutableJarExporter;
import aQute.bnd.exporter.runbundles.RunbundlesExporter;
import aQute.bnd.header.Attrs;
import aQute.bnd.header.OSGiHeader;
import aQute.bnd.header.Parameters;
import aQute.bnd.help.Syntax;
import aQute.bnd.http.HttpClient;
import aQute.bnd.maven.support.Pom;
import aQute.bnd.maven.support.ProjectPom;
import aQute.bnd.osgi.About;
import aQute.bnd.osgi.Analyzer;
import aQute.bnd.osgi.Builder;
import aQute.bnd.osgi.Constants;
import aQute.bnd.osgi.Instruction;
import aQute.bnd.osgi.Instructions;
import aQute.bnd.osgi.Jar;
import aQute.bnd.osgi.JarResource;
import aQute.bnd.osgi.Macro;
import aQute.bnd.osgi.Packages;
import aQute.bnd.osgi.Processor;
import aQute.bnd.osgi.Resource;
import aQute.bnd.osgi.Verifier;
import aQute.bnd.osgi.eclipse.EclipseClasspath;
import aQute.bnd.osgi.resource.CapReqBuilder;
import aQute.bnd.osgi.resource.ResourceUtils;
import aQute.bnd.osgi.resource.ResourceUtils.IdentityCapability;
import aQute.bnd.service.CommandPlugin;
import aQute.bnd.service.DependencyContributor;
import aQute.bnd.service.Deploy;
import aQute.bnd.service.RepositoryPlugin;
import aQute.bnd.service.RepositoryPlugin.PutOptions;
import aQute.bnd.service.RepositoryPlugin.PutResult;
import aQute.bnd.service.Scripter;
import aQute.bnd.service.Strategy;
import aQute.bnd.service.action.Action;
import aQute.bnd.service.action.NamedAction;
import aQute.bnd.service.export.Exporter;
import aQute.bnd.service.release.ReleaseBracketingPlugin;
import aQute.bnd.service.specifications.RunSpecification;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.collections.ExtList;
import aQute.lib.collections.Iterables;
import aQute.lib.converter.Converter;
import aQute.lib.exceptions.Exceptions;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.command.Command;
import aQute.libg.generics.Create;
import aQute.libg.glob.Glob;
import aQute.libg.qtokens.QuotedTokenizer;
import aQute.libg.reporter.ReporterMessages;
import aQute.libg.sed.Replacer;
import aQute.libg.sed.Sed;
import aQute.libg.tuple.Pair;
/**
* This class is NOT threadsafe
*/
public class Project extends Processor {
private final static Logger logger = LoggerFactory.getLogger(Project.class);
static class RefreshData {
Parameters installRepositories;
}
final static String DEFAULT_ACTIONS = "build; label='Build', test; label='Test', run; label='Run', clean; label='Clean', release; label='Release', refreshAll; label=Refresh, deploy;label=Deploy";
public final static String BNDFILE = "bnd.bnd";
final static Path BNDPATH = Paths.get(BNDFILE);
public final static String BNDCNF = "cnf";
public final static String SHA_256 = "SHA-256";
final Workspace workspace;
private final AtomicBoolean preparedPaths = new AtomicBoolean();
private final Set<Project> dependenciesFull = new LinkedHashSet<>();
private final Set<Project> dependenciesBuild = new LinkedHashSet<>();
private final Set<Project> dependenciesTest = new LinkedHashSet<>();
private final Set<Project> dependents = new LinkedHashSet<>();
final Collection<Container> classpath = new LinkedHashSet<>();
final Collection<Container> buildpath = new LinkedHashSet<>();
final Collection<Container> testpath = new LinkedHashSet<>();
final Collection<Container> runpath = new LinkedHashSet<>();
final Collection<Container> runbundles = new LinkedHashSet<>();
final Collection<Container> runfw = new LinkedHashSet<>();
File runstorage;
final Map<File, Attrs> sourcepath = new LinkedHashMap<>();
final Collection<File> allsourcepath = new LinkedHashSet<>();
final Collection<Container> bootclasspath = new LinkedHashSet<>();
final Map<String, Version> versionMap = new LinkedHashMap<>();
File output;
File target;
private final AtomicInteger revision = new AtomicInteger();
private File files[];
boolean delayRunDependencies = true;
final ProjectMessages msgs = ReporterMessages.base(this,
ProjectMessages.class);
private Properties ide;
final Packages exportedPackages = new Packages();
final Packages importedPackages = new Packages();
final Packages containedPackages = new Packages();
final PackageInfo packageInfo = new PackageInfo(this);
private Makefile makefile;
private volatile RefreshData data = new RefreshData();
public Map<String, Container> unreferencedClasspathEntries = new HashMap<>();
public Project(Workspace workspace, File unused, File buildFile) {
super(workspace);
this.workspace = workspace;
setFileMustExist(false);
if (buildFile != null)
setProperties(buildFile);
// For backward compatibility reasons, we also read
readBuildProperties();
}
public Project(Workspace workspace, File buildDir) {
this(workspace, buildDir, new File(buildDir, BNDFILE));
}
private void readBuildProperties() {
try {
File f = getFile("build.properties");
if (f.isFile()) {
Properties p = loadProperties(f);
for (String key : Iterables.iterable(p.propertyNames(), String.class::cast)) {
String newkey = key;
if (key.indexOf('$') >= 0) {
newkey = getReplacer().process(key);
}
setProperty(newkey, p.getProperty(key));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Project getUnparented(File propertiesFile) throws Exception {
propertiesFile = propertiesFile.getAbsoluteFile();
Workspace workspace = new Workspace(propertiesFile.getParentFile());
Project project = new Project(workspace, propertiesFile.getParentFile());
project.setProperties(propertiesFile);
project.setFileMustExist(true);
return project;
}
public boolean isValid() {
if (getBase() == null || !getBase().isDirectory())
return false;
return getPropertiesFile() == null || getPropertiesFile().isFile();
}
/**
* Return a new builder that is nicely setup for this project. Please close
* this builder after use.
*
* @param parent The project builder to use as parent, use this project if
* null
* @throws Exception
*/
public ProjectBuilder getBuilder(ProjectBuilder parent) throws Exception {
ProjectBuilder builder;
if (parent == null)
builder = new ProjectBuilder(this);
else
builder = new ProjectBuilder(parent);
builder.setBase(getBase());
builder.use(this);
return builder;
}
public int getChanged() {
return revision.get();
}
/*
* Indicate a change in the external world that affects our build. This will
* clear any cached results.
*/
public void setChanged() {
// if (refresh()) {
preparedPaths.set(false);
files = null;
revision.getAndIncrement();
}
public Workspace getWorkspace() {
return workspace;
}
@Override
public String toString() {
return getName();
}
/**
* Set up all the paths
*/
public void prepare() throws Exception {
if (!isValid()) {
warning("Invalid project attempts to prepare: %s", this);
return;
}
synchronized (preparedPaths) {
if (preparedPaths.get()) {
// ensure output folders exist
getSrcOutput0();
getTarget0();
return;
}
if (!workspace.trail.add(this)) {
throw new CircularDependencyException(workspace.trail.toString() + "," + this);
}
try {
String basePath = IO.absolutePath(getBase());
dependenciesFull.clear();
dependenciesBuild.clear();
dependenciesTest.clear();
dependents.clear();
buildpath.clear();
testpath.clear();
sourcepath.clear();
allsourcepath.clear();
bootclasspath.clear();
// JIT
runpath.clear();
runbundles.clear();
runfw.clear();
// We use a builder to construct all the properties for
// use.
setProperty("basedir", basePath);
// If a bnd.bnd file exists, we read it.
// Otherwise, we just do the build properties.
if (!getPropertiesFile().isFile() && new File(getBase(), ".classpath").isFile()) {
// Get our Eclipse info, we might depend on other
// projects
// though ideally this should become empty and void
doEclipseClasspath();
}
// Calculate our source directories
Parameters srces = new Parameters(mergeProperties(Constants.DEFAULT_PROP_SRC_DIR), this);
if (srces.isEmpty())
srces.add(Constants.DEFAULT_PROP_SRC_DIR, new Attrs());
for (Entry<String, Attrs> e : srces.entrySet()) {
File dir = getFile(removeDuplicateMarker(e.getKey()));
if (!IO.absolutePath(dir)
.startsWith(basePath)) {
error("The source directory lies outside the project %s directory: %s", this, dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
try {
IO.mkdirs(dir);
} catch (Exception ex) {
exception(ex, "could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
if (!dir.exists()) {
error("could not create src directory (in src property) %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
continue;
}
}
if (dir.isDirectory()) {
sourcepath.put(dir, new Attrs(e.getValue()));
allsourcepath.add(dir);
} else
error("the src path (src property) contains an entry that is not a directory %s", dir)
.header(Constants.DEFAULT_PROP_SRC_DIR)
.context(e.getKey());
}
// Set default bin directory
output = getSrcOutput0();
if (!output.isDirectory()) {
msgs.NoOutputDirectory_(output);
}
// Where we store all our generated stuff.
target = getTarget0();
// Where the launched OSGi framework stores stuff
String runStorageStr = getProperty(Constants.RUNSTORAGE);
runstorage = runStorageStr != null ? getFile(runStorageStr) : null;
// We might have some other projects we want build
// before we do anything, but these projects are not in
// our path. The -dependson allows you to build them before.
// The values are possibly negated globbing patterns.
Set<String> requiredProjectNames = new LinkedHashSet<>(
getMergedParameters(Constants.DEPENDSON).keySet());
// Allow DependencyConstributors to modify requiredProjectNames
List<DependencyContributor> dcs = getPlugins(DependencyContributor.class);
for (DependencyContributor dc : dcs)
dc.addDependencies(this, requiredProjectNames);
Instructions is = new Instructions(requiredProjectNames);
Collection<Project> projects = getWorkspace().getAllProjects();
projects.remove(this); // since -dependson could use a wildcard
Set<Instruction> unused = new HashSet<>();
Set<Project> buildDeps = new LinkedHashSet<>(is.select(projects, unused, false));
for (Instruction u : unused)
msgs.MissingDependson_(u.getInput());
// We have two paths that consists of repo files, projects,
// or some other stuff. The doPath routine adds them to the
// path and extracts the projects so we can build them
// before.
doPath(buildpath, buildDeps, parseBuildpath(), bootclasspath, false, BUILDPATH);
Set<Project> testDeps = new LinkedHashSet<>(buildDeps);
doPath(testpath, testDeps, parseTestpath(), bootclasspath, false, TESTPATH);
if (!delayRunDependencies) {
doPath(runfw, testDeps, parseRunFw(), null, false, RUNFW);
doPath(runpath, testDeps, parseRunpath(), null, false, RUNPATH);
doPath(runbundles, testDeps, parseRunbundles(), null, true, RUNBUNDLES);
}
// We now know all dependent projects. But we also depend
// on whatever those projects depend on. This creates an
// ordered list without any duplicates. This of course assumes
// that there is no circularity. However, this is checked
// by the inPrepare flag, will throw an exception if we
// are circular.
Set<Project> visited = new HashSet<>();
visited.add(this);
for (Project project : testDeps) {
project.traverse(dependenciesFull, this, visited);
}
dependenciesBuild.addAll(dependenciesFull);
dependenciesBuild.retainAll(buildDeps);
dependenciesTest.addAll(dependenciesFull);
dependenciesTest.retainAll(testDeps);
for (Project project : dependenciesFull) {
allsourcepath.addAll(project.getSourcePath());
}
preparedPaths.set(true);
} finally {
workspace.trail.remove(this);
}
}
}
private File getSrcOutput0() throws IOException {
File output = getSrcOutput().getAbsoluteFile();
if (!output.exists()) {
IO.mkdirs(output);
getWorkspace().changedFile(output);
}
return output;
}
private File getTarget0() throws IOException {
File target = getTargetDir();
if (!target.exists()) {
IO.mkdirs(target);
getWorkspace().changedFile(target);
}
return target;
}
/**
* This method is deprecated because this can handle only one source dir.
* Use getSourcePath. For backward compatibility we will return the first
* entry on the source path.
*
* @return first entry on the {@link #getSourcePath()}
*/
@Deprecated
public File getSrc() throws Exception {
prepare();
if (sourcepath.isEmpty())
return getFile("src");
return sourcepath.keySet()
.iterator()
.next();
}
public File getSrcOutput() {
return getFile(getProperty(Constants.DEFAULT_PROP_BIN_DIR));
}
public File getTestSrc() {
return getFile(getProperty(Constants.DEFAULT_PROP_TESTSRC_DIR));
}
public File getTestOutput() {
return getFile(getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR));
}
public File getTargetDir() {
return getFile(getProperty(Constants.DEFAULT_PROP_TARGET_DIR));
}
private void traverse(Set<Project> dependencies, Project dependent, Set<Project> visited) throws Exception {
if (visited.add(this)) {
for (Project project : getTestDependencies()) {
project.traverse(dependencies, this, visited);
}
dependencies.add(this);
}
dependents.add(dependent);
}
/**
* Iterate over the entries and place the projects on the projects list and
* all the files of the entries on the resultpath.
*
* @param resultpath The list that gets all the files
* @param projects The list that gets any projects that are entries
* @param entries The input list of classpath entries
*/
private void doPath(Collection<Container> resultpath, Collection<Project> projects, Collection<Container> entries,
Collection<Container> bootclasspath, boolean noproject, String name) {
for (Container cpe : entries) {
if (cpe.getError() != null)
error("%s", cpe.getError()).header(name)
.context(cpe.getBundleSymbolicName());
else {
if (cpe.getType() == Container.TYPE.PROJECT) {
projects.add(cpe.getProject());
if (noproject
&& since(About._2_3)
&& VERSION_ATTR_PROJECT.equals(cpe.getAttributes()
.get(VERSION_ATTRIBUTE))) {
// we're trying to put a project's output directory on
// -runbundles list
error(
"%s is specified with version=project on %s. This version uses the project's output directory, which is not allowed since it must be an actual JAR file for this list.",
cpe.getBundleSymbolicName(), name).header(name)
.context(cpe.getBundleSymbolicName());
}
}
if (bootclasspath != null && (cpe.getBundleSymbolicName()
.startsWith("ee.")
|| cpe.getAttributes()
.containsKey("boot")))
bootclasspath.add(cpe);
else
resultpath.add(cpe);
}
}
}
/**
* Parse the list of bundles that are a prerequisite to this project.
* Bundles are listed in repo specific names. So we just let our repo
* plugins iterate over the list of bundles and we get the highest version
* from them.
*/
private List<Container> parseBuildpath() throws Exception {
List<Container> bundles = getBundles(Strategy.LOWEST, mergeProperties(Constants.BUILDPATH),
Constants.BUILDPATH);
return bundles;
}
private List<Container> parseRunpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNPATH), Constants.RUNPATH);
}
private List<Container> parseRunbundles() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.RUNBUNDLES), Constants.RUNBUNDLES);
}
private List<Container> parseRunFw() throws Exception {
return getBundles(Strategy.HIGHEST, getProperty(Constants.RUNFW), Constants.RUNFW);
}
private List<Container> parseTestpath() throws Exception {
return getBundles(Strategy.HIGHEST, mergeProperties(Constants.TESTPATH), Constants.TESTPATH);
}
/**
* Analyze the header and return a list of files that should be on the
* build, test or some other path. The list is assumed to be a list of bsns
* with a version specification. The special case of version=project
* indicates there is a project in the same workspace. The path to the
* output directory is calculated. The default directory ${bin} can be
* overridden with the output attribute.
*
* @param strategyx STRATEGY_LOWEST or STRATEGY_HIGHEST
* @param spec The header
*/
public List<Container> getBundles(Strategy strategyx, String spec, String source) throws Exception {
List<Container> result = new ArrayList<>();
Parameters bundles = new Parameters(spec, this);
try {
for (Iterator<Entry<String, Attrs>> i = bundles.entrySet()
.iterator(); i.hasNext();) {
Entry<String, Attrs> entry = i.next();
String bsn = removeDuplicateMarker(entry.getKey());
Map<String, String> attrs = entry.getValue();
Container found = null;
String versionRange = attrs.get("version");
boolean triedGetBundle = false;
if (bsn.indexOf('*') >= 0) {
return getBundlesWildcard(bsn, versionRange, strategyx, attrs);
}
if (versionRange != null) {
if (versionRange.equals(VERSION_ATTR_LATEST) || versionRange.equals(VERSION_ATTR_SNAPSHOT)) {
found = getBundle(bsn, versionRange, strategyx, attrs);
triedGetBundle = true;
}
}
if (found == null) {
// TODO This looks like a duplicate
// of what is done in getBundle??
if (versionRange != null
&& (versionRange.equals(VERSION_ATTR_PROJECT) || versionRange.equals(VERSION_ATTR_LATEST))) {
// Use the bin directory ...
Project project = getWorkspace().getProject(bsn);
if (project != null && project.exists()) {
File f = project.getOutput();
found = new Container(project, bsn, versionRange, Container.TYPE.PROJECT, f, null, attrs,
null);
} else {
msgs.NoSuchProject(bsn, spec)
.context(bsn)
.header(source);
continue;
}
} else if (versionRange != null && versionRange.equals("file")) {
File f = getFile(bsn);
String error = null;
if (!f.exists())
error = "File does not exist: " + IO.absolutePath(f);
if (f.getName()
.endsWith(".lib")) {
found = new Container(this, bsn, "file", Container.TYPE.LIBRARY, f, error, attrs, null);
} else {
found = new Container(this, bsn, "file", Container.TYPE.EXTERNAL, f, error, attrs, null);
}
} else if (!triedGetBundle) {
found = getBundle(bsn, versionRange, strategyx, attrs);
}
}
if (found != null) {
List<Container> libs = found.getMembers();
for (Container cc : libs) {
if (result.contains(cc)) {
if (isPedantic())
warning("Multiple bundles with the same final URL: %s, dropped duplicate", cc);
} else {
if (cc.getError() != null) {
error("Cannot find %s", cc).context(bsn)
.header(source);
}
result.add(cc);
}
}
} else {
// Oops, not a bundle in sight :-(
Container x = new Container(this, bsn, versionRange, Container.TYPE.ERROR, null,
bsn + ";version=" + versionRange + " not found", attrs, null);
result.add(x);
error("Can not find URL for bsn %s", bsn).context(bsn)
.header(source);
}
}
} catch (CircularDependencyException e) {
String message = e.getMessage();
if (source != null)
message = String.format("%s (from property: %s)", message, source);
msgs.CircularDependencyContext_Message_(getName(), message);
} catch (IOException e) {
exception(e, "Unexpected exception in get bundles", spec);
}
return result;
}
/**
* Just calls a new method with a default parm.
*
* @throws Exception
*/
Collection<Container> getBundles(Strategy strategy, String spec) throws Exception {
return getBundles(strategy, spec, null);
}
/**
* Get all bundles matching a wildcard expression.
*
* @param bsnPattern A bsn wildcard, e.g. "osgi*" or just "*".
* @param range A range to narrow the versions of bundles found, or null to
* return any version.
* @param strategyx The version selection strategy, which may be 'HIGHEST'
* or 'LOWEST' only -- 'EXACT' is not permitted.
* @param attrs Additional search attributes.
* @throws Exception
*/
public List<Container> getBundlesWildcard(String bsnPattern, String range, Strategy strategyx,
Map<String, String> attrs) throws Exception {
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range))
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use snapshot or project version with wildcard matches", null, null));
if (strategyx == Strategy.EXACT)
return Collections.singletonList(new Container(this, bsnPattern, range, TYPE.ERROR, null,
"Cannot use exact version strategy with wildcard matches", null, null));
VersionRange versionRange;
if (range == null || VERSION_ATTR_LATEST.equals(range))
versionRange = new VersionRange("0");
else
versionRange = new VersionRange(range);
RepoFilter repoFilter = parseRepoFilter(attrs);
if (bsnPattern != null) {
bsnPattern = bsnPattern.trim();
if (bsnPattern.length() == 0 || bsnPattern.equals("*"))
bsnPattern = null;
}
SortedMap<String, Pair<Version, RepositoryPlugin>> providerMap = new TreeMap<>();
List<RepositoryPlugin> plugins = workspace.getRepositories();
for (RepositoryPlugin plugin : plugins) {
if (repoFilter != null && !repoFilter.match(plugin))
continue;
List<String> bsns = plugin.list(bsnPattern);
if (bsns != null)
for (String bsn : bsns) {
SortedSet<Version> versions = plugin.versions(bsn);
if (versions != null && !versions.isEmpty()) {
Pair<Version, RepositoryPlugin> currentProvider = providerMap.get(bsn);
Version candidate;
switch (strategyx) {
case HIGHEST :
candidate = versions.last();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) > 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
case LOWEST :
candidate = versions.first();
if (currentProvider == null || candidate.compareTo(currentProvider.getFirst()) < 0) {
providerMap.put(bsn, new Pair<>(candidate, plugin));
}
break;
default :
// we shouldn't have reached this point!
throw new IllegalStateException(
"Cannot use exact version strategy with wildcard matches");
}
}
}
}
List<Container> containers = new ArrayList<>(providerMap.size());
for (Entry<String, Pair<Version, RepositoryPlugin>> entry : providerMap.entrySet()) {
String bsn = entry.getKey();
Version version = entry.getValue()
.getFirst();
RepositoryPlugin repo = entry.getValue()
.getSecond();
DownloadBlocker downloadBlocker = new DownloadBlocker(this);
File bundle = repo.get(bsn, version, attrs, downloadBlocker);
if (bundle != null && !bundle.getName()
.endsWith(".lib")) {
containers
.add(new Container(this, bsn, range, Container.TYPE.REPO, bundle, null, attrs, downloadBlocker));
}
}
return containers;
}
static void mergeNames(String names, Set<String> set) {
StringTokenizer tokenizer = new StringTokenizer(names, ",");
while (tokenizer.hasMoreTokens())
set.add(tokenizer.nextToken()
.trim());
}
static String flatten(Set<String> names) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String name : names) {
if (!first)
builder.append(',');
builder.append(name);
first = false;
}
return builder.toString();
}
static void addToPackageList(Container container, String newPackageNames) {
Set<String> merged = new HashSet<>();
String packageListStr = container.getAttributes()
.get("packages");
if (packageListStr != null)
mergeNames(packageListStr, merged);
if (newPackageNames != null)
mergeNames(newPackageNames, merged);
container.putAttribute("packages", flatten(merged));
}
/**
* The user selected pom in a path. This will place the pom as well as its
* dependencies on the list
*
* @param strategyx the strategy to use.
* @param result The list of result containers
* @throws Exception anything goes wrong
*/
public void doMavenPom(Strategy strategyx, List<Container> result, String action) throws Exception {
File pomFile = getFile("pom.xml");
if (!pomFile.isFile())
msgs.MissingPom();
else {
ProjectPom pom = getWorkspace().getMaven()
.createProjectModel(pomFile);
if (action == null)
action = "compile";
Pom.Scope act = Pom.Scope.valueOf(action);
Set<Pom> dependencies = pom.getDependencies(act);
for (Pom sub : dependencies) {
File artifact = sub.getArtifact();
Container container = new Container(artifact, null);
result.add(container);
}
}
}
/**
* Return the full transitive dependencies of this project.
*
* @return A set of the full transitive dependencies of this project.
* @throws Exception
*/
public Collection<Project> getDependson() throws Exception {
prepare();
return dependenciesFull;
}
/**
* Return the direct build dependencies of this project.
*
* @return A set of the direct build dependencies of this project.
* @throws Exception
*/
public Set<Project> getBuildDependencies() throws Exception {
prepare();
return dependenciesBuild;
}
/**
* Return the direct test dependencies of this project.
* <p>
* The result includes the direct build dependencies of this project as
* well, so the result is a super set of {@link #getBuildDependencies()}.
*
* @return A set of the test build dependencies of this project.
* @throws Exception
*/
public Set<Project> getTestDependencies() throws Exception {
prepare();
return dependenciesTest;
}
/**
* Return the full transitive dependents of this project.
* <p>
* The result includes projects which have build and test dependencies on
* this project.
* <p>
* Since the full transitive dependents of this project is updated during
* the computation of other project dependencies, until all projects are
* prepared, the dependents result may be partial.
*
* @return A set of the transitive set of projects which depend on this
* project.
* @throws Exception
*/
public Set<Project> getDependents() throws Exception {
prepare();
return dependents;
}
public Collection<Container> getBuildpath() throws Exception {
prepare();
return buildpath;
}
public Collection<Container> getTestpath() throws Exception {
prepare();
return testpath;
}
/**
* Handle dependencies for paths that are calculated on demand.
*
* @param testpath2
* @param parseTestpath
*/
private void justInTime(Collection<Container> path, List<Container> entries, boolean noproject, String name) {
if (delayRunDependencies && path.isEmpty())
doPath(path, dependenciesFull, entries, null, noproject, name);
}
public Collection<Container> getRunpath() throws Exception {
prepare();
justInTime(runpath, parseRunpath(), false, RUNPATH);
return runpath;
}
public Collection<Container> getRunbundles() throws Exception {
prepare();
justInTime(runbundles, parseRunbundles(), true, RUNBUNDLES);
return runbundles;
}
/**
* Return the run framework
*
* @throws Exception
*/
public Collection<Container> getRunFw() throws Exception {
prepare();
justInTime(runfw, parseRunFw(), false, RUNFW);
return runfw;
}
public File getRunStorage() throws Exception {
prepare();
return runstorage;
}
public boolean getRunBuilds() {
boolean result;
String runBuildsStr = getProperty(Constants.RUNBUILDS);
if (runBuildsStr == null)
result = !getPropertiesFile().getName()
.toLowerCase()
.endsWith(Constants.DEFAULT_BNDRUN_EXTENSION);
else
result = Boolean.parseBoolean(runBuildsStr);
return result;
}
public Collection<File> getSourcePath() throws Exception {
prepare();
return sourcepath.keySet();
}
public Collection<File> getAllsourcepath() throws Exception {
prepare();
return allsourcepath;
}
public Collection<Container> getBootclasspath() throws Exception {
prepare();
return bootclasspath;
}
public File getOutput() throws Exception {
prepare();
return output;
}
private void doEclipseClasspath() throws Exception {
EclipseClasspath eclipse = new EclipseClasspath(this, getWorkspace().getBase(), getBase());
eclipse.setRecurse(false);
// We get the file directories but in this case we need
// to tell ant that the project names
for (File dependent : eclipse.getDependents()) {
Project required = workspace.getProject(dependent.getName());
dependenciesFull.add(required);
}
for (File f : eclipse.getClasspath()) {
buildpath.add(new Container(f, null));
}
for (File f : eclipse.getBootclasspath()) {
bootclasspath.add(new Container(f, null));
}
for (File f : eclipse.getSourcepath()) {
sourcepath.put(f, new Attrs());
}
allsourcepath.addAll(eclipse.getAllSources());
output = eclipse.getOutput();
}
public String _p_dependson(String args[]) throws Exception {
return list(args, toFiles(getDependson()));
}
private Collection<?> toFiles(Collection<Project> projects) {
List<File> files = new ArrayList<>();
for (Project p : projects) {
files.add(p.getBase());
}
return files;
}
public String _p_buildpath(String args[]) throws Exception {
return list(args, getBuildpath());
}
public String _p_testpath(String args[]) throws Exception {
return list(args, getRunpath());
}
public String _p_sourcepath(String args[]) throws Exception {
return list(args, getSourcePath());
}
public String _p_allsourcepath(String args[]) throws Exception {
return list(args, getAllsourcepath());
}
public String _p_bootclasspath(String args[]) throws Exception {
return list(args, getBootclasspath());
}
public String _p_output(String args[]) throws Exception {
if (args.length != 1)
throw new IllegalArgumentException("${output} should not have arguments");
return IO.absolutePath(getOutput());
}
private String list(String[] args, Collection<?> list) {
if (args.length > 3)
throw new IllegalArgumentException(
"${" + args[0] + "[;<separator>]} can only take a separator as argument, has " + Arrays.toString(args));
String separator = ",";
if (args.length == 2) {
separator = args[1];
}
return join(list, separator);
}
@Override
protected Object[] getMacroDomains() {
return new Object[] {
workspace
};
}
public File release(String jarName, InputStream jarStream) throws Exception {
return release(null, jarName, jarStream);
}
public URI releaseURI(String jarName, InputStream jarStream) throws Exception {
return releaseURI(null, jarName, jarStream);
}
/**
* Release
*
* @param name The repository name
* @param jarName
* @param jarStream
* @throws Exception
*/
public File release(String name, String jarName, InputStream jarStream) throws Exception {
URI uri = releaseURI(name, jarName, jarStream);
if (uri != null && uri.getScheme()
.equals("file")) {
return new File(uri);
}
return null;
}
public URI releaseURI(String name, String jarName, InputStream jarStream) throws Exception {
List<RepositoryPlugin> releaseRepos = getReleaseRepos(name);
if (releaseRepos.isEmpty()) {
return null;
}
try (ProjectBuilder builder = getBuilder(null)) {
builder.init();
RepositoryPlugin releaseRepo = releaseRepos.get(0); // use only
// first
// release repo
return releaseRepo(releaseRepo, builder, jarName, jarStream);
}
}
private URI releaseRepo(RepositoryPlugin releaseRepo, Processor context, String jarName, InputStream jarStream)
throws Exception {
logger.debug("release to {}", releaseRepo.getName());
try {
PutOptions putOptions = new RepositoryPlugin.PutOptions();
// TODO find sub bnd that is associated with this thing
putOptions.context = context;
PutResult r = releaseRepo.put(jarStream, putOptions);
logger.debug("Released {} to {} in repository {}", jarName, r.artifact, releaseRepo);
return r.artifact;
} catch (Exception e) {
msgs.Release_Into_Exception_(jarName, releaseRepo, e);
return null;
}
}
private List<RepositoryPlugin> getReleaseRepos(String names) {
Parameters repoNames = parseReleaseRepos(names);
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
List<RepositoryPlugin> result = new ArrayList<>();
if (repoNames == null) { // -releaserepo unspecified
for (RepositoryPlugin plugin : plugins) {
if (plugin.canWrite()) {
result.add(plugin);
break;
}
}
if (result.isEmpty()) {
msgs.NoNameForReleaseRepository();
}
return result;
}
repoNames: for (String repoName : repoNames.keySet()) {
for (RepositoryPlugin plugin : plugins) {
if (plugin.canWrite() && repoName.equals(plugin.getName())) {
result.add(plugin);
continue repoNames;
}
}
msgs.ReleaseRepository_NotFoundIn_(repoName, plugins);
}
return result;
}
private Parameters parseReleaseRepos(String names) {
if (names == null) {
names = mergeProperties(RELEASEREPO);
if (names == null) {
return null; // -releaserepo unspecified
}
}
return new Parameters(names, this);
}
public void release(boolean test) throws Exception {
release(null, test);
}
/**
* Release
*
* @param name The respository name
* @param test Run testcases
* @throws Exception
*/
public void release(String name, boolean test) throws Exception {
List<RepositoryPlugin> releaseRepos = getReleaseRepos(name);
if (releaseRepos.isEmpty()) {
return;
}
logger.debug("release");
File[] jars = getBuildFiles(false);
if (jars == null) {
jars = build(test);
// If build fails jars will be null
if (jars == null) {
logger.debug("no jars built");
return;
}
}
logger.debug("releasing {} - {}", jars, releaseRepos);
try (ProjectBuilder builder = getBuilder(null)) {
builder.init();
for (RepositoryPlugin releaseRepo : releaseRepos) {
for (File jar : jars) {
releaseRepo(releaseRepo, builder, jar.getName(), new BufferedInputStream(IO.stream(jar)));
}
}
}
}
/**
* Get a bundle from one of the plugin repositories. If an exact version is
* required we just return the first repository found (in declaration order
* in the build.bnd file).
*
* @param bsn The bundle symbolic name
* @param range The version range
* @param strategy set to LOWEST or HIGHEST
* @return the file object that points to the bundle or null if not found
* @throws Exception when something goes wrong
*/
public Container getBundle(String bsn, String range, Strategy strategy, Map<String, String> attrs)
throws Exception {
if (range == null)
range = "0";
if (VERSION_ATTR_SNAPSHOT.equals(range) || VERSION_ATTR_PROJECT.equals(range)) {
return getBundleFromProject(bsn, attrs);
} else if (VERSION_ATTR_HASH.equals(range)) {
return getBundleByHash(bsn, attrs);
}
Strategy useStrategy = strategy;
if (VERSION_ATTR_LATEST.equals(range)) {
Container c = getBundleFromProject(bsn, attrs);
if (c != null)
return c;
useStrategy = Strategy.HIGHEST;
}
useStrategy = overrideStrategy(attrs, useStrategy);
RepoFilter repoFilter = parseRepoFilter(attrs);
List<RepositoryPlugin> plugins = workspace.getRepositories();
if (useStrategy == Strategy.EXACT) {
if (!Verifier.isVersion(range))
return new Container(this, bsn, range, Container.TYPE.ERROR, null,
bsn + ";version=" + range + " Invalid version", null, null);
// For an exact range we just iterate over the repos
// and return the first we find.
Version version = new Version(range);
for (RepositoryPlugin plugin : plugins) {
DownloadBlocker blocker = new DownloadBlocker(this);
File result = plugin.get(bsn, version, attrs, blocker);
if (result != null)
return toContainer(bsn, range, attrs, result, blocker);
}
} else {
VersionRange versionRange = VERSION_ATTR_LATEST.equals(range) ? new VersionRange("0")
: new VersionRange(range);
// We have a range search. Gather all the versions in all the repos
// and make a decision on that choice. If the same version is found
// multiple repos we take the first
SortedMap<Version, RepositoryPlugin> versions = new TreeMap<>();
for (RepositoryPlugin plugin : plugins) {
if (repoFilter != null && !repoFilter.match(plugin))
continue;
try {
SortedSet<Version> vs = plugin.versions(bsn);
if (vs != null) {
for (Version v : vs) {
if (!versions.containsKey(v) && versionRange.includes(v))
versions.put(v, plugin);
}
}
} catch (UnsupportedOperationException ose) {
// We have a plugin that cannot list versions, try
// if it has this specific version
// The main reaosn for this code was the Maven Remote
// Repository
// To query, we must have a real version
if (!versions.isEmpty() && Verifier.isVersion(range)) {
Version version = new Version(range);
DownloadBlocker blocker = new DownloadBlocker(this);
File file = plugin.get(bsn, version, attrs, blocker);
// and the entry must exist
// if it does, return this as a result
if (file != null)
return toContainer(bsn, range, attrs, file, blocker);
}
}
}
// We have to augment the list of returned versions
// with info from the workspace. We use null as a marker
// to indicate that it is a workspace project
SortedSet<Version> localVersions = getWorkspace().getWorkspaceRepository()
.versions(bsn);
for (Version v : localVersions) {
if (!versions.containsKey(v) && versionRange.includes(v))
versions.put(v, null);
}
// Verify if we found any, if so, we use the strategy to pick
// the first or last
if (!versions.isEmpty()) {
Version provider = null;
switch (useStrategy) {
case HIGHEST :
provider = versions.lastKey();
break;
case LOWEST :
provider = versions.firstKey();
break;
case EXACT :
// TODO need to handle exact better
break;
}
if (provider != null) {
RepositoryPlugin repo = versions.get(provider);
if (repo == null) {
// A null provider indicates that we have a local
// project
return getBundleFromProject(bsn, attrs);
}
String version = provider.toString();
DownloadBlocker blocker = new DownloadBlocker(this);
File result = repo.get(bsn, provider, attrs, blocker);
if (result != null)
return toContainer(bsn, version, attrs, result, blocker);
} else {
msgs.FoundVersions_ForStrategy_ButNoProvider(versions, useStrategy);
}
}
}
// If we get this far we ran into an error somewhere
return new Container(this, bsn, range, Container.TYPE.ERROR, null,
bsn + ";version=" + range + " Not found in " + plugins, null, null);
}
/**
* @param attrs
* @param useStrategy
*/
protected Strategy overrideStrategy(Map<String, String> attrs, Strategy useStrategy) {
if (attrs != null) {
String overrideStrategy = attrs.get("strategy");
if (overrideStrategy != null) {
if ("highest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.HIGHEST;
else if ("lowest".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.LOWEST;
else if ("exact".equalsIgnoreCase(overrideStrategy))
useStrategy = Strategy.EXACT;
}
}
return useStrategy;
}
private static class RepoFilter {
private Pattern[] patterns;
RepoFilter(Pattern[] patterns) {
this.patterns = patterns;
}
boolean match(RepositoryPlugin repo) {
if (patterns == null)
return true;
for (Pattern pattern : patterns) {
if (pattern.matcher(repo.getName())
.matches())
return true;
}
return false;
}
}
protected RepoFilter parseRepoFilter(Map<String, String> attrs) {
if (attrs == null)
return null;
String patternStr = attrs.get("repo");
if (patternStr == null)
return null;
List<Pattern> patterns = new LinkedList<>();
QuotedTokenizer tokenize = new QuotedTokenizer(patternStr, ",");
String token = tokenize.nextToken();
while (token != null) {
patterns.add(Glob.toPattern(token));
token = tokenize.nextToken();
}
return new RepoFilter(patterns.toArray(new Pattern[0]));
}
/**
* @param bsn
* @param range
* @param attrs
* @param result
*/
protected Container toContainer(String bsn, String range, Map<String, String> attrs, File result,
DownloadBlocker db) {
File f = result;
if (f == null) {
msgs.ConfusedNoContainerFile();
f = new File("was null");
}
Container container;
if (f.getName()
.endsWith("lib"))
container = new Container(this, bsn, range, Container.TYPE.LIBRARY, f, null, attrs, db);
else
container = new Container(this, bsn, range, Container.TYPE.REPO, f, null, attrs, db);
return container;
}
/**
* Look for the bundle in the workspace. The premise is that the bsn must
* start with the project name.
*
* @param bsn The bsn
* @param attrs Any attributes
* @throws Exception
*/
private Container getBundleFromProject(String bsn, Map<String, String> attrs) throws Exception {
String pname = bsn;
while (true) {
Project p = getWorkspace().getProject(pname);
if (p != null && p.isValid()) {
Container c = p.getDeliverable(bsn, attrs);
return c;
}
int n = pname.lastIndexOf('.');
if (n <= 0)
return null;
pname = pname.substring(0, n);
}
}
private Container getBundleByHash(String bsn, Map<String, String> attrs) throws Exception {
String hashStr = attrs.get("hash");
String algo = SHA_256;
String hash = hashStr;
int colonIndex = hashStr.indexOf(':');
if (colonIndex > -1) {
algo = hashStr.substring(0, colonIndex);
int afterColon = colonIndex + 1;
hash = (colonIndex < hashStr.length()) ? hashStr.substring(afterColon) : "";
}
for (RepositoryPlugin plugin : workspace.getRepositories()) {
// The plugin *may* understand version=hash directly
DownloadBlocker blocker = new DownloadBlocker(this);
File result = plugin.get(bsn, Version.LOWEST, Collections.unmodifiableMap(attrs), blocker);
// If not, and if the repository implements the OSGi Repository
// Service, use a capability search on the osgi.content namespace.
if (result == null && plugin instanceof Repository) {
Repository repo = (Repository) plugin;
if (!SHA_256.equals(algo))
// R5 repos only support SHA-256
continue;
Requirement contentReq = new CapReqBuilder(ContentNamespace.CONTENT_NAMESPACE)
.filter(String.format("(%s=%s)", ContentNamespace.CONTENT_NAMESPACE, hash))
.buildSyntheticRequirement();
Set<Requirement> reqs = Collections.singleton(contentReq);
Map<Requirement, Collection<Capability>> providers = repo.findProviders(reqs);
Collection<Capability> caps = providers != null ? providers.get(contentReq) : null;
if (caps != null && !caps.isEmpty()) {
Capability cap = caps.iterator()
.next();
IdentityCapability idCap = ResourceUtils.getIdentityCapability(cap.getResource());
Map<String, Object> idAttrs = idCap.getAttributes();
String id = (String) idAttrs.get(IdentityNamespace.IDENTITY_NAMESPACE);
Object version = idAttrs.get(IdentityNamespace.CAPABILITY_VERSION_ATTRIBUTE);
Version bndVersion = version != null ? Version.parseVersion(version.toString()) : Version.LOWEST;
if (!bsn.equals(id)) {
String error = String.format("Resource with requested hash does not match ID '%s' [hash: %s]",
bsn, hashStr);
return new Container(this, bsn, "hash", Container.TYPE.ERROR, null, error, null, null);
}
result = plugin.get(id, bndVersion, null, blocker);
}
}
if (result != null)
return toContainer(bsn, "hash", attrs, result, blocker);
}
// If we reach this far, none of the repos found the resource.
return new Container(this, bsn, "hash", Container.TYPE.ERROR, null,
"Could not find resource by content hash " + hashStr, null, null);
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param name The repository name
* @param file bundle
*/
public void deploy(String name, File file) throws Exception {
List<RepositoryPlugin> plugins = getPlugins(RepositoryPlugin.class);
RepositoryPlugin rp = null;
for (RepositoryPlugin plugin : plugins) {
if (!plugin.canWrite()) {
continue;
}
if (name == null) {
rp = plugin;
break;
} else if (name.equals(plugin.getName())) {
rp = plugin;
break;
}
}
if (rp != null) {
try {
rp.put(new BufferedInputStream(IO.stream(file)), new RepositoryPlugin.PutOptions());
return;
} catch (Exception e) {
msgs.DeployingFile_On_Exception_(file, rp.getName(), e);
}
return;
}
logger.debug("No repo found {}", file);
throw new IllegalArgumentException("No repository found for " + file);
}
/**
* Deploy the file (which must be a bundle) into the repository.
*
* @param file bundle
*/
public void deploy(File file) throws Exception {
String name = getProperty(Constants.DEPLOYREPO);
deploy(name, file);
}
/**
* Deploy the current project to a repository
*
* @throws Exception
*/
public void deploy() throws Exception {
Parameters deploy = new Parameters(getProperty(DEPLOY), this);
if (deploy.isEmpty()) {
warning("Deploying but %s is not set to any repo", DEPLOY);
return;
}
File[] outputs = getBuildFiles();
for (File output : outputs) {
for (Deploy d : getPlugins(Deploy.class)) {
logger.debug("Deploying {} to: {}", output.getName(), d);
try {
if (d.deploy(this, output.getName(), new BufferedInputStream(IO.stream(output))))
logger.debug("deployed {} successfully to {}", output, d);
} catch (Exception e) {
msgs.Deploying(e);
}
}
}
}
/**
* Macro access to the repository ${repo;<bsn>[;<version>[;<low|high>]]}
*/
static String _repoHelp = "${repo ';'<bsn> [ ; <version> [; ('HIGHEST'|'LOWEST')]}";
public String _repo(String args[]) throws Exception {
if (args.length < 2) {
msgs.RepoTooFewArguments(_repoHelp, args);
return null;
}
String bsns = args[1];
String version = null;
Strategy strategy = Strategy.HIGHEST;
if (args.length > 2) {
version = args[2];
if (args.length == 4) {
if (args[3].equalsIgnoreCase("HIGHEST"))
strategy = Strategy.HIGHEST;
else if (args[3].equalsIgnoreCase("LOWEST"))
strategy = Strategy.LOWEST;
else if (args[3].equalsIgnoreCase("EXACT"))
strategy = Strategy.EXACT;
else
msgs.InvalidStrategy(_repoHelp, args);
}
}
Collection<String> parts = split(bsns);
List<String> paths = new ArrayList<>();
for (String bsn : parts) {
Container container = getBundle(bsn, version, strategy, null);
if (container.getError() != null) {
error("${repo} macro refers to an artifact %s-%s (%s) that has an error: %s", bsn, version, strategy,
container.getError());
} else
add(paths, container);
}
return join(paths);
}
private void add(List<String> paths, Container container) throws Exception {
if (container.getType() == Container.TYPE.LIBRARY) {
List<Container> members = container.getMembers();
for (Container sub : members) {
add(paths, sub);
}
} else {
if (container.getError() == null)
paths.add(IO.absolutePath(container.getFile()));
else {
paths.add("<<${repo} = " + container.getBundleSymbolicName() + "-" + container.getVersion() + " : "
+ container.getError() + ">>");
if (isPedantic()) {
warning("Could not expand repo path request: %s ", container);
}
}
}
}
public File getTarget() throws Exception {
prepare();
return target;
}
/**
* This is the external method that will pre-build any dependencies if it is
* out of date.
*
* @param underTest
* @throws Exception
*/
public File[] build(boolean underTest) throws Exception {
if (isNoBundles())
return null;
if (getProperty("-nope") != null) {
warning("Please replace -nope with %s", NOBUNDLES);
return null;
}
logger.debug("building {}", this);
File[] files = buildLocal(underTest);
install(files);
return files;
}
private void install(File[] files) throws Exception {
if (files == null)
return;
Parameters p = getInstallRepositories();
for (Map.Entry<String, Attrs> e : p.entrySet()) {
RepositoryPlugin rp = getWorkspace().getRepository(e.getKey());
if (rp != null) {
for (File f : files) {
install(f, rp, e.getValue());
}
} else
warning("No such repository to install into: %s", e.getKey());
}
}
public Parameters getInstallRepositories() {
if (data.installRepositories == null) {
data.installRepositories = new Parameters(mergeProperties(BUILDREPO), this);
}
return data.installRepositories;
}
private void install(File f, RepositoryPlugin repo, Attrs value) throws Exception {
try (Processor p = new Processor()) {
p.getProperties()
.putAll(value);
PutOptions options = new PutOptions();
options.context = p;
try (InputStream in = IO.stream(f)) {
repo.put(in, options);
} catch (Exception e) {
exception(e, "Cannot install %s into %s because %s", f, repo.getName(), e);
}
}
}
/**
* Return the files
*/
public File[] getFiles() {
return files;
}
/**
* Check if this project needs building. This is defined as:
*/
public boolean isStale() throws Exception {
Set<Project> visited = new HashSet<>();
return isStale(visited);
}
boolean isStale(Set<Project> visited) throws Exception {
// When we do not generate anything ...
if (isNoBundles())
return false;
if (!visited.add(this)) {
return false;
}
long buildTime = 0;
File[] files = getBuildFiles(false);
if (files == null)
return true;
for (File f : files) {
if (f.lastModified() < lastModified())
return true;
if (buildTime < f.lastModified())
buildTime = f.lastModified();
}
for (Project dependency : getDependson()) {
if (dependency == this)
continue;
if (dependency.isNoBundles()) {
continue;
}
if (dependency.isStale(visited)) {
return true;
}
File[] deps = dependency.getBuildFiles(false);
if (deps == null) {
return true;
}
for (File f : deps) {
if (buildTime < f.lastModified()) {
return true;
}
}
}
return false;
}
/**
* This method must only be called when it is sure that the project has been
* build before in the same session. It is a bit yucky, but ant creates
* different class spaces which makes it hard to detect we already build it.
* This method remembers the files in the appropriate instance vars.
*/
public File[] getBuildFiles() throws Exception {
return getBuildFiles(true);
}
public File[] getBuildFiles(boolean buildIfAbsent) throws Exception {
File[] current = files;
if (current != null) {
return current;
}
File bfs = new File(getTarget(), BUILDFILES);
if (bfs.isFile()) {
try (BufferedReader rdr = IO.reader(bfs)) {
List<File> list = newList();
for (String s = rdr.readLine(); s != null; s = rdr.readLine()) {
s = s.trim();
File ff = new File(s);
if (!ff.isFile()) {
// Originally we warned the user
// but lets just rebuild. That way
// the error is not noticed but
// it seems better to correct,
// See #154
rdr.close();
IO.delete(bfs);
return files = buildIfAbsent ? buildLocal(false) : null;
}
list.add(ff);
}
return files = list.toArray(new File[0]);
}
}
return files = buildIfAbsent ? buildLocal(false) : null;
}
/**
* Build without doing any dependency checking. Make sure any dependent
* projects are built first.
*
* @param underTest
* @throws Exception
*/
public File[] buildLocal(boolean underTest) throws Exception {
if (isNoBundles()) {
return files = null;
}
versionMap.clear();
getMakefile().make();
File[] buildfiles = getBuildFiles(false);
File bfs = new File(getTarget(), BUILDFILES);
files = null;
// #761 tstamp can vary between invocations in one build
// Macro can handle a @tstamp time so we freeze the time at
// the start of the build. We do this carefully so someone higher
// up the chain can actually freeze the time longer
boolean tstamp = false;
if (getProperty(TSTAMP) == null) {
setProperty(TSTAMP, Long.toString(System.currentTimeMillis()));
tstamp = true;
}
try (ProjectBuilder builder = getBuilder(null)) {
if (underTest)
builder.setProperty(Constants.UNDERTEST, "true");
Jar jars[] = builder.builds();
getInfo(builder);
if (isPedantic() && !unreferencedClasspathEntries.isEmpty()) {
warning("Unreferenced class path entries %s", unreferencedClasspathEntries.keySet());
}
if (!isOk()) {
return null;
}
Set<File> builtFiles = Create.set();
long lastModified = 0L;
for (Jar jar : jars) {
File file = saveBuild(jar);
if (file == null) {
getInfo(builder);
error("Could not save %s", jar.getName());
return null;
}
builtFiles.add(file);
if (lastModified < file.lastModified()) {
lastModified = file.lastModified();
}
}
boolean bfsWrite = !bfs.exists() || (lastModified > bfs.lastModified());
if (buildfiles != null) {
Set<File> removed = Create.set(buildfiles);
if (!removed.equals(builtFiles)) {
bfsWrite = true;
removed.removeAll(builtFiles);
for (File remove : removed) {
IO.delete(remove);
getWorkspace().changedFile(remove);
}
}
}
// Write out the filenames in the buildfiles file
// so we can get them later even in another process
if (bfsWrite) {
try (PrintWriter fw = IO.writer(bfs)) {
for (File f : builtFiles) {
fw.write(IO.absolutePath(f));
fw.write('\n');
}
}
getWorkspace().changedFile(bfs);
}
bfs = null; // avoid delete in finally block
return files = builtFiles.toArray(new File[0]);
} finally {
if (tstamp)
unsetProperty(TSTAMP);
if (bfs != null) {
IO.delete(bfs); // something went wrong, so delete
getWorkspace().changedFile(bfs);
}
}
}
/**
* Answer if this project does not have any output
*/
public boolean isNoBundles() {
return isTrue(getProperty(NOBUNDLES));
}
public File saveBuild(Jar jar) throws Exception {
try {
File outputFile = getOutputFile(jar.getName(), jar.getVersion());
File logicalFile = outputFile;
String msg = "";
if (!outputFile.exists() || outputFile.lastModified() < jar.lastModified()) {
reportNewer(outputFile.lastModified(), jar);
File fp = outputFile.getParentFile();
if (!fp.isDirectory()) {
IO.mkdirs(fp);
}
// On windows we sometimes cannot delete a file because
// someone holds a lock in our or another process. So if
// we set the -overwritestrategy flag we use an avoiding
// strategy.
// We will always write to a temp file name. Basically the
// calculated name + a variable suffix. We then create
// a link with the constant name to this variable name.
// This allows us to pick a different suffix when we cannot
// delete the file. Yuck, but better than the alternative.
String overwritestrategy = getProperty("-x-overwritestrategy", "classic");
swtch: switch (overwritestrategy) {
case "delay" :
for (int i = 0; i < 10; i++) {
try {
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
} catch (Exception e) {
Thread.sleep(500);
}
}
// Execute normal case to get classic behavior
// FALL THROUGH
case "classic" :
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
case "gc" :
try {
IO.deleteWithException(outputFile);
} catch (Exception e) {
System.gc();
System.runFinalization();
IO.deleteWithException(outputFile);
}
jar.write(outputFile);
break swtch;
case "windows-only-disposable-names" :
boolean isWindows = File.separatorChar == '\\';
if (!isWindows) {
IO.deleteWithException(outputFile);
jar.write(outputFile);
break;
}
// Fall through
case "disposable-names" :
int suffix = 0;
while (true) {
outputFile = new File(outputFile.getParentFile(), outputFile.getName() + "-" + suffix);
IO.delete(outputFile);
if (!outputFile.isFile()) {
// Succeeded to delete the file
jar.write(outputFile);
Files.createSymbolicLink(logicalFile.toPath(), outputFile.toPath());
break;
} else {
warning("Could not delete build file {} ", overwritestrategy);
logger.warn("Cannot delete file {} but that should be ok", outputFile);
}
suffix++;
}
break swtch;
default :
error(
"Invalid value for -x-overwritestrategy: %s, expected classic, delay, gc, windows-only-disposable-names, disposable-names",
overwritestrategy);
IO.deleteWithException(outputFile);
jar.write(outputFile);
break swtch;
}
// For maven we've got the shitty situation that the
// files in the generated directories have an ever changing
// version number so it is hard to refer to them in test cases
// and from for example bndtools if you want to refer to the
// latest so the following code attempts to create a link to the
// output file if this is using some other naming scheme,
// creating a constant name. Would probably be more logical to
// always output in the canonical name and then create a link to
// the desired name but not sure how much that would break BJ's
// maven handling that caused these versioned JARs
File canonical = new File(getTarget(), jar.getName() + ".jar");
if (!canonical.equals(logicalFile)) {
IO.delete(canonical);
if (!IO.createSymbolicLink(canonical, outputFile)) {
// As alternative, we copy the file
IO.copy(outputFile, canonical);
}
getWorkspace().changedFile(canonical);
}
getWorkspace().changedFile(outputFile);
if (!outputFile.equals(logicalFile))
getWorkspace().changedFile(logicalFile);
} else {
msg = "(not modified since " + new Date(outputFile.lastModified()) + ")";
}
logger.debug("{} ({}) {} {}", jar.getName(), outputFile.getName(), jar.getResources()
.size(), msg);
return logicalFile;
} finally
{
jar.close();
}
}
/**
* Calculate the file for a JAR. The default name is bsn.jar, but this can
* be overridden with an
*
* @throws Exception
*/
public File getOutputFile(String bsn, String version) throws Exception {
if (version == null)
version = "0";
try (Processor scoped = new Processor(this)) {
scoped.setProperty("@bsn", bsn);
scoped.setProperty("@version", version);
String path = scoped.getProperty(OUTPUTMASK, bsn + ".jar");
return IO.getFile(getTarget(), path);
}
}
public File getOutputFile(String bsn) throws Exception {
return getOutputFile(bsn, "0.0.0");
}
private void reportNewer(long lastModified, Jar jar) {
if (isTrue(getProperty(Constants.REPORTNEWER))) {
StringBuilder sb = new StringBuilder();
String del = "Newer than " + new Date(lastModified);
for (Map.Entry<String, Resource> entry : jar.getResources()
.entrySet()) {
if (entry.getValue()
.lastModified() > lastModified) {
sb.append(del);
del = ", \n ";
sb.append(entry.getKey());
}
}
if (sb.length() > 0)
warning("%s", sb.toString());
}
}
/**
* Refresh if we are based on stale data. This also implies our workspace.
*/
@Override
public boolean refresh() {
versionMap.clear();
data = new RefreshData();
boolean changed = false;
if (isCnf()) {
changed = workspace.refresh();
}
return super.refresh() || changed;
}
public boolean isCnf() {
try {
return getBase().getCanonicalPath()
.equals(getWorkspace().getBuildDir()
.getCanonicalPath());
} catch (IOException e) {
return false;
}
}
@Override
public void propertiesChanged() {
super.propertiesChanged();
preparedPaths.set(false);
files = null;
makefile = null;
versionMap.clear();
data = new RefreshData();
}
public String getName() {
return getBase().getName();
}
public Map<String, Action> getActions() {
Map<String, Action> all = newMap();
Map<String, Action> actions = newMap();
fillActions(all);
getWorkspace().fillActions(all);
for (Map.Entry<String, Action> action : all.entrySet()) {
String key = getReplacer().process(action.getKey());
if (key != null && key.trim()
.length() != 0)
actions.put(key, action.getValue());
}
return actions;
}
public void fillActions(Map<String, Action> all) {
List<NamedAction> plugins = getPlugins(NamedAction.class);
for (NamedAction a : plugins)
all.put(a.getName(), a);
Parameters actions = new Parameters(getProperty("-actions", DEFAULT_ACTIONS), this);
for (Entry<String, Attrs> entry : actions.entrySet()) {
String key = Processor.removeDuplicateMarker(entry.getKey());
Action action;
if (entry.getValue()
.get("script") != null) {
// TODO check for the type
action = new ScriptAction(entry.getValue()
.get("type"),
entry.getValue()
.get("script"));
} else {
action = new ReflectAction(key);
}
String label = entry.getValue()
.get("label");
all.put(label.toLowerCase(), action);
}
}
public void release() throws Exception {
release(false);
}
public Map.Entry<String, Resource> export(String type, Map<String, String> options) throws Exception {
Exporter exporter = getExporter(type);
if (exporter == null) {
error("No exporter for %s", type);
return null;
}
if (options == null) {
options = Collections.emptyMap();
}
Parameters exportTypes = parseHeader(getProperty(Constants.EXPORTTYPE));
Map<String, String> attrs = exportTypes.get(type);
if (attrs != null) {
attrs.putAll(options);
options = attrs;
}
return exporter.export(type, this, options);
}
private Exporter getExporter(String type) {
List<Exporter> exporters = getPlugins(Exporter.class);
for (Exporter e : exporters) {
for (String exporterType : e.getTypes()) {
if (type.equals(exporterType)) {
return e;
}
}
}
return null;
}
public void export(String runFilePath, boolean keep, File output) throws Exception {
Map<String, String> options = Collections.singletonMap("keep", Boolean.toString(keep));
Entry<String, Resource> export;
if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) {
clear();
export = export(ExecutableJarExporter.EXECUTABLE_JAR, options);
} else {
File runFile = IO.getFile(getBase(), runFilePath);
if (!runFile.isFile())
throw new IOException(
String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile)));
try (Run run = new Run(getWorkspace(), getBase(), runFile)) {
export = run.export(ExecutableJarExporter.EXECUTABLE_JAR, options);
getInfo(run);
}
}
if (export != null) {
try (JarResource r = (JarResource) export.getValue()) {
r.getJar()
.write(output);
}
}
}
/**
* @since 2.4
*/
public void exportRunbundles(String runFilePath, File outputDir) throws Exception {
Map<String, String> options = Collections.emptyMap();
Entry<String, Resource> export;
if (runFilePath == null || runFilePath.length() == 0 || ".".equals(runFilePath)) {
clear();
export = export(RunbundlesExporter.RUNBUNDLES, options);
} else {
File runFile = IO.getFile(getBase(), runFilePath);
if (!runFile.isFile())
throw new IOException(
String.format("Run file %s does not exist (or is not a file).", IO.absolutePath(runFile)));
try (Run run = new Run(getWorkspace(), getBase(), runFile)) {
export = run.export(RunbundlesExporter.RUNBUNDLES, options);
getInfo(run);
}
}
if (export != null) {
try (JarResource r = (JarResource) export.getValue()) {
r.getJar()
.writeFolder(outputDir);
}
}
}
/**
* Release.
*
* @param name The repository name
* @throws Exception
*/
public void release(String name) throws Exception {
release(name, false);
}
public void clean() throws Exception {
clean(getTargetDir(), "target");
clean(getSrcOutput(), "source output");
clean(getTestOutput(), "test output");
}
void clean(File dir, String type) throws IOException {
if (!dir.exists())
return;
String basePath = getBase().getCanonicalPath();
String dirPath = dir.getCanonicalPath();
if (!dirPath.startsWith(basePath)) {
logger.debug("path outside the project dir {}", type);
return;
}
if (dirPath.length() == basePath.length()) {
error("Trying to delete the project directory for %s", type);
return;
}
IO.delete(dir);
if (dir.exists()) {
error("Trying to delete %s (%s), but failed", dir, type);
return;
}
IO.mkdirs(dir);
}
public File[] build() throws Exception {
return build(false);
}
private Makefile getMakefile() {
if (makefile == null) {
makefile = new Makefile(this);
}
return makefile;
}
public void run() throws Exception {
try (ProjectLauncher pl = getProjectLauncher()) {
pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE)));
pl.launch();
}
}
public void runLocal() throws Exception {
try (ProjectLauncher pl = getProjectLauncher()) {
pl.setTrace(isTrace() || isTrue(getProperty(RUNTRACE)));
pl.start(null);
}
}
public void test() throws Exception {
test(null);
}
public void test(List<String> tests) throws Exception {
String testcases = getProperties().getProperty(Constants.TESTCASES);
if (testcases == null) {
warning("No %s set", Constants.TESTCASES);
return;
}
clear();
test(null, tests);
}
public void test(File reportDir, List<String> tests) throws Exception {
ProjectTester tester = getProjectTester();
if (reportDir != null) {
logger.debug("Setting reportDir {}", reportDir);
IO.delete(reportDir);
tester.setReportDir(reportDir);
}
if (tests != null) {
logger.debug("Adding tests {}", tests);
for (String test : tests) {
tester.addTest(test);
}
}
tester.prepare();
if (!isOk()) {
logger.error("Tests not run because project has errors");
return;
}
int errors = tester.test();
if (errors == 0) {
logger.info("No Errors");
} else {
if (errors > 0) {
logger.info("{} Error(s)", errors);
} else {
logger.info("Error {}", errors);
}
}
}
/**
* Run JUnit
*
* @throws Exception
*/
public void junit() throws Exception {
@SuppressWarnings("resource")
JUnitLauncher launcher = new JUnitLauncher(this);
launcher.launch();
}
/**
* This methods attempts to turn any jar into a valid jar. If this is a
* bundle with manifest, a manifest is added based on defaults. If it is a
* bundle, but not r4, we try to add the r4 headers.
*
* @throws Exception
*/
public Jar getValidJar(File f) throws Exception {
Jar jar = new Jar(f);
return getValidJar(jar, IO.absolutePath(f));
}
public Jar getValidJar(URL url) throws Exception {
try (Resource resource = Resource.fromURL(url, getPlugin(HttpClient.class))) {
Jar jar = Jar.fromResource(url.getFile()
.replace('/', '.'), resource);
return getValidJar(jar, url.toString());
}
}
public Jar getValidJar(Jar jar, String id) throws Exception {
Manifest manifest = jar.getManifest();
if (manifest == null) {
logger.debug("Wrapping with all defaults");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because lacked manifest");
b.setProperty(Constants.EXPORT_PACKAGE, "*");
b.setProperty(Constants.IMPORT_PACKAGE, "*;resolution:=optional");
jar = b.build();
} else if (manifest.getMainAttributes()
.getValue(Constants.BUNDLE_MANIFESTVERSION) == null) {
logger.debug("Not a release 4 bundle, wrapping with manifest as source");
Builder b = new Builder(this);
this.addClose(b);
b.addClasspath(jar);
b.setProperty(Constants.PRIVATE_PACKAGE, "*");
b.mergeManifest(manifest);
String imprts = manifest.getMainAttributes()
.getValue(Constants.IMPORT_PACKAGE);
if (imprts == null)
imprts = "";
else
imprts += ",";
imprts += "*;resolution=optional";
b.setProperty(Constants.IMPORT_PACKAGE, imprts);
b.setProperty("Bnd-Message", "Wrapped from " + id + "because had incomplete manifest");
jar = b.build();
}
return jar;
}
public String _project(@SuppressWarnings("unused") String args[]) {
return IO.absolutePath(getBase());
}
/**
* Bump the version of this project. First check the main bnd file. If this
* does not contain a version, check the include files. If they still do not
* contain a version, then check ALL the sub builders. If not, add a version
* to the main bnd file.
*
* @param mask the mask for bumping, see {@link Macro#_version(String[])}
* @throws Exception
*/
public void bump(String mask) throws Exception {
String pattern = "(" + Constants.BUNDLE_VERSION + "\\s*(:|=)\\s*)(([0-9]+(\\.[0-9]+(\\.[0-9]+)?)?))";
String replace = "$1${version;" + mask + ";$3}";
try {
// First try our main bnd file
if (replace(getPropertiesFile(), pattern, replace))
return;
logger.debug("no version in bnd.bnd");
// Try the included filed in reverse order (last has highest
// priority)
for (Iterator<File> iter = new ArrayDeque<>(getIncluded()).descendingIterator(); iter.hasNext();) {
File file = iter.next();
if (replace(file, pattern, replace)) {
logger.debug("replaced version in file {}", file);
return;
}
}
logger.debug("no version in included files");
boolean found = false;
// Replace in all sub builders.
try (ProjectBuilder b = getBuilder(null)) {
for (Builder sub : b.getSubBuilders()) {
found |= replace(sub.getPropertiesFile(), pattern, replace);
}
}
if (!found) {
logger.debug("no version in sub builders, add it to bnd.bnd");
String bndfile = IO.collect(getPropertiesFile());
bndfile += "\n# Added by by bump\n" + Constants.BUNDLE_VERSION + ": 0.0.0\n";
IO.store(bndfile, getPropertiesFile());
}
} finally {
forceRefresh();
}
}
boolean replace(File f, String pattern, String replacement) throws IOException {
final Macro macro = getReplacer();
Sed sed = new Sed(new Replacer() {
@Override
public String process(String line) {
return macro.process(line);
}
}, f);
sed.replace(pattern, replacement);
return sed.doIt() > 0;
}
public void bump() throws Exception {
bump(getProperty(BUMPPOLICY, "=+0"));
}
public void action(String command) throws Exception {
action(command, new Object[0]);
}
public void action(String command, Object... args) throws Exception {
Map<String, Action> actions = getActions();
Action a = actions.get(command);
if (a == null)
a = new ReflectAction(command);
before(this, command);
try {
if (args.length == 0)
a.execute(this, command);
else
a.execute(this, args);
} catch (Exception t) {
after(this, command, t);
throw t;
}
}
/**
* Run all before command plugins
*/
void before(@SuppressWarnings("unused") Project p, String a) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (CommandPlugin testPlugin : testPlugins) {
testPlugin.before(this, a);
}
}
/**
* Run all after command plugins
*/
void after(@SuppressWarnings("unused") Project p, String a, Throwable t) {
List<CommandPlugin> testPlugins = getPlugins(CommandPlugin.class);
for (int i = testPlugins.size() - 1; i >= 0; i
testPlugins.get(i)
.after(this, a, t);
}
}
public void refreshAll() {
workspace.refresh();
refresh();
}
@SuppressWarnings("unchecked")
public void script(@SuppressWarnings("unused") String type, String script) throws Exception {
script(type, script, new Object[0]);
}
@SuppressWarnings({
"unchecked", "rawtypes"
})
public void script(String type, String script, Object... args) throws Exception {
// TODO check tyiping
List<Scripter> scripters = getPlugins(Scripter.class);
if (scripters.isEmpty()) {
msgs.NoScripters_(script);
return;
}
Properties p = new UTF8Properties(getProperties());
for (int i = 0; i < args.length; i++)
p.setProperty("" + i, Converter.cnv(String.class, args[i]));
scripters.get(0)
.eval((Map) p, new StringReader(script));
}
public String _repos(@SuppressWarnings("unused") String args[]) throws Exception {
List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class);
List<String> names = new ArrayList<>();
for (RepositoryPlugin rp : repos)
names.add(rp.getName());
return join(names, ", ");
}
public String _help(String args[]) throws Exception {
if (args.length == 1)
return "Specify the option or header you want information for";
Syntax syntax = Syntax.HELP.get(args[1]);
if (syntax == null)
return "No help for " + args[1];
String what = null;
if (args.length > 2)
what = args[2];
if (what == null || what.equals("lead"))
return syntax.getLead();
if (what.equals("example"))
return syntax.getExample();
if (what.equals("pattern"))
return syntax.getPattern();
if (what.equals("values"))
return syntax.getValues();
return "Invalid type specified for help: lead, example, pattern, values";
}
/**
* Returns containers for the deliverables of this project. The deliverables
* is the project builder for this project if no -sub is specified.
* Otherwise it contains all the sub bnd files.
*
* @return A collection of containers
* @throws Exception
*/
public Collection<Container> getDeliverables() throws Exception {
List<Container> result = new ArrayList<>();
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder builder : pb.getSubBuilders()) {
Container c = new Container(this, builder.getBsn(), builder.getVersion(), Container.TYPE.PROJECT,
getOutputFile(builder.getBsn(), builder.getVersion()), null, null, null);
result.add(c);
}
return result;
}
}
/**
* Return a builder associated with the give bnd file or null. The bnd.bnd
* file can contain -sub option. This option allows specifying files in the
* same directory that should drive the generation of multiple deliverables.
* This method figures out if the bndFile is actually one of the bnd files
* of a deliverable.
*
* @param bndFile A file pointing to a bnd file.
* @return null or a builder for a sub file, the caller must close this
* builder
* @throws Exception
*/
public Builder getSubBuilder(File bndFile) throws Exception {
bndFile = bndFile.getAbsoluteFile();
// Verify that we are inside the project.
if (!bndFile.toPath()
.startsWith(getBase().toPath()))
return null;
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
for (Builder b : pb.getSubBuilders()) {
File propertiesFile = b.getPropertiesFile();
if (propertiesFile != null) {
if (propertiesFile.equals(bndFile)) {
// Found it!
// disconnect from its parent life cycle
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
return b;
}
}
}
return null;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Return a build that maps to the sub file.
*
* @param string
* @throws Exception
*/
public ProjectBuilder getSubBuilder(String string) throws Exception {
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
for (Builder b : pb.getSubBuilders()) {
if (b.getBsn()
.equals(string)
|| b.getBsn()
.endsWith("." + string)) {
// disconnect from its parent life cycle
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
return (ProjectBuilder) b;
}
}
return null;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Answer the container associated with a given bsn.
*
* @throws Exception
*/
public Container getDeliverable(String bsn, Map<String, String> attrs) throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder b : pb.getSubBuilders()) {
if (b.getBsn()
.equals(bsn))
return new Container(this, getOutputFile(bsn, b.getVersion()), attrs);
}
}
return null;
}
/**
* Get a list of the sub builders. A bnd.bnd file can contain the -sub
* option. This will generate multiple deliverables. This method returns the
* builders for each sub file. If no -sub option is present, the list will
* contain a builder for the bnd.bnd file.
*
* @return A list of builders.
* @throws Exception
* @deprecated As of 3.4. Replace with
*
* <pre>
* try (ProjectBuilder pb = getBuilder(null)) {
* for (Builder b : pb.getSubBuilders()) {
* ...
* }
* }
* </pre>
*/
@Deprecated
public Collection<? extends Builder> getSubBuilders() throws Exception {
ProjectBuilder pb = getBuilder(null);
boolean close = true;
try {
List<Builder> builders = pb.getSubBuilders();
for (Builder b : builders) {
if (b == pb) {
close = false;
} else {
pb.removeClose(b);
}
}
return builders;
} finally {
if (close) {
pb.close();
}
}
}
/**
* Calculate the classpath. We include our own runtime.jar which includes
* the test framework and we include the first of the test frameworks
* specified.
*
* @throws Exception
*/
Collection<File> toFile(Collection<Container> containers) throws Exception {
ArrayList<File> files = new ArrayList<>();
for (Container container : containers) {
container.contributeFiles(files, this);
}
return files;
}
public Collection<String> getRunVM() {
Parameters hdr = getMergedParameters(RUNVM);
return hdr.keyList();
}
public Collection<String> getRunProgramArgs() {
Parameters hdr = getMergedParameters(RUNPROGRAMARGS);
return hdr.keyList();
}
public Map<String, String> getRunProperties() {
return OSGiHeader.parseProperties(mergeProperties(RUNPROPERTIES));
}
/**
* Get a launcher.
*
* @throws Exception
*/
public ProjectLauncher getProjectLauncher() throws Exception {
return getHandler(ProjectLauncher.class, getRunpath(), LAUNCHER_PLUGIN, "biz.aQute.launcher");
}
public ProjectTester getProjectTester() throws Exception {
String defaultDefault = since(About._3_0) ? "biz.aQute.tester" : "biz.aQute.junit";
return getHandler(ProjectTester.class, getTestpath(), TESTER_PLUGIN,
getProperty(Constants.TESTER, defaultDefault));
}
private <T> T getHandler(Class<T> target, Collection<Container> containers, String header, String defaultHandler)
throws Exception {
Class<? extends T> handlerClass = target;
// Make sure we find at least one handler, but hope to find an earlier
// one
List<Container> withDefault = Create.list();
withDefault.addAll(containers);
withDefault.addAll(getBundles(Strategy.HIGHEST, defaultHandler, null));
logger.debug("candidates for handler {}: {}", target, withDefault);
for (Container c : withDefault) {
Manifest manifest = c.getManifest();
if (manifest != null) {
String launcher = manifest.getMainAttributes()
.getValue(header);
if (launcher != null) {
Class<?> clz = getClass(launcher, c.getFile());
if (clz != null) {
if (!target.isAssignableFrom(clz)) {
msgs.IncompatibleHandler_For_(launcher, defaultHandler);
} else {
logger.debug("found handler {} from {}", defaultHandler, c);
handlerClass = clz.asSubclass(target);
Constructor<? extends T> constructor;
try {
constructor = handlerClass.getConstructor(Project.class, Container.class);
} catch (NoSuchMethodException e) {
constructor = handlerClass.getConstructor(Project.class);
}
try {
return (constructor.getParameterCount() == 1) ? constructor.newInstance(this)
: constructor.newInstance(this, c);
} catch (InvocationTargetException e) {
throw Exceptions.duck(e.getCause());
}
}
}
}
}
}
throw new IllegalArgumentException("Default handler for " + header + " not found in " + defaultHandler);
}
/**
* Make this project delay the calculation of the run dependencies. The run
* dependencies calculation can be done in prepare or until the dependencies
* are actually needed.
*/
public void setDelayRunDependencies(boolean x) {
delayRunDependencies = x;
}
/**
* bnd maintains a class path that is set by the environment, i.e. bnd is
* not in charge of it.
*/
public void addClasspath(File f) {
if (!f.isFile() && !f.isDirectory()) {
msgs.AddingNonExistentFileToClassPath_(f);
}
Container container = new Container(f, null);
classpath.add(container);
}
public void clearClasspath() {
classpath.clear();
unreferencedClasspathEntries.clear();
}
public Collection<Container> getClasspath() {
return classpath;
}
/**
* Pack the project (could be a bndrun file) and save it on disk. Report
* errors if they happen.
*/
static List<String> ignore = new ExtList<>(BUNDLE_SPECIFIC_HEADERS);
/**
* Caller must close this JAR
*
* @param profile
* @return a jar with the executable code
* @throws Exception
*/
public Jar pack(String profile) throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
List<Builder> subBuilders = pb.getSubBuilders();
if (subBuilders.size() != 1) {
error("Project has multiple bnd files, please select one of the bnd files").header(EXPORT)
.context(profile);
return null;
}
Builder b = subBuilders.iterator()
.next();
ignore.remove(BUNDLE_SYMBOLICNAME);
ignore.remove(BUNDLE_VERSION);
ignore.add(SERVICE_COMPONENT);
try (ProjectLauncher launcher = getProjectLauncher()) {
launcher.getRunProperties()
.put("profile", profile); // TODO
// remove
launcher.getRunProperties()
.put(PROFILE, profile);
Jar jar = launcher.executable();
Manifest m = jar.getManifest();
Attributes main = m.getMainAttributes();
for (String key : this) {
if (Character.isUpperCase(key.charAt(0)) && !ignore.contains(key)) {
String value = getProperty(key);
if (value == null)
continue;
Name name = new Name(key);
String trimmed = value.trim();
if (trimmed.isEmpty())
main.remove(name);
else if (EMPTY_HEADER.equals(trimmed))
main.put(name, "");
else
main.put(name, value);
}
}
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, b.getBsn());
if (main.getValue(BUNDLE_SYMBOLICNAME) == null)
main.putValue(BUNDLE_SYMBOLICNAME, getName());
if (main.getValue(BUNDLE_VERSION) == null) {
main.putValue(BUNDLE_VERSION, Version.LOWEST.toString());
warning("No version set, uses 0.0.0");
}
jar.setManifest(m);
jar.calcChecksums(new String[] {
"SHA1", "MD5"
});
launcher.removeClose(jar);
return jar;
}
}
}
/**
* Do a baseline for this project
*
* @throws Exception
*/
public void baseline() throws Exception {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder b : pb.getSubBuilders()) {
@SuppressWarnings("resource")
Jar build = b.build();
getInfo(b);
}
getInfo(pb);
}
}
/**
* Method to verify that the paths are correct, ie no missing dependencies
*
* @param test for test cases, also adds -testpath
* @throws Exception
*/
public void verifyDependencies(boolean test) throws Exception {
verifyDependencies(RUNBUNDLES, getRunbundles());
verifyDependencies(RUNPATH, getRunpath());
if (test)
verifyDependencies(TESTPATH, getTestpath());
verifyDependencies(BUILDPATH, getBuildpath());
}
private void verifyDependencies(String title, Collection<Container> path) throws Exception {
List<String> msgs = new ArrayList<>();
for (Container c : new ArrayList<>(path)) {
for (Container cc : c.getMembers()) {
if (cc.getError() != null)
msgs.add(cc + " - " + cc.getError());
else if (!cc.getFile()
.isFile()
&& !cc.getFile()
.equals(cc.getProject()
.getOutput())
&& !cc.getFile()
.equals(cc.getProject()
.getTestOutput()))
msgs.add(cc + " file does not exists: " + cc.getFile());
}
}
if (msgs.isEmpty())
return;
error("%s: has errors: %s", title, Strings.join(msgs));
}
/**
* Report detailed info from this project
*
* @throws Exception
*/
@Override
public void report(Map<String, Object> table) throws Exception {
super.report(table);
report(table, true);
}
protected void report(Map<String, Object> table, boolean isProject) throws Exception {
if (isProject) {
table.put("Target", getTarget());
table.put("Source", getSrc());
table.put("Output", getOutput());
File[] buildFiles = getBuildFiles();
if (buildFiles != null)
table.put("BuildFiles", Arrays.asList(buildFiles));
table.put("Classpath", getClasspath());
table.put("Actions", getActions());
table.put("AllSourcePath", getAllsourcepath());
table.put("BootClassPath", getBootclasspath());
table.put("BuildPath", getBuildpath());
table.put("Deliverables", getDeliverables());
table.put("DependsOn", getDependson());
table.put("SourcePath", getSourcePath());
}
table.put("RunPath", getRunpath());
table.put("TestPath", getTestpath());
table.put("RunProgramArgs", getRunProgramArgs());
table.put("RunVM", getRunVM());
table.put("Runfw", getRunFw());
table.put("Runbundles", getRunbundles());
}
// TODO test format parametsr
public void compile(boolean test) throws Exception {
Command javac = getCommonJavac(false);
javac.add("-d", IO.absolutePath(getOutput()));
StringBuilder buildpath = new StringBuilder();
String buildpathDel = "";
Collection<Container> bp = Container.flatten(getBuildpath());
logger.debug("buildpath {}", getBuildpath());
for (Container c : bp) {
buildpath.append(buildpathDel)
.append(IO.absolutePath(c.getFile()));
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
List<File> sp = new ArrayList<>(getSourcePath());
StringBuilder sourcepath = new StringBuilder();
String sourcepathDel = "";
for (File sourceDir : sp) {
sourcepath.append(sourcepathDel)
.append(IO.absolutePath(sourceDir));
sourcepathDel = File.pathSeparator;
}
javac.add("-sourcepath", sourcepath.toString());
Glob javaFiles = new Glob("*.java");
List<File> files = javaFiles.getFiles(getSrc(), true, false);
for (File file : files) {
javac.add(IO.absolutePath(file));
}
if (files.isEmpty()) {
logger.debug("Not compiled, no source files");
} else
compile(javac, "src");
if (test) {
javac = getCommonJavac(true);
javac.add("-d", IO.absolutePath(getTestOutput()));
Collection<Container> tp = Container.flatten(getTestpath());
for (Container c : tp) {
buildpath.append(buildpathDel)
.append(IO.absolutePath(c.getFile()));
buildpathDel = File.pathSeparator;
}
if (buildpath.length() != 0) {
javac.add("-classpath", buildpath.toString());
}
sourcepath.append(sourcepathDel)
.append(IO.absolutePath(getTestSrc()));
javac.add("-sourcepath", sourcepath.toString());
javaFiles.getFiles(getTestSrc(), files, true, false);
for (File file : files) {
javac.add(IO.absolutePath(file));
}
if (files.isEmpty()) {
logger.debug("Not compiled for test, no test src files");
} else
compile(javac, "test");
}
}
private void compile(Command javac, String what) throws Exception {
logger.debug("compile {} {}", what, javac);
StringBuilder stdout = new StringBuilder();
StringBuilder stderr = new StringBuilder();
int n = javac.execute(stdout, stderr);
logger.debug("javac stdout: {}", stdout);
logger.debug("javac stderr: {}", stderr);
if (n != 0) {
error("javac failed %s", stderr);
}
}
private Command getCommonJavac(boolean test) throws Exception {
Command javac = new Command();
javac.add(getProperty("javac", "javac"));
String target = getProperty("javac.target", "1.6");
String profile = getProperty("javac.profile", "");
String source = getProperty("javac.source", "1.6");
String debug = getProperty("javac.debug");
if ("on".equalsIgnoreCase(debug) || "true".equalsIgnoreCase(debug))
debug = "vars,source,lines";
Parameters options = new Parameters(getProperty("java.options"), this);
boolean deprecation = isTrue(getProperty("java.deprecation"));
javac.add("-encoding", "UTF-8");
javac.add("-source", source);
javac.add("-target", target);
if (!profile.isEmpty())
javac.add("-profile", profile);
if (deprecation)
javac.add("-deprecation");
if (test || debug == null) {
javac.add("-g:source,lines,vars");
} else {
javac.add("-g:" + debug);
}
javac.addAll(options.keyList());
StringBuilder bootclasspath = new StringBuilder();
String bootclasspathDel = "-Xbootclasspath/p:";
Collection<Container> bcp = Container.flatten(getBootclasspath());
for (Container c : bcp) {
bootclasspath.append(bootclasspathDel)
.append(IO.absolutePath(c.getFile()));
bootclasspathDel = File.pathSeparator;
}
if (bootclasspath.length() != 0) {
javac.add(bootclasspath.toString());
}
return javac;
}
public String _ide(String[] args) throws IOException {
if (args.length < 2) {
error("The ${ide;<>} macro needs an argument");
return null;
}
if (ide == null) {
ide = new UTF8Properties();
File file = getFile(".settings/org.eclipse.jdt.core.prefs");
if (!file.isFile()) {
error("The ${ide;<>} macro requires a .settings/org.eclipse.jdt.core.prefs file in the project");
return null;
}
try (InputStream in = IO.stream(file)) {
ide.load(in);
}
}
String deflt = args.length > 2 ? args[2] : null;
if ("javac.target".equals(args[1])) {
return ide.getProperty("org.eclipse.jdt.core.compiler.codegen.targetPlatform", deflt);
}
if ("javac.source".equals(args[1])) {
return ide.getProperty("org.eclipse.jdt.core.compiler.source", deflt);
}
return null;
}
public Map<String, Version> getVersions() throws Exception {
if (versionMap.isEmpty()) {
try (ProjectBuilder pb = getBuilder(null)) {
for (Builder builder : pb.getSubBuilders()) {
String v = builder.getVersion();
if (v == null)
v = "0";
else {
v = Analyzer.cleanupVersion(v);
if (!Verifier.isVersion(v))
continue; // skip
}
Version version = new Version(v);
versionMap.put(builder.getBsn(), version);
}
}
}
return new LinkedHashMap<>(versionMap);
}
public Collection<String> getBsns() throws Exception {
return new ArrayList<>(getVersions().keySet());
}
public Version getVersion(String bsn) throws Exception {
Version version = getVersions().get(bsn);
if (version == null) {
throw new IllegalArgumentException("Bsn " + bsn + " does not exist in project " + getName());
}
return version;
}
/**
* Get the exported packages form all builders calculated from the last
* build
*/
public Packages getExports() {
return exportedPackages;
}
/**
* Get the imported packages from all builders calculated from the last
* build
*/
public Packages getImports() {
return importedPackages;
}
/**
* Get the contained packages calculated from all builders from the last
* build
*/
public Packages getContained() {
return containedPackages;
}
public void remove() throws Exception {
getWorkspace().removeProject(this);
IO.delete(getBase());
}
public boolean getRunKeep() {
return is(Constants.RUNKEEP);
}
public void setPackageInfo(String packageName, Version newVersion) throws Exception {
packageInfo.setPackageInfo(packageName, newVersion);
}
public Version getPackageInfo(String packageName) throws Exception {
return packageInfo.getPackageInfo(packageName);
}
/**
* Actions to perform before a full workspace release. This is executed for
* projects that describe the distribution
*/
public void preRelease() {
for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) {
rp.begin(this);
}
}
/**
* Actions to perform after a full workspace release. This is executed for
* projects that describe the distribution
*/
public void postRelease() {
for (ReleaseBracketingPlugin rp : getWorkspace().getPlugins(ReleaseBracketingPlugin.class)) {
rp.end(this);
}
}
/**
* Copy a repository to another repository
*
* @throws Exception
*/
public void copy(RepositoryPlugin source, String filter, RepositoryPlugin destination) throws Exception {
copy(source, filter == null ? null : new Instructions(filter), destination);
}
public void copy(RepositoryPlugin source, Instructions filter, RepositoryPlugin destination) throws Exception {
assert source != null;
assert destination != null;
logger.info("copy from repo {} to {} with filter {}", source, destination, filter);
for (String bsn : source.list(null)) {
for (Version version : source.versions(bsn)) {
if (filter == null || filter.matches(bsn)) {
logger.info("copy {}:{}", bsn, version);
File file = source.get(bsn, version, null);
if (file.getName()
.endsWith(".jar")) {
try (InputStream in = IO.stream(file)) {
PutOptions po = new PutOptions();
po.bsn = bsn;
po.context = null;
po.type = "bundle";
po.version = version;
PutResult put = destination.put(in, po);
} catch (Exception e) {
logger.error("Failed to copy {}-{}", e, bsn, version);
error("Failed to copy %s:%s from %s to %s, error: %s", bsn, version, source, destination,
e);
}
}
}
}
}
}
@Override
public boolean isInteractive() {
return getWorkspace().isInteractive();
}
/**
* Return a basic type only specification of the run aspect of this project
*/
public RunSpecification getSpecification() {
RunSpecification runspecification = new RunSpecification();
try {
runspecification.bin = getOutput().getAbsolutePath();
runspecification.bin_test = getTestOutput().getAbsolutePath();
runspecification.target = getTarget().getAbsolutePath();
runspecification.errors.addAll(getErrors());
runspecification.extraSystemCapabilities = getRunSystemCapabilities().toBasic();
runspecification.extraSystemPackages = getRunSystemPackages().toBasic();
runspecification.properties = getRunProperties();
runspecification.runbundles = toPaths(runspecification.errors, getRunbundles());
runspecification.runfw = toPaths(runspecification.errors, getRunFw());
runspecification.runpath = toPaths(runspecification.errors, getRunpath());
} catch (Exception e) {
runspecification.errors.add(e.toString());
}
return runspecification;
}
public Parameters getRunSystemPackages() {
return new Parameters(mergeProperties(Constants.RUNSYSTEMPACKAGES));
}
public Parameters getRunSystemCapabilities() {
return new Parameters(mergeProperties(Constants.RUNSYSTEMCAPABILITIES));
}
}
|
package me.buildcarter8.iBukkit;
import java.util.logging.Logger;
import me.buildcarter8.iBukkit.utils.Messages;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
//Recommended for: CraftBukkit 1.8.* Can be used for: Spigot 1.8.6
public class Main extends JavaPlugin
{
public static final String iBukkitVersion = "2";
public static final String buildNumber = "3";
public static final String SpigotVersion = "1.8.6" + "1.8.7";
public static final String spigot = "Spigot-1.8.6+";
public static final String pluginfile = "plugin.yml";
public final Logger log = Logger.getLogger("Minecraft-Server");
public static Main plugin;
@Override
public void onDisable() {
log.info(" iBukkit Features Have Been Disabled!");
}
@Override
public void onLoad() {
log.info("Loading iBukkit...");
log.info("Created by buildcarter8...");
log.info("Loading iBukkit Utils...");
}
@Override
public void onEnable() {
log.info("iBukkit Features are now usable!");
}
//TODO: Code it better
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player) sender;
if(cmd.getName().equalsIgnoreCase("ibukkit"))
{
sender.sendMessage(ChatColor.AQUA + "iBukkit -- Version " + iBukkitVersion + "." + buildNumber);
sender.sendMessage(ChatColor.AQUA + "iBukkit was designed to help the average developer and make it easier for him/her");
}
return true;
}
}
|
package de.bitbrain.braingdx.ui;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import java.util.HashSet;
import java.util.Set;
import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenEquation;
import aurelienribon.tweenengine.TweenEquations;
import aurelienribon.tweenengine.TweenManager;
import de.bitbrain.braingdx.tweens.ActorTween;
import de.bitbrain.braingdx.tweens.SharedTweenManager;
/**
* Provides tooltips on the screen
*
* @since 1.0.0
* @version 1.0.0
* @author Miguel Gonzalez <miguel-gonzalez@gmx.de>
*/
public class Tooltip {
private static final Tooltip instance = new Tooltip();
private TweenManager tweenManager = SharedTweenManager.getInstance();
private Stage stage;
private Camera camera;
private Set<Label> tooltips = new HashSet<Label>();
private TweenEquation equation;
private float duration;
private float scale;
private Tooltip() {
setTweenEquation(TweenEquations.easeOutCubic);
duration = 0.9f;
scale = 1.0f;
}
public static Tooltip getInstance() {
return instance;
}
public void create(float x, float y, Label.LabelStyle style, String text) {
create(x, y, style, text, Color.WHITE);
}
public void create(float x, float y, Label.LabelStyle style, String text, Color color) {
final Label tooltip = new Label(text, style) {
@Override
public float getX() {
return super.getX() - camera.position.x + camera.viewportWidth / 2f - this.getWidth() / 2f;
}
@Override
public float getY() {
return super.getY() - camera.position.y + camera.viewportHeight / 2f - this.getHeight() / 2f;
}
@Override
public float getOriginX() {
return super.getOriginX() + this.getWidth() / 2f;
}
@Override
public float getOriginY() {
return super.getOriginY() + this.getHeight() / 2f;
}
};
tooltip.setColor(color);
tooltip.setPosition(x, y);
stage.addActor(tooltip);
tooltips.add(tooltip);
Tween.to(tooltip, ActorTween.ALPHA, this.duration).target(0f).setCallbackTriggers(TweenCallback.COMPLETE)
.setCallback(new TweenCallback() {
@Override
public void onEvent(int type, BaseTween<?> source) {
stage.getActors().removeValue(tooltip, true);
}
}).ease(equation).start(tweenManager);
Tween.to(tooltip, ActorTween.SCALE, this.duration).target(scale).ease(equation).start(tweenManager);
}
public void setDuration(float duration) {
this.duration = duration;
}
public void setTweenEquation(TweenEquation equation) {
this.equation = equation;
}
public void setScale(float scale) {
this.scale = scale;
}
public void clear() {
for (Label l : tooltips) {
tweenManager.killTarget(l);
stage.getActors().removeValue(l, true);
}
tooltips.clear();
}
public void init(Stage stage, Camera camera) {
this.stage = stage;
this.camera = camera;
}
}
|
package nodes.modifiers;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.util.Set;
import processing.core.PApplet;
import controlP5.CallbackEvent;
import controlP5.CallbackListener;
import controlP5.ControlP5;
import controlP5.Textfield;
import nodes.Edge;
import nodes.Graph;
import nodes.Modifier;
import nodes.Node;
import nodes.Selection;
/**
* @author karim
*
* Search modifier, adds the ability to search for nodes containing or matching a string specified by the user
* via a popup window
*/
public class TripleSearch extends Modifier {
public TripleSearch(Graph graph) {
super(graph);
}
@Override
public boolean isCompatible() {
return graph.tripleCount() > 0;
}
@Override
public String getTitle() {
return "Search";
}
@Override
public void modify() {
SearchFrame s = new SearchFrame(this);
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
String searchTerm = s.getSearchTerm();
s.close();
if (searchTerm == null || searchTerm.isEmpty())
return;
Selection sele = graph.getSelection();
sele.clearBuffer();
sele.clear();
Set<Edge> edges = graph.getEdges();
Node src, dest;
for (Edge e : edges) {
src = e.getSourceNode();
dest = e.getDestinationNode();
if(e.getName().contains(searchTerm) || graph.prefixed(e.getName()).contains(searchTerm))
sele.addToBuffer(e);
if (src != null && (src.getName().contains(searchTerm) || graph.prefixed(src.getName()).contains(searchTerm)))
sele.addToBuffer(src);
if (dest != null && (dest.getName().contains(searchTerm) || graph.prefixed(dest.getName()).contains(searchTerm)))
sele.addToBuffer(dest);
src = null;
dest = null;
}
sele.commitBuffer();
}
/*
* Mostly taken from TripleChoserFrame by kdbanman
*/
private class SearchFrame extends Frame {
private static final long serialVersionUID = 1150469663366192294L;
private String searchTerm;
int frameW, frameH;
Object waiting;
SearchWindow search;
public SearchFrame(Object waitingObj) {
super("Enter search text");
frameW = 300;
frameH = 100;
waiting = waitingObj;
setLayout(new BorderLayout());
setSize(frameW, frameH);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
search = new SearchWindow();
add(search, BorderLayout.CENTER);
validate();
search.init();
}
public void close() {
search.stop();
dispose();
}
public String getSearchTerm() {
return searchTerm;
}
public void setSearchTerm(String searchTerm) {
this.searchTerm = searchTerm;
}
private class SearchWindow extends PApplet {
private static final long serialVersionUID = 982758246505135143L;
ControlP5 cp5;
Textfield sBox;
public SearchWindow() {}
@Override
public void setup() {
size(frameW, frameH);
cp5 = new ControlP5(this);
sBox = cp5.addTextfield("search text").setPosition(20, 20)
.setSize(150, 20).setText("").setFocus(true);
setSearchTerm("");
cp5.addButton("FIND TRIPLES").setPosition(200, 20)
.setSize(70, 20).addCallback(new CallbackListener() {
@Override
public void controlEvent(CallbackEvent event) {
if (event.getAction() == ControlP5.ACTION_RELEASED) {
setSearchTerm(sBox.getText());
synchronized (waiting) {
waiting.notify();
}
}
}
});
}
@Override
public void draw() {
background(0);
}
}
}
}
|
package org.basex.query;
import static org.basex.data.DataText.*;
import java.util.ArrayList;
import java.util.Stack;
import org.basex.core.Context;
import org.basex.data.Data;
import org.basex.data.SkelNode;
import org.basex.data.Skeleton;
import org.basex.query.item.Type;
import org.basex.query.path.Axis;
import org.basex.query.path.NameTest;
import org.basex.query.path.Test;
import org.basex.util.StringList;
import org.basex.util.Token;
public class QuerySuggest extends QueryParser {
/** Context. */
Context ctx;
/** Current skeleton nodes. */
Stack<ArrayList<SkelNode>> stack = new Stack<ArrayList<SkelNode>>();
/** Skeleton reference. */
Skeleton skel;
/** Last axis. */
Axis laxis;
/** Last test. */
Test ltest;
/**
* Constructor.
* @param c QueryContext
* @param context Context
*/
public QuerySuggest(final QueryContext c, final Context context) {
super(c);
ctx = context;
skel = ctx.data().skel;
}
@Override
void sugPath(final int type) {
if (type == 0) {
//System.out.println("absLocPath");
final ArrayList<SkelNode> list = new ArrayList<SkelNode>();
list.add(skel.root);
stack.push(list);
} else if (type == 1) {
//System.out.println("relLocPath");
ArrayList<SkelNode> list = null;
if(stack.size() == 0) {
if(!ctx.root()) return;
list = new ArrayList<SkelNode>();
list.add(skel.root);
} else {
list = skel.desc(stack.peek(), 0, Data.ELEM, false);
}
stack.push(list);
}
}
@Override
void checkStep(final Axis axis, final Test test) {
//System.out.println("checkStep: " + axis + " " + test);
filter(true);
if(axis == null) {
if(!stack.empty()) stack.push(skel.desc(stack.pop(), 0,
Data.ELEM, false));
return;
}
// [CG] Suggest/check when stack is empty at this stage
if(!stack.empty()) {
if(axis == Axis.CHILD) {
stack.push(skel.desc(stack.pop(), 0, Data.ELEM, false));
} else if(axis == Axis.ATTR) {
stack.push(skel.desc(stack.pop(), 0, Data.ATTR, false));
} else if(axis == Axis.DESC || axis == Axis.DESCORSELF) {
stack.push(skel.desc(stack.pop(), 0, Data.ELEM, true));
} else {
stack.peek().clear();
}
}
laxis = axis;
ltest = test;
}
/**
* Filters the current steps.
* @param finish finish flag
*/
public void filter(final boolean finish) {
//System.out.println("Filter: " + finish);
if(laxis == null) return;
if(finish && ltest == Test.NODE) return;
final byte[] tn = entry(laxis, ltest);
if(tn == null) return;
/**
* Returns the code completions.
* @return completions
*/
public StringList complete() {
//System.out.println("complete");
final StringList sl = new StringList();
if(stack.empty()) return sl;
for(final SkelNode r : stack.peek()) {
final String name = Token.string(r.token(ctx.data()));
if(name.length() != 0 && !sl.contains(name)) sl.add(name);
}
sl.sort(true);
return sl;
}
/**
* Returns a node entry.
* @param a axis
* @param t text
* @return completion
*/
private byte[] entry(final Axis a, final Test t) {
//System.out.println("entry: " + a + " " + t);
if(t.type == Type.TXT) {
return TEXT;
}
if(t.type == Type.COM) {
return COMM;
}
if(t.type == Type.PI) {
return PI;
}
if(t instanceof NameTest && t.name != null) {
final byte[] name = t.name.ln();
return a == Axis.ATTR ? Token.concat(ATT, name) : name;
}
return Token.EMPTY;
}
@Override
void error(final Object[] err, final Object... arg) throws QueryException {
System.out.println("error");
final QueryException qe = new QueryException(err, arg);
System.out.println(qe.simple());
mark();
if (qe.simple().startsWith("Unexpected") ||
qe.simple().equals("Expecting attribute name.")) filter(false);
qe.complete(this, complete());
throw qe;
}
}
|
package org.basex.query.func;
import static org.basex.query.QueryText.*;
import static org.basex.query.QueryTokens.*;
import static org.basex.util.Token.*;
import java.io.IOException;
import org.basex.build.xml.XMLInput;
import org.basex.core.Main;
import org.basex.core.User;
import org.basex.data.Data;
import org.basex.data.Data.Type;
import org.basex.io.IO;
import org.basex.query.IndexContext;
import org.basex.query.QueryContext;
import org.basex.query.QueryException;
import org.basex.query.expr.Expr;
import org.basex.query.expr.IndexAccess;
import org.basex.query.ft.FTIndexAccess;
import org.basex.query.ft.FTWords;
import org.basex.query.item.DBNode;
import org.basex.query.item.Dbl;
import org.basex.query.item.Item;
import org.basex.query.item.Str;
import org.basex.query.iter.Iter;
import org.basex.query.util.Err;
import org.basex.util.TokenBuilder;
import org.deepfs.fs.DeepFS;
public final class FNBaseX extends Fun {
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
switch(func) {
case INDEX: return index(ctx);
default: return super.iter(ctx);
}
}
@Override
public Item atomic(final QueryContext ctx) throws QueryException {
switch(func) {
case EVAL: return eval(ctx);
case READ: return read(ctx);
case RANDOM: return random();
case RUN: return run(ctx);
case DB: return db(ctx);
case FSPATH: return fspath(ctx);
default: return super.atomic(ctx);
}
}
@Override
public Expr c(final QueryContext ctx) throws QueryException {
return func == FunDef.DB && expr[0].i() &&
(expr.length == 1 || expr[1].i()) ? db(ctx) : this;
}
/**
* Performs the eval function.
* @param ctx query context
* @return iterator
* @throws QueryException query exception
*/
private Item eval(final QueryContext ctx) throws QueryException {
return eval(ctx, checkStr(expr[0], ctx));
}
/**
* Performs the query function.
* @param ctx query context
* @return iterator
* @throws QueryException query exception
*/
private Item run(final QueryContext ctx) throws QueryException {
final IO io = file(ctx);
try {
return eval(ctx, io.content());
} catch(final IOException ex) {
Main.debug(ex);
Err.or(NODOC, ex.getMessage());
return null;
}
}
/**
* Evaluates the specified string.
* @param ctx query context
* @param qu query string
* @return iterator
* @throws QueryException query exception
*/
private Item eval(final QueryContext ctx, final byte[] qu)
throws QueryException {
final QueryContext qt = new QueryContext(ctx.context);
qt.parse(string(qu));
qt.compile();
return qt.iter().finish();
}
/**
* Performs the read function.
* @param ctx query context
* @return iterator
* @throws QueryException query exception
*/
private Item read(final QueryContext ctx) throws QueryException {
final IO io = file(ctx);
try {
final XMLInput in = new XMLInput(io);
final int len = (int) in.length();
final TokenBuilder tb = new TokenBuilder(len);
while(in.pos() < len) tb.addUTF(in.next());
in.finish();
return Str.get(tb.finish());
} catch(final IOException ex) {
Main.debug(ex);
Err.or(NODOC, ex.getMessage());
return null;
}
}
/**
* Returns the filesystem path for this node.
* @param ctx query context
* @return filesystem path
* @throws QueryException query exception
*/
private Item fspath(final QueryContext ctx) throws QueryException {
final DBNode node = (DBNode) expr[0].atomic(ctx);
final DeepFS fs = ctx.data().fs;
return (node == null || fs == null) ? Str.ZERO :
Str.get(fs.path(node.pre, false));
}
/**
* Returns a file instance for the first argument.
* @param ctx query context
* @return io instance
* @throws QueryException query exception
*/
private IO file(final QueryContext ctx) throws QueryException {
final byte[] name = checkStr(expr[0], ctx);
final IO io = IO.get(string(name));
if(!ctx.context.user.perm(User.ADMIN) || !io.exists()) Err.or(DOCERR, name);
return io;
}
/**
* Performs the db function.
* @param ctx query context
* @return iterator
* @throws QueryException query exception
*/
private Item db(final QueryContext ctx) throws QueryException {
DBNode node = ctx.doc(checkStr(expr[0], ctx), false, true);
if(expr.length == 2) {
final Item it = expr[1].atomic(ctx);
if(it == null) Err.empty(expr[1]);
if(!it.u() && !it.n()) Err.num(info(), it);
final long pre = it.itr();
if(pre < 0 || pre >= node.data.meta.size) Err.or(NOPRE, pre);
node = new DBNode(node.data, (int) pre);
}
return node;
}
/**
* Performs the random function.
* @return iterator
*/
private Item random() {
return Dbl.get(Math.random());
}
/**
* Performs the contains lower case function.
* @param ctx query context
* @return iterator
* @throws QueryException query exception
*/
private Iter index(final QueryContext ctx) throws QueryException {
final Data data = ctx.data();
if(data == null) Err.or(XPNOCTX, this);
final IndexContext ic = new IndexContext(ctx, data, null, true);
final String type = string(checkStr(expr[1], ctx)).toLowerCase();
final byte[] word = checkStr(expr[0], ctx);
if(type.equals(FULLTEXT)) {
if(!data.meta.ftxindex) Err.or(NOIDX, FULLTEXT);
return new FTIndexAccess(new FTWords(
data, word, ctx.ftpos == null), ic).iter(ctx);
}
if(type.equals(TEXT)) {
if(!data.meta.txtindex) Err.or(NOIDX, TEXT);
return new IndexAccess(expr[0], Type.TXT, ic).iter(ctx);
}
if(type.equals(ATTRIBUTE)) {
if(!data.meta.atvindex) Err.or(NOIDX, ATTRIBUTE);
return new IndexAccess(expr[0], Type.ATV, ic).iter(ctx);
}
Err.or(WHICHIDX, type);
return null;
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.tools;
import jargs.gnu.CmdLineParser;
import org.apache.log4j.*;
import org.broad.igv.Globals;
import org.broad.igv.data.seg.SegmentedDataWriter;
import org.broad.igv.feature.GFFParser;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.sam.reader.AlignmentIndexer;
import org.broad.igv.tools.converters.ExpressionFormatter;
import org.broad.igv.tools.converters.GCTtoIGVConverter;
import org.broad.igv.tools.sort.Sorter;
import org.broad.igv.track.WindowFunction;
import org.broad.igv.feature.tribble.CodecFactory;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.FileUtils;
import org.broad.igv.util.ParsingUtils;
import org.broad.igv.vcf.VCFtoBed;
import org.broad.tribble.FeatureCodec;
import org.broad.tribble.TribbleException;
import org.broad.tribble.index.Index;
import org.broad.tribble.index.IndexFactory;
import org.broad.tribble.util.LittleEndianOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* Command line parser for "igvtools".
*
* @author jrobinso
*/
public class IgvTools {
static String version = "@VERSION";
static String[] commandDocs = new String[]{
"version print the version number",
"sort sort an alignment file by start position",
"index index an alignment file",
"tile convert an input file (cn, gct, wig) to tiled data format (tdf)",
"count compute coverage density for an alignment file"
};
static final int MAX_RECORDS_IN_RAM = 500000;
public static final int MAX_ZOOM = 7;
public static final int WINDOW_SIZE = 25;
public static final int EXT_FACTOR = 0;
public static final Object PROBE_FILE = null;
public static final int LINEAR_BIN_SIZE = 16000;
public static final int INTERVAL_SIZE = 1000;
public static final int LINEAR_INDEX = 1;
public static final int INTERVAL_INDEX = 2;
/**
* The general usage string
*/
static String usageString() {
StringBuffer buf = new StringBuffer();
buf.append("\nProgram: igvtools\n\n");
buf.append("Usage: igvtools [command] [options] [arguments]\n\n");
buf.append("Command:");
for (String c : commandDocs) {
buf.append(" " + c + "\n\t");
}
return buf.toString();
}
/**
* Main method. Used to run igvtools from the command line
*
* @param argv
* @throws IOException
* @throws PreprocessingException
*/
public static void main(String[] argv) throws IOException, PreprocessingException {
RollingFileAppender appender = new RollingFileAppender();
PatternLayout layout = new PatternLayout();
layout.setConversionPattern("%p [%d{ISO8601}] [%F:%L] %m%n");
appender.setName("R");
appender.setFile("igv.log");
appender.setThreshold(Level.ALL);
appender.setMaxFileSize("10KB");
appender.setMaxBackupIndex(1);
appender.setAppend(true);
appender.activateOptions();
appender.setLayout(layout);
Logger.getRootLogger().addAppender(appender);
Globals.setHeadless(true);
(new IgvTools()).run(argv);
}
private void parseArguments(String[] argv) {
}
private void run(String[] argv) {
CmdLineParser parser = new CmdLineParser();
CmdLineParser.Option helpOption = parser.addBooleanOption('h', "help");
CmdLineParser.Option guiOption = parser.addBooleanOption('g', "gui");
// general options
CmdLineParser.Option windowFunctions = parser.addStringOption('f', "windowFunctions");
CmdLineParser.Option tmpDirOption = parser.addStringOption('t', "tmpDir");
CmdLineParser.Option maxZoomOption = parser.addIntegerOption('z', "maxZoom");
CmdLineParser.Option compressOption = parser.addBooleanOption('c', "compressed");
// options for sort
CmdLineParser.Option maxRecordsOption = parser.addIntegerOption('m', "maxRecords");
// options for gct files
CmdLineParser.Option probeFileOption = parser.addStringOption('p', "probeFile");
// options for coverage
CmdLineParser.Option windowSizeOption = parser.addIntegerOption('w', "windowSize");
CmdLineParser.Option extFactorOption = parser.addIntegerOption('e', "extFactor");
// options for index
CmdLineParser.Option indexTypeOption = parser.addIntegerOption('i', "indexType");
CmdLineParser.Option binSizeOption = parser.addIntegerOption('b', "binSize");
CmdLineParser.Option outputDirOption = parser.addStringOption('o', "outputDir");
// options for gentest
//CmdLineParser.Option nRows = parser.addIntegerOption('r', "numRows");
CmdLineParser.Option strandOption = parser.addIntegerOption('s', "strand");
//CmdLineParser.Option unOrdered = parser.addBooleanOption('u', "unOrdered");
// options for coverage
CmdLineParser.Option coverageOptions = parser.addStringOption('x', "coverageOptions");
// Parse optional arguments (switches, etc)
try {
parser.parse(argv);
} catch (CmdLineParser.OptionException e) {
System.err.println(e.getMessage());
return;
}
boolean help = ((Boolean) parser.getOptionValue(helpOption, false));
if (argv.length < 1 || help) {
System.out.println(usageString());
return;
}
boolean gui = ((Boolean) parser.getOptionValue(guiOption, false));
if (gui) {
launchGUI();
Runtime.getRuntime().halt(0);
}
String tmpDirName = (String) parser.getOptionValue(tmpDirOption);
String[] nonOptionArgs = parser.getRemainingArgs();
try {
validateArgsLength(nonOptionArgs, 1);
// The command
String command = nonOptionArgs[EXT_FACTOR].toLowerCase();
// Do "version" now, its the only command with no arguments
if (command.equals("version")) {
System.out.println("Version " + version);
return;
}
// All remaining commands require an input file, and most need the file extension. Do that here.
validateArgsLength(nonOptionArgs, 2);
String ifile = nonOptionArgs[1];
boolean isList = ifile.indexOf(",") > 0;
if (!isList && !(new File(ifile)).exists()) {
throw new PreprocessingException("File not found: " + ifile);
}
int maxRecords = (Integer) parser.getOptionValue(maxRecordsOption, MAX_RECORDS_IN_RAM);
if (command.equals("count") || command.equals("pre") || command.equals("tile")) {
validateArgsLength(nonOptionArgs, 4);
int windowSizeValue = (Integer) parser.getOptionValue(windowSizeOption, WINDOW_SIZE);
int maxZoomValue = (Integer) parser.getOptionValue(maxZoomOption, MAX_ZOOM);
String ofile = nonOptionArgs[2];
String genomeId = nonOptionArgs[3];
boolean isGCT = Preprocessor.getExtension(ifile).endsWith("gct");
String wfsString = (String) parser.getOptionValue(windowFunctions);
Collection<WindowFunction> wfList = parseWFS(wfsString, isGCT);
String coverageOpt = (String) parser.getOptionValue(coverageOptions);
if (command.equals("count")) {
int extFactorValue = (Integer) parser.getOptionValue(extFactorOption, EXT_FACTOR);
int strandOptionValue = (Integer) parser.getOptionValue(strandOption, -1);
doCount(ifile, ofile, genomeId, maxZoomValue, wfList, windowSizeValue, extFactorValue,
strandOptionValue, coverageOpt);
} else {
String probeFile = (String) parser.getOptionValue(probeFileOption, PROBE_FILE);
doTile(ifile, ofile, probeFile, genomeId, maxZoomValue, wfList, tmpDirName, maxRecords);
}
} else if (command.toLowerCase().equals("sort")) {
validateArgsLength(nonOptionArgs, 3);
String ofile = nonOptionArgs[2];
doSort(ifile, ofile, tmpDirName, maxRecords);
} else if (command.equals("index")) {
int indexType = (Integer) parser.getOptionValue(indexTypeOption, LINEAR_INDEX);
int defaultBinSize = indexType == LINEAR_INDEX ? LINEAR_BIN_SIZE : INTERVAL_SIZE;
int binSize = (Integer) parser.getOptionValue(binSizeOption, defaultBinSize);
String outputDir = (String) parser.getOptionValue(outputDirOption, null);
doIndex(ifile, outputDir, indexType, binSize);
} else if (command.equals("seg")) {
doPreprocessSeg(argv);
} else if (command.equals("wibtowig")) {
validateArgsLength(nonOptionArgs, 4);
File txtFile = new File(nonOptionArgs[1]);
File wibFile = new File(nonOptionArgs[2]);
File wigFile = new File(nonOptionArgs[3]);
String trackLine = nonOptionArgs.length > 4 ? nonOptionArgs[4] : null;
doWIBtoWIG(txtFile, wibFile, wigFile, trackLine);
} else if (command.equals("splitgff")) {
validateArgsLength(nonOptionArgs, 3);
String outputDirectory = nonOptionArgs[2];
GFFParser.splitFileByType(ifile, outputDirectory);
//} else if (command.equals("gentest")) {
// validateArgsLength(nonOptionArgs, 2);
// int nRowsValue = (Integer) parser.getOptionValue(nRows, 10);
// boolean sorted = !((Boolean) parser.getOptionValue(unOrdered, false));
// int strandOptionValue = (Integer) parser.getOptionValue(strandOption, -1);
// String ofile = ifile;
// TestFileGenerator.generateTestFile(ofile, sorted, nRowsValue, strandOptionValue);
} else if (command.toLowerCase().equals("gcttoigv")) {
validateArgsLength(nonOptionArgs, 4);
String ofile = nonOptionArgs[2];
// Output files must have .igv extension
if (!ofile.endsWith(".igv")) {
ofile = ofile + ".igv";
}
String genomeId = nonOptionArgs[3];
String probeFile = (String) parser.getOptionValue(probeFileOption, PROBE_FILE);
doGCTtoIGV(ifile, new File(ofile), probeFile, genomeId, maxRecords, tmpDirName);
} else if (command.equals("formatexp")) {
validateArgsLength(nonOptionArgs, 3);
File inputFile = new File(nonOptionArgs[1]);
File outputFile = new File(nonOptionArgs[2]);
(new ExpressionFormatter()).convert(inputFile, outputFile);
} else if (command.equals("wigtobed")) {
validateArgsLength(nonOptionArgs, 2);
String inputFile = nonOptionArgs[1];
float hetThreshold = 0.17f;
if (nonOptionArgs.length > 2) {
hetThreshold = Float.parseFloat(nonOptionArgs[2]);
}
float homThreshold = 0.55f;
if (nonOptionArgs.length > 3) {
homThreshold = Float.parseFloat(nonOptionArgs[3]);
}
WigToBed.run(inputFile, hetThreshold, homThreshold);
} else if (command.equals("vcftobed")) {
validateArgsLength(nonOptionArgs, 3);
String inputFile = nonOptionArgs[1];
String outputFile = nonOptionArgs[2];
VCFtoBed.convert(inputFile, outputFile);
} else if (command.equals("lanecounter")) {
validateArgsLength(nonOptionArgs, 3);
Genome genome = loadGenome(nonOptionArgs[1]);
String bamFileList = nonOptionArgs[2];
String queryInterval = nonOptionArgs[3];
LaneCounter.run(genome, bamFileList, queryInterval);
} else if (command.equals("sumwigs")) {
sumWigs(nonOptionArgs[1], nonOptionArgs[2]);
} else {
throw new PreprocessingException("Unknown command: " + argv[EXT_FACTOR]);
}
} catch (PreprocessingException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
throw new PreprocessingException("Unexpected IO error: ", e);
}
}
private void sumWigs(String inputString, String outputString) throws IOException {
String[] tokens = inputString.split(",");
List<File> in = new ArrayList();
for (String f : tokens) {
in.add(new File(f));
}
File out = new File(outputString);
WigSummer.sumWigs(in, out);
}
private void doGCTtoIGV(String ifile, File ofile, String probefile, String genomeId, int maxRecords, String tmpDirName) throws IOException {
Genome genome = loadGenome(genomeId);
if (genome == null) {
throw new PreprocessingException("Genome could not be loaded: " + genomeId);
}
File tmpDir = null;
if (tmpDirName != null && tmpDirName.trim().length() > 0) {
tmpDir = new File(tmpDirName);
if (!tmpDir.exists()) {
System.err.println("Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
throw new PreprocessingException("Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
}
}
GCTtoIGVConverter.convert(new File(ifile), ofile, probefile, genomeId, maxRecords, tmpDir);
}
public void doTile(String ifile, String ofile, String probeFile, String genomeId, int maxZoomValue,
Collection<WindowFunction> windowFunctions) throws IOException, PreprocessingException {
doTile(ifile, ofile, probeFile, genomeId, maxZoomValue, windowFunctions, null, MAX_RECORDS_IN_RAM);
}
public void doTile(String ifile, String ofile, String probeFile, String genomeId, int maxZoomValue,
Collection<WindowFunction> windowFunctions, String tmpDirName, int maxRecords) throws IOException, PreprocessingException {
validateIsTilable(ifile);
System.out.println("Tile. File = " + ifile);
System.out.println("Max zoom = " + maxZoomValue);
if (probeFile != null && probeFile.trim().length() > 0) {
System.out.println("Probe file = " + probeFile);
}
System.out.print("Window functions: ");
for (WindowFunction wf : windowFunctions) {
System.out.print(wf.toString() + " ");
}
System.out.println();
Genome genome = loadGenome(genomeId);
if (genome == null) {
throw new PreprocessingException("Genome could not be loaded: " + genomeId);
}
File tmp = new File(ifile);
int nLines = tmp.isDirectory() ? ParsingUtils.estimateLineCount(tmp) : ParsingUtils.estimateLineCount(ifile);
// Convert gct files to igv format first
if (isGCT(ifile)) {
File tmpDir = null;
if (tmpDirName != null && tmpDirName.length() > 0) {
tmpDir = new File(tmpDirName);
if (!tmpDir.exists() || !tmpDir.isDirectory()) {
throw new PreprocessingException("Specified tmp directory does not exist or is not directory: " + tmpDirName);
}
} else {
tmpDir = new File(System.getProperty("java.io.tmpdir"), System.getProperty("user.name"));
}
if (!tmpDir.exists()) {
tmpDir.mkdir();
}
String baseName = (new File(ifile)).getName();
File igvFile = new File(tmpDir, baseName + ".igv");
igvFile.deleteOnExit();
doGCTtoIGV(ifile, igvFile, probeFile, genomeId, maxRecords, tmpDirName);
tmp = igvFile;
}
Preprocessor p = new Preprocessor(new File(ofile), genome, windowFunctions, nLines, null);
if (tmp.isDirectory()) {
for (File f : tmp.listFiles()) {
p.preprocess(f, probeFile, maxZoomValue);
}
} else {
p.preprocess(tmp, probeFile, maxZoomValue);
}
p.finish();
System.out.flush();
}
private boolean isGCT(String iFile) {
String tmp = iFile;
if (tmp.endsWith(".txt")) tmp = tmp.substring(0, tmp.length() - 4);
if (tmp.endsWith(".gz")) tmp = tmp.substring(0, tmp.length() - 3);
return tmp.endsWith(".gct") || tmp.endsWith(".tab");
}
/**
* Compute coverage or density of an alignment or feature file.
*
* @param ifile Alignement or feature file
* @param ofile Output file
* @param genomeId Genome id (e.g. hg18) or full path to a .genome file (e.g. /xchip/igv/scer2.genome)
* @param maxZoomValue Maximum zoom level to precompute. Default value is 7
* @param windowFunctions
* @param windowSizeValue
* @param extFactorValue
* @param strandOption
* @throws IOException
*/
public void doCount(String ifile, String ofile, String genomeId, int maxZoomValue,
Collection<WindowFunction> windowFunctions,
int windowSizeValue, int extFactorValue, int strandOption,
String coverageOpt) throws IOException {
System.out.println("Computing coverage. File = " + ifile);
System.out.println("Max zoom = " + maxZoomValue);
System.out.println("Window size = " + windowSizeValue);
System.out.print("Window functions: ");
for (WindowFunction wf : windowFunctions) {
System.out.print(wf.toString() + " ");
}
System.out.println();
System.out.println("Ext factor = " + extFactorValue);
Genome genome = loadGenome(genomeId);
if (genome == null) {
throw new PreprocessingException("Genome could not be loaded: " + genomeId);
}
// Multiple files allowed for count command (a tdf and a wig)
File tdfFile = null;
File wigFile = null;
String[] files = ofile.split(",");
if (files[0].endsWith("wig")) {
wigFile = new File(files[0]);
} else {
tdfFile = new File(files[0]);
}
if (files.length > 1) {
if (files[1].endsWith("wig")) {
wigFile = new File(files[1]);
} else if (files[1].endsWith("tdf")) {
tdfFile = new File(files[1]);
}
}
if (tdfFile != null && !tdfFile.getName().endsWith(".tdf")) {
tdfFile = new File(tdfFile.getAbsolutePath() + ".tdf");
}
Preprocessor p = new Preprocessor(tdfFile, genome, windowFunctions, -1, null);
p.count(ifile, windowSizeValue, extFactorValue, maxZoomValue, wigFile, strandOption, coverageOpt);
p.finish();
System.out.flush();
}
public void doWIBtoWIG(File txtFile, File wibFile, File wigFile, String trackLine) {
UCSCUtils.convertWIBFile(txtFile, wibFile, wigFile, trackLine);
}
/**
* @param argv
* @deprecated Convert a .seg file to a .seg.zip file
*/
public void doPreprocessSeg(String[] argv) {
int nArgs = argv.length - 1;
String[] args = new String[nArgs];
System.arraycopy(argv, 1, args, EXT_FACTOR, nArgs);
SegmentedDataWriter.main(args);
}
/**
* Create an index for an alignment or feature file
*
* @param ifile
* @throws IOException
*/
public void doIndex(String ifile, int indexType, int binSize) throws IOException {
doIndex(ifile, null, indexType, binSize);
}
public void doIndex(String ifile, String outputFileName, int indexType, int binSize) throws IOException {
if (ifile.endsWith(".gz")) {
System.out.println("Cannot index a gzipped file");
throw new PreprocessingException("Cannot index a gzipped file");
}
if (outputFileName == null) {
outputFileName = ifile;
}
if (ifile.endsWith(".bed") || ifile.endsWith(".vcf") || ifile.endsWith(".vcf4") || ifile.endsWith(".gff") ||
ifile.endsWith(".gff3") || ifile.endsWith(".psl") || ifile.endsWith(".pslx")) {
if (!outputFileName.endsWith(".idx")) {
outputFileName = outputFileName + ".idx";
}
try {
createTribbleIndex(ifile, new File(outputFileName), indexType, binSize);
} catch (TribbleException.MalformedFeatureFile e) {
StringBuffer buf = new StringBuffer();
buf.append("<html>Files must be sorted by start position prior to indexing.<br>");
buf.append(e.getMessage());
buf.append("<br><br>Note: igvtools can be used to sort the file, select \"File > Run igvtools...\".");
MessageUtils.showMessage(buf.toString());
}
} else {
if (!outputFileName.endsWith(".sai")) {
outputFileName = outputFileName + ".sai";
}
AlignmentIndexer indexer = AlignmentIndexer.getInstance(new File(ifile), null, null);
indexer.createSamIndex(new File(outputFileName));
}
System.out.flush();
}
/**
* Create a tribble style index.
*
* @param ifile
* @param outputFile
* @param indexType
* @param binSize
* @throws IOException
*/
private void createTribbleIndex(String ifile, File outputFile, int indexType, int binSize) throws IOException {
FeatureCodec codec = CodecFactory.getCodec(ifile);
File inputFile = new File(ifile);
Index idx = null;
if (indexType == LINEAR_INDEX) {
idx = IndexFactory.createLinearIndex(inputFile, codec, binSize);
} else {
idx = IndexFactory.createIntervalIndex(inputFile, codec, binSize);
}
if (idx != null) {
String idxFile;
if (outputFile != null) {
idxFile = outputFile.getAbsolutePath();
} else {
idxFile = ifile = ".idx";
}
LittleEndianOutputStream stream = null;
try {
stream = new LittleEndianOutputStream(new BufferedOutputStream(new FileOutputStream(idxFile)));
idx.write(stream);
}
finally {
if (stream != null) {
stream.close();
}
}
}
}
public void doSort(String ifile, String ofile, String tmpDirName, int maxRecords) {
System.out.println("Sorting " + ifile + " -> " + ofile);
File inputFile = new File(ifile);
File outputFile = new File(ofile);
Sorter sorter = Sorter.getSorter(inputFile, outputFile);
if (tmpDirName != null && tmpDirName.trim().length() > 0) {
File tmpDir = new File(tmpDirName);
if (!tmpDir.exists()) {
System.err.println("Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
throw new PreprocessingException("Error: tmp directory: " + tmpDir.getAbsolutePath() + " does not exist.");
}
sorter.setTmpDir(tmpDir);
}
sorter.setMaxRecords(maxRecords);
sorter.run();
System.out.println("Done");
System.out.flush();
}
private void validateArgsLength(String[] nonOptionArgs, int len) throws PreprocessingException {
if (nonOptionArgs.length < len) {
throw new PreprocessingException(usageString());
}
}
public static Genome loadGenome(String genomeFileOrID) {
String rootDir = FileUtils.getInstallDirectory();
final GenomeManager genomeManager = new GenomeManager();
Genome genome = genomeManager.getGenome(genomeFileOrID);
if (genome != null) {
return genome;
}
File genomeFile = new File(rootDir, "genomes" + File.separator + genomeFileOrID + ".genome");
if (!genomeFile.exists()) {
genomeFile = new File(rootDir, "genomes" + File.separator + genomeFileOrID);
}
if (!genomeFile.exists()) {
genomeFile = new File(genomeFileOrID);
}
if (!genomeFile.exists()) {
throw new PreprocessingException("Genome definition file not found for: " + genomeFileOrID);
}
GenomeManager.GenomeListItem item = genomeManager.loadGenomeFromLocalFile(genomeFile);
String genomeId = item.getId();
if (genomeId == null) {
throw new PreprocessingException("Error loading: " + genomeFileOrID);
}
genomeManager.setGenomeId(genomeId);
genome = genomeManager.getGenome(genomeId);
return genome;
}
/**
* Test if the file type can be "tiled".
*/
private static void validateIsTilable(String ifile) {
File tmp = new File(ifile);
if (tmp.isDirectory()) {
File[] files = tmp.listFiles();
if (files.length == EXT_FACTOR) {
throw new PreprocessingException("Tile command not supported for empty directory: " + ifile);
}
ifile = files[EXT_FACTOR].getName();
}
String ext = Preprocessor.getExtension(ifile);
if (!(ext.equals(".cn") ||
ext.equals(".igv") ||
ext.equals(".wig") ||
ifile.toLowerCase().endsWith("cpg.txt") ||
ext.equals(".ewig") ||
ext.equals(".cn") ||
ext.equals(".snp") ||
ext.equals(".xcn") ||
ext.equals(".gct") ||
ext.equals(".bedgraph") ||
Preprocessor.isAlignmentFile(ext))) {
throw new PreprocessingException("Tile command not supported for files of type: " + ext);
}
}
/**
* Parse the window functions line.
*
* @param string comma delimited string of window functions, e.g. min, p10, max
* @return colleciton of WindowFunctions objects
*/
private static Collection<WindowFunction> parseWFS(String string, boolean isGCT) {
if (string == null || string.length() == EXT_FACTOR) {
return isGCT ? Arrays.asList(WindowFunction.min, WindowFunction.mean, WindowFunction.max) :
Arrays.asList(WindowFunction.mean);
} else {
String[] tokens = string.split(",");
List<WindowFunction> funcs = new ArrayList(tokens.length);
for (int i = EXT_FACTOR; i < tokens.length; i++) {
String wf = tokens[i];
if (wf.startsWith("p")) {
wf = wf.replaceFirst("p", "percentile");
}
try {
funcs.add(WindowFunction.valueOf(wf));
} catch (Exception e) {
System.err.println("Unrecognized window function: " + tokens[i]);
}
}
return funcs;
}
}
private static void launchGUI() {
IgvToolsGui.main(null);
}
}
|
package org.broad.igv.util;
import biz.source_code.base64Coder.Base64Coder;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.HttpDate;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.exceptions.HttpResponseException;
import org.broad.igv.gs.GSUtils;
import org.broad.igv.ui.IGV;
import org.broad.igv.util.stream.IGVUrlHelper;
import org.broad.tribble.util.SeekableHTTPStream;
import org.broad.tribble.util.ftp.FTPClient;
import org.broad.tribble.util.ftp.FTPStream;
import org.broad.tribble.util.ftp.FTPUtils;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
/**
* Wrapper utility class... for interacting with HttpURLConnection.
*
* @author Jim Robinson
* @date 9/22/11
*/
public class HttpUtils {
private static Logger log = Logger.getLogger(HttpUtils.class);
private static HttpUtils instance;
private Map<String, Boolean> byteRangeTestMap;
private ProxySettings proxySettings = null;
private final int MAX_REDIRECTS = 5;
private String defaultUserName = null;
private char[] defaultPassword = null;
private static Pattern URLmatcher = Pattern.compile(".{1,8}:
/**
* @return the single instance
*/
public static HttpUtils getInstance() {
if (instance == null) {
instance = new HttpUtils();
}
return instance;
}
/**
* Constructor
*/
private HttpUtils() {
org.broad.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class);
disableCertificateValidation();
CookieHandler.setDefault(new IGVCookieManager());
Authenticator.setDefault(new IGVAuthenticator());
byteRangeTestMap = Collections.synchronizedMap(new HashMap());
}
public static boolean isRemoteURL(String string) {
String lcString = string.toLowerCase();
return lcString.startsWith("http:
}
/**
* Join the {@code elements} with the character {@code joiner},
* URLencoding the {@code elements} along the way. {@code joiner}
* is NOT URLEncoded
* Example:
* String[] parm_list = new String[]{"app les", "oranges", "bananas"};
* String formatted = buildURLString(Arrays.asList(parm_list), "+");
* <p/>
* formatted will be "app%20les+oranges+bananas"
*
* @param elements
* @param joiner
* @return
*/
public static String buildURLString(Iterable<String> elements, String joiner) {
Iterator<String> iter = elements.iterator();
if (!iter.hasNext()) {
return "";
}
String wholequery = iter.next();
try {
while (iter.hasNext()) {
wholequery += joiner + URLEncoder.encode(iter.next(), "UTF-8");
}
return wholequery;
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Bad argument in genelist: " + e.getMessage());
}
}
/**
* Return the contents of the url as a String. This method should only be used for queries expected to return
* a small amount of data.
*
* @param url
* @return
* @throws IOException
*/
public String getContentsAsString(URL url) throws IOException {
InputStream is = null;
HttpURLConnection conn = openConnection(url, null);
try {
is = conn.getInputStream();
return readContents(is);
} finally {
if (is != null) is.close();
}
}
public String getContentsAsJSON(URL url) throws IOException {
InputStream is = null;
Map<String, String> reqProperties = new HashMap();
reqProperties.put("Accept", "application/json,text/plain");
HttpURLConnection conn = openConnection(url, reqProperties);
try {
is = conn.getInputStream();
return readContents(is);
} finally {
if (is != null) is.close();
}
}
/**
* Open a connection stream for the URL.
*
* @param url
* @return
* @throws IOException
*/
public InputStream openConnectionStream(URL url) throws IOException {
if (url.getProtocol().toLowerCase().equals("ftp")) {
String userInfo = url.getUserInfo();
String host = url.getHost();
String file = url.getPath();
FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl());
ftp.pasv();
ftp.retr(file);
return new FTPStream(ftp);
} else {
return openConnectionStream(url, null);
}
}
public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException {
HttpURLConnection conn = openConnection(url, requestProperties);
if (conn == null)
return null;
InputStream input = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
input = new GZIPInputStream(input);
}
return input;
}
public boolean resourceAvailable(URL url) {
if (url.getProtocol().toLowerCase().equals("ftp")) {
return FTPUtils.resourceAvailable(url);
}
try {
HttpURLConnection conn = openConnection(url, null, "HEAD");
int code = conn.getResponseCode();
return code == 200;
} catch (IOException e) {
return false;
}
}
public String getHeaderField(URL url, String key) throws IOException {
HttpURLConnection conn = openConnection(url, null, "HEAD");
if (conn == null) return null;
return conn.getHeaderField(key);
}
public long getContentLength(URL url) throws IOException {
String contentLengthString = getHeaderField(url, "Content-Length");
if (contentLengthString == null) {
return -1;
} else {
return Long.parseLong(contentLengthString);
}
}
/**
* Compare a local and remote resource.
*
* @param file
* @param url
* @return true if the files are "the same", false if the remote file has been modified wrt the local one.
* @throws IOException
*/
public boolean compareResources(File file, URL url) throws IOException {
if (!file.exists()) {
return false;
}
HttpURLConnection conn = openConnection(url, null, "HEAD");
// Check content-length first
long contentLength = -1;
String contentLengthString = conn.getHeaderField("Content-Length");
if (contentLengthString != null) {
try {
contentLength = Long.parseLong(contentLengthString);
} catch (NumberFormatException e) {
log.error("Error parsing content-length string: " + contentLengthString + " from URL: "
+ url.toString());
contentLength = -1;
}
}
if (contentLength != file.length()) {
return false;
}
// Compare last-modified dates
String lastModifiedString = conn.getHeaderField("Last-Modified");
if (lastModifiedString == null) {
return false;
} else {
HttpDate date = new HttpDate();
date.parse(lastModifiedString);
long remoteModifiedTime = date.getTime();
long localModifiedTime = file.lastModified();
return remoteModifiedTime <= localModifiedTime;
}
}
public void updateProxySettings() {
boolean useProxy;
String proxyHost;
int proxyPort = -1;
boolean auth = false;
String user = null;
String pw = null;
PreferenceManager prefMgr = PreferenceManager.getInstance();
useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY);
proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null);
try {
proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1"));
} catch (NumberFormatException e) {
proxyPort = -1;
}
auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE);
user = prefMgr.get(PreferenceManager.PROXY_USER, null);
String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null);
if (pwString != null) {
pw = Utilities.base64Decode(pwString);
}
String proxyTypeString = prefMgr.get(PreferenceManager.PROXY_TYPE, "HTTP");
Proxy.Type type = proxyTypeString.equals("SOCKS") ? Proxy.Type.SOCKS : Proxy.Type.HTTP;
proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort, type);
}
public boolean downloadFile(String url, File outputFile) throws IOException {
log.info("Downloading " + url + " to " + outputFile.getAbsolutePath());
HttpURLConnection conn = openConnection(new URL(url), null);
long contentLength = -1;
String contentLengthString = conn.getHeaderField("Content-Length");
if (contentLengthString != null) {
contentLength = Long.parseLong(contentLengthString);
}
log.info("Content length = " + contentLength);
InputStream is = null;
OutputStream out = null;
try {
is = conn.getInputStream();
out = new FileOutputStream(outputFile);
byte[] buf = new byte[64 * 1024];
int downloaded = 0;
int bytesRead = 0;
while ((bytesRead = is.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
downloaded += bytesRead;
}
log.info("Download complete. Total bytes downloaded = " + downloaded);
} finally {
if (is != null) is.close();
if (out != null) {
out.flush();
out.close();
}
}
long fileLength = outputFile.length();
return contentLength <= 0 || contentLength == fileLength;
}
public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException {
HttpURLConnection urlconnection = null;
OutputStream bos = null;
URL url = new URL(uri);
urlconnection = openConnection(url, headers, "PUT");
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
bos = new BufferedOutputStream(urlconnection.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) > 0) {
bos.write(i);
}
bos.close();
int responseCode = urlconnection.getResponseCode();
// Error messages below.
if (responseCode >= 400) {
String message = readErrorStream(urlconnection);
throw new IOException("Error uploading " + file.getName() + " : " + message);
}
}
public String createGenomeSpaceDirectory(URL url, String body) throws IOException {
HttpURLConnection urlconnection = null;
OutputStream bos = null;
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Content-Length", String.valueOf(body.getBytes().length));
urlconnection = openConnection(url, headers, "PUT");
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
bos = new BufferedOutputStream(urlconnection.getOutputStream());
bos.write(body.getBytes());
bos.close();
int responseCode = urlconnection.getResponseCode();
// Error messages below.
StringBuffer buf = new StringBuffer();
InputStream inputStream;
if (responseCode >= 200 && responseCode < 300) {
inputStream = urlconnection.getInputStream();
} else {
inputStream = urlconnection.getErrorStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = br.readLine()) != null) {
buf.append(nextLine);
buf.append('\n');
}
inputStream.close();
if (responseCode >= 200 && responseCode < 300) {
return buf.toString();
} else {
throw new IOException("Error creating GS directory: " + buf.toString());
}
}
/**
* Code for disabling SSL certification
*/
private void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException e) {
} catch (KeyManagementException e) {
}
}
private String readContents(InputStream is) throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
while ((b = bis.read()) >= 0) {
bos.write(b);
}
return new String(bos.toByteArray());
}
private String readErrorStream(HttpURLConnection connection) throws IOException {
InputStream inputStream = null;
try {
inputStream = connection.getErrorStream();
if (inputStream == null) {
return null;
}
return readContents(inputStream);
} finally {
if (inputStream != null) inputStream.close();
}
}
private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException {
return openConnection(url, requestProperties, "GET");
}
private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException {
return openConnection(url, requestProperties, method, 0);
}
/**
* The "real" connection method
*
* @param url
* @param requestProperties
* @param method
* @return
* @throws java.io.IOException
*/
private HttpURLConnection openConnection(
URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException {
boolean useProxy = proxySettings != null && proxySettings.useProxy && proxySettings.proxyHost != null &&
proxySettings.proxyPort > 0;
HttpURLConnection conn;
if (useProxy) {
Proxy proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort));
conn = (HttpURLConnection) url.openConnection(proxy);
if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) {
byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes();
String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes));
conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
}
} else {
conn = (HttpURLConnection) url.openConnection();
}
if (GSUtils.isGenomeSpace(url)) {
String token = GSUtils.getGSToken();
if (token != null) conn.setRequestProperty("Cookie", "gs-token=" + token);
conn.setRequestProperty("Accept", "application/json,text/plain");
}
else {
conn.setRequestProperty("Accept", "text/plain");
}
conn.setUseCaches(false);
conn.setConnectTimeout(Globals.CONNECT_TIMEOUT);
conn.setReadTimeout(Globals.READ_TIMEOUT);
conn.setRequestMethod(method);
conn.setRequestProperty("Connection", "Keep-Alive");
if (requestProperties != null) {
for (Map.Entry<String, String> prop : requestProperties.entrySet()) {
conn.setRequestProperty(prop.getKey(), prop.getValue());
}
}
conn.setRequestProperty("User-Agent", Globals.applicationString());
if (method.equals("PUT")) {
return conn;
} else {
int code = conn.getResponseCode();
// Redirects. These can occur even if followRedirects == true if there is a change in protocol,
// for example http -> https.
if (code >= 300 && code < 400) {
if (redirectCount > MAX_REDIRECTS) {
throw new IOException("Too many redirects");
}
String newLocation = conn.getHeaderField("Location");
log.debug("Redirecting to " + newLocation);
return openConnection(new URL(newLocation), requestProperties, method, redirectCount++);
}
// TODO -- handle other response codes.
else if (code >= 400) {
String message;
if (code == 404) {
message = "File not found: " + url.toString();
throw new FileNotFoundException(message);
}
else if (code == 401) {
// Looks like this only happens when user hits "Cancel".
// message = "Not authorized to view this file";
// JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE);
redirectCount = MAX_REDIRECTS + 1;
return null;
}
else {
message = conn.getResponseMessage();
}
String details = readErrorStream(conn);
log.debug("error stream: " + details);
log.debug(message);
HttpResponseException exc = new HttpResponseException(code);
throw exc;
}
}
return conn;
}
public void setDefaultPassword(String defaultPassword) {
this.defaultPassword = defaultPassword.toCharArray();
}
public void setDefaultUserName(String defaultUserName) {
this.defaultUserName = defaultUserName;
}
public void clearDefaultCredentials() {
this.defaultPassword = null;
this.defaultUserName = null;
}
/**
* Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header.
* This is not a test of the server, but the client. In some environments the byte-range header gets removed
* by filters after the request is made by IGV.
*
* @return
*/
public boolean useByteRange(URL url) {
// We can test byte-range success for hosts we can reach.
final String host = url.getHost();
if (byteRangeTestMap.containsKey(host)) {
return byteRangeTestMap.get(host);
} else {
try {
boolean byteRangeTestSuccess = true;
if (host.contains("broadinstitute.org")) {
byteRangeTestSuccess = testBroadHost(host);
} else {
// Generic URL
byte[] firstBytes = getFirstBytes(url, 10000);
if (firstBytes.length > 1000) {
int end = firstBytes.length;
int start = end - 100;
SeekableHTTPStream str = new SeekableHTTPStream(new IGVUrlHelper(url));
str.seek(start);
int len = end - start;
byte[] buffer = new byte[len];
int n = 0;
while (n < len) {
int count = str.read(buffer, n, len - n);
if (count < 0)
throw new EOFException();
n += count;
}
for (int i = 0; i < len; i++) {
if (buffer[i] != firstBytes[i + start]) {
byteRangeTestSuccess = false;
}
}
} else {
// Too small a sample to test, return "true" but don't record this host as tested.
return true;
}
}
if (byteRangeTestSuccess) {
log.info("Range-byte request succeeded");
} else {
log.info("Range-byte test failed -- problem with client network environment.");
}
byteRangeTestMap.put(host, byteRangeTestSuccess);
return byteRangeTestSuccess;
} catch (IOException e) {
log.error("Error while testing byte range " + e.getMessage());
// We could not reach the test server, so we can't know if this client can do byte-range tests or
// not. Take the "optimistic" view.
return true;
}
}
}
private boolean testBroadHost(String host) throws IOException {
// Test broad urls for successful byte range requests.
log.info("Testing range-byte request on host: " + host);
String testURL;
if (host.endsWith("www.broadinstitute.org")) {
testURL = "http:
} else {
testURL = "http://igvdata.broadinstitute.org/genomes/seq/hg19/chr12.txt";
}
byte[] expectedBytes = {'T', 'C', 'G', 'C', 'T', 'T', 'G', 'A', 'A', 'C', 'C', 'C', 'G', 'G',
'G', 'A', 'G', 'A', 'G', 'G'};
SeekableHTTPStream str = new SeekableHTTPStream(new IGVUrlHelper(new URL(testURL)));
str.seek(25350000);
byte[] buffer = new byte[80000];
str.read(buffer);
for (int i = 0; i < expectedBytes.length; i++) {
if (buffer[i] != expectedBytes[i]) {
return false;
}
}
return true;
}
/**
* Return the first bytes of content from the URL. The number of bytes returned is ~ nominalLength.
*
* @param url
* @param nominalLength
* @return
* @throws IOException
*/
private byte[] getFirstBytes(URL url, int nominalLength) throws IOException {
InputStream is = null;
try {
is = url.openStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
while ((b = bis.read()) >= 0) {
bos.write(b);
if (bos.size() >= nominalLength) {
break;
}
}
return bos.toByteArray();
} finally {
if (is != null) is.close();
}
}
public void shutdown() {
// Do any cleanup required here
}
/**
* Checks if the string is a URL (not necessarily remote, can be any protocol)
*
* @param f
* @return
*/
public static boolean isURL(String f) {
return f.startsWith("http:") || f.startsWith("ftp:") || f.startsWith("https:") || URLmatcher.matcher(f).matches();
}
public static class ProxySettings {
boolean auth = false;
String user;
String pw;
boolean useProxy;
String proxyHost;
int proxyPort = -1;
Proxy.Type type;
public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) {
this(useProxy, user, pw, auth, proxyHost, proxyPort, Proxy.Type.HTTP);
this.auth = auth;
}
public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort, Proxy.Type proxyType) {
this.auth = auth;
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.pw = pw;
this.useProxy = useProxy;
this.user = user;
this.type = proxyType;
}
}
/**
* The default authenticator
*/
public class IGVAuthenticator extends Authenticator {
Hashtable<String, PasswordAuthentication> pwCache = new Hashtable<String, PasswordAuthentication>();
HashSet<String> cacheAttempts = new HashSet<String>();
/**
* Called when password authentication is needed.
*
* @return
*/
@Override
protected synchronized PasswordAuthentication getPasswordAuthentication() {
RequestorType type = getRequestorType();
String urlString = getRequestingURL().toString();
boolean isProxyChallenge = type == RequestorType.PROXY;
// Cache user entered PWs. In normal use this shouldn't be necessary as credentials are cached upstream,
// but if loading many files in parallel (e.g. from sessions) calls to this method can queue up before the
// user enters their credentials, causing needless reentry.
String pKey = type.toString() + getRequestingProtocol() + getRequestingHost();
PasswordAuthentication pw = pwCache.get(pKey);
if (pw != null) {
// Prevents infinite loop if credentials are incorrect
if (cacheAttempts.contains(urlString)) {
cacheAttempts.remove(urlString);
} else {
cacheAttempts.add(urlString);
return pw;
}
}
if (isProxyChallenge) {
if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) {
return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray());
}
}
if (defaultUserName != null && defaultPassword != null) {
return new PasswordAuthentication(defaultUserName, defaultPassword);
}
Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null;
boolean isGenomeSpace = GSUtils.isGenomeSpace(getRequestingURL());
if (isGenomeSpace) {
// If we are being challenged by GS the token must be bad/expired
GSUtils.logout();
}
LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, urlString, isProxyChallenge);
dlg.setVisible(true);
if (dlg.isCanceled()) {
return null;
} else {
final String userString = dlg.getUsername();
final char[] userPass = dlg.getPassword();
if (isProxyChallenge) {
proxySettings.user = userString;
proxySettings.pw = new String(userPass);
}
pw = new PasswordAuthentication(userString, userPass);
pwCache.put(pKey, pw);
return pw;
}
}
}
/**
* Provide override for unit tests
*/
public void setAuthenticator(Authenticator authenticator) {
Authenticator.setDefault(authenticator);
}
/**
* For unit tests
*/
public void resetAuthenticator() {
Authenticator.setDefault(new IGVAuthenticator());
}
/**
* Extension of CookieManager that grabs cookies from the GenomeSpace identity server to store locally.
* This is to support the GenomeSpace "single sign-on". Examples ...
* gs-username=igvtest; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/
* gs-token=HnR9rBShNO4dTXk8cKXVJT98Oe0jWVY+; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/
*/
static class IGVCookieManager extends CookieManager {
@Override
public void put(URI uri, Map<String, List<String>> stringListMap) throws IOException {
if (uri.toString().startsWith(PreferenceManager.getInstance().get(PreferenceManager.GENOME_SPACE_IDENTITY_SERVER))) {
List<String> cookies = stringListMap.get("Set-Cookie");
if (cookies != null) {
for (String cstring : cookies) {
String[] tokens = Globals.equalPattern.split(cstring);
if (tokens.length >= 2) {
String cookieName = tokens[0];
String[] vTokens = Globals.semicolonPattern.split(tokens[1]);
String value = vTokens[0];
if (cookieName.equals("gs-token")) {
GSUtils.setGSToken(value);
} else if (cookieName.equals("gs-username")) {
GSUtils.setGSUser(value);
}
}
}
}
}
super.put(uri, stringListMap);
}
}
}
|
package org.broad.igv.util;
import biz.source_code.base64Coder.Base64Coder;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.ftp.FTPClient;
import htsjdk.samtools.util.ftp.FTPStream;
import org.apache.log4j.Logger;
import org.apache.tomcat.util.HttpDate;
import org.broad.igv.Globals;
import org.broad.igv.PreferenceManager;
import org.broad.igv.exceptions.HttpResponseException;
import org.broad.igv.gs.GSUtils;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.CancellableProgressDialog;
import org.broad.igv.ui.util.ProgressMonitor;
import org.broad.igv.util.collections.CI;
import org.broad.igv.util.ftp.FTPUtils;
import org.broad.igv.util.stream.IGVSeekableHTTPStream;
import org.broad.igv.util.stream.IGVUrlHelper;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.List;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
/**
* Wrapper utility class... for interacting with HttpURLConnection.
*
* @author Jim Robinson
* @date 9/22/11
*/
public class HttpUtils {
private static Logger log = Logger.getLogger(HttpUtils.class);
private static HttpUtils instance;
private Map<String, Boolean> byteRangeTestMap;
private ProxySettings proxySettings = null;
private final int MAX_REDIRECTS = 5;
private String defaultUserName = null;
private char[] defaultPassword = null;
private static Pattern URLmatcher = Pattern.compile(".{1,8}:
// static provided to support unit testing
private static boolean BYTE_RANGE_DISABLED = false;
private Map<URL, Boolean> headURLCache = new HashMap<URL, Boolean>();
/**
* @return the single instance
*/
public static HttpUtils getInstance() {
if (instance == null) {
instance = new HttpUtils();
}
return instance;
}
private HttpUtils() {
htsjdk.tribble.util.ParsingUtils.registerHelperClass(IGVUrlHelper.class);
disableCertificateValidation();
CookieHandler.setDefault(new IGVCookieManager());
Authenticator.setDefault(new IGVAuthenticator());
try {
System.setProperty("java.net.useSystemProxies", "true");
} catch (Exception e) {
log.info("Couldn't set useSystemProxies=true");
}
byteRangeTestMap = Collections.synchronizedMap(new HashMap());
}
public static boolean isRemoteURL(String string) {
String lcString = string.toLowerCase();
return lcString.startsWith("http:
}
/**
* Provided to support unit testing (force disable byte range requests)
*
* @return
*/
public static void disableByteRange(boolean b) {
BYTE_RANGE_DISABLED = b;
}
/**
* Return the contents of the url as a String. This method should only be used for queries expected to return
* a small amount of data.
*
* @param url
* @return
* @throws IOException
*/
public String getContentsAsString(URL url) throws IOException {
InputStream is = null;
HttpURLConnection conn = openConnection(url, null);
try {
is = conn.getInputStream();
return readContents(is);
} catch (IOException e) {
readErrorStream(conn); // Consume content
throw e;
} finally {
if (is != null) is.close();
}
}
public String getContentsAsJSON(URL url) throws IOException {
InputStream is = null;
Map<String, String> reqProperties = new HashMap();
reqProperties.put("Accept", "application/json,text/plain");
HttpURLConnection conn = openConnection(url, reqProperties);
try {
is = conn.getInputStream();
return readContents(is);
} catch (IOException e) {
readErrorStream(conn); // Consume content
throw e;
} finally {
if (is != null) is.close();
}
}
/**
* Open a connection stream for the URL.
*
* @param url
* @return
* @throws IOException
*/
public InputStream openConnectionStream(URL url) throws IOException {
log.debug("Opening connection stream to " + url);
if (url.getProtocol().toLowerCase().equals("ftp")) {
String userInfo = url.getUserInfo();
String host = url.getHost();
String file = url.getPath();
FTPClient ftp = FTPUtils.connect(host, userInfo, new UserPasswordInputImpl());
ftp.pasv();
ftp.retr(file);
return new FTPStream(ftp);
} else {
return openConnectionStream(url, null);
}
}
public InputStream openConnectionStream(URL url, Map<String, String> requestProperties) throws IOException {
HttpURLConnection conn = openConnection(url, requestProperties);
if (conn == null) {
return null;
}
boolean rangeRequestedNotReceived = isExpectedRangeMissing(conn, requestProperties);
if (rangeRequestedNotReceived) {
String msg = "Byte range requested, but no Content-Range header in response";
log.error(msg);
// if(Globals.isTesting()){
// throw new IOException(msg);
}
try {
InputStream input = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
input = new GZIPInputStream(input);
}
return input;
} catch (IOException e) {
readErrorStream(conn); // Consume content
throw e;
}
}
boolean isExpectedRangeMissing(URLConnection conn, Map<String, String> requestProperties) {
final boolean rangeRequested = (requestProperties != null) && (new CI.CIHashMap<String>(requestProperties)).containsKey("Range");
if (!rangeRequested) return false;
Map<String, List<String>> headerFields = conn.getHeaderFields();
boolean rangeReceived = (headerFields != null) && (new CI.CIHashMap<List<String>>(headerFields)).containsKey("Content-Range");
return !rangeReceived;
}
public boolean resourceAvailable(URL url) {
log.debug("Checking if resource is available: " + url);
if (url.getProtocol().toLowerCase().equals("ftp")) {
return FTPUtils.resourceAvailable(url);
} else {
try {
HttpURLConnection conn = openConnectionHeadOrGet(url);
int code = conn.getResponseCode();
return code >= 200 && code < 300;
} catch (IOException e) {
return false;
}
}
}
/**
* First tries a HEAD request, then a GET request if the HEAD fails.
* If the GET fails, the exception is thrown
*
* @param url
* @return
* @throws IOException
*/
private HttpURLConnection openConnectionHeadOrGet(URL url) throws IOException {
// Keep track of urls for which "HEAD" does not work (e.g. Amazon with signed urls).
boolean tryHead = headURLCache.containsKey(url) ? headURLCache.get(url) : true;
if (tryHead) {
try {
HttpURLConnection conn = openConnection(url, null, "HEAD");
headURLCache.put(url, true);
return conn;
} catch (IOException e) {
if (e instanceof FileNotFoundException) {
throw e;
}
log.info("HEAD request failed for url: " + url.toExternalForm() + ". Trying GET");
headURLCache.put(url, false);
}
}
return openConnection(url, null, "GET");
}
public String getHeaderField(URL url, String key) throws IOException {
HttpURLConnection conn = openConnectionHeadOrGet(url);
if (conn == null) return null;
return conn.getHeaderField(key);
}
public long getLastModified(URL url) throws IOException {
HttpURLConnection conn = openConnectionHeadOrGet(url);
if (conn == null) return 0;
return conn.getLastModified();
}
public long getContentLength(URL url) throws IOException {
try {
String contentLengthString = getHeaderField(url, "Content-Length");
if (contentLengthString == null) {
return -1;
} else {
return Long.parseLong(contentLengthString);
}
} catch (Exception e) {
log.error("Error fetching content length", e);
return -1;
}
}
/**
* Compare a local and remote resource, returning true if it is believed that the
* remote file is newer than the local file
*
* @param file
* @param url
* @param compareContentLength Whether to use the content length to compare files. If false, only
* the modified date is used
* @return true if the files are the same or the local file is newer, false if the remote file has been modified wrt the local one.
* @throws IOException
*/
public boolean remoteIsNewer(File file, URL url, boolean compareContentLength) throws IOException {
if (!file.exists()) {
return false;
}
HttpURLConnection conn = openConnection(url, null, "HEAD");
// Check content-length first
long contentLength = -1;
String contentLengthString = conn.getHeaderField("Content-Length");
if (contentLengthString != null) {
try {
contentLength = Long.parseLong(contentLengthString);
} catch (NumberFormatException e) {
log.error("Error parsing content-length string: " + contentLengthString + " from URL: "
+ url.toString());
contentLength = -1;
}
}
if (contentLength != file.length()) {
return true;
}
// Compare last-modified dates
String lastModifiedString = conn.getHeaderField("Last-Modified");
if (lastModifiedString == null) {
return false;
} else {
HttpDate date = new HttpDate();
date.parse(lastModifiedString);
long remoteModifiedTime = date.getTime();
long localModifiedTime = file.lastModified();
return remoteModifiedTime > localModifiedTime;
}
}
public void updateProxySettings() {
boolean useProxy;
String proxyHost;
int proxyPort = -1;
boolean auth = false;
String user = null;
String pw = null;
PreferenceManager prefMgr = PreferenceManager.getInstance();
useProxy = prefMgr.getAsBoolean(PreferenceManager.USE_PROXY);
proxyHost = prefMgr.get(PreferenceManager.PROXY_HOST, null);
try {
proxyPort = Integer.parseInt(prefMgr.get(PreferenceManager.PROXY_PORT, "-1"));
} catch (NumberFormatException e) {
proxyPort = -1;
}
auth = prefMgr.getAsBoolean(PreferenceManager.PROXY_AUTHENTICATE);
user = prefMgr.get(PreferenceManager.PROXY_USER, null);
String pwString = prefMgr.get(PreferenceManager.PROXY_PW, null);
if (pwString != null) {
pw = Utilities.base64Decode(pwString);
}
String proxyTypeString = prefMgr.get(PreferenceManager.PROXY_TYPE, "HTTP");
Proxy.Type type = Proxy.Type.valueOf(proxyTypeString.trim().toUpperCase());
proxySettings = new ProxySettings(useProxy, user, pw, auth, proxyHost, proxyPort, type);
}
/**
* Get the system defined proxy defined for the URI, or null if
* not available. May also return a {@code Proxy} object which
* represents a direct connection
*
* @param uri
* @return
*/
private Proxy getSystemProxy(String uri) {
try {
log.debug("Getting system proxy for " + uri);
ProxySelector selector = ProxySelector.getDefault();
List<Proxy> proxyList = selector.select(new URI(uri));
return proxyList.get(0);
} catch (URISyntaxException e) {
log.error(e.getMessage(), e);
return null;
} catch (NullPointerException e) {
return null;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
/**
* Calls {@link #downloadFile(String, java.io.File, Frame, String)}
* with {@code dialogsParent = null, title = null}
*
* @param url
* @param outputFile
* @return RunnableResult
* @throws IOException
*/
public RunnableResult downloadFile(String url, File outputFile) throws IOException {
URLDownloader downloader = downloadFile(url, outputFile, null, null);
return downloader.getResult();
}
/**
* @param url
* @param outputFile
* @param dialogsParent Parent of dialog to show progress. If null, none shown
* @return URLDownloader used to perform download
* @throws IOException
*/
public URLDownloader downloadFile(String url, File outputFile, Frame dialogsParent, String dialogTitle) throws IOException {
final URLDownloader urlDownloader = new URLDownloader(url, outputFile);
boolean showProgressDialog = dialogsParent != null;
if (!showProgressDialog) {
urlDownloader.run();
return urlDownloader;
} else {
ProgressMonitor monitor = new ProgressMonitor();
urlDownloader.setMonitor(monitor);
ActionListener buttonListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
urlDownloader.cancel(true);
}
};
String permText = "Downloading " + url;
String title = dialogTitle != null ? dialogTitle : permText;
CancellableProgressDialog dialog = CancellableProgressDialog.showCancellableProgressDialog(dialogsParent, title, buttonListener, false, monitor);
dialog.setPermText(permText);
Dimension dms = new Dimension(600, 150);
dialog.setPreferredSize(dms);
dialog.setSize(dms);
dialog.validate();
LongRunningTask.submit(urlDownloader);
return urlDownloader;
}
}
public void uploadGenomeSpaceFile(String uri, File file, Map<String, String> headers) throws IOException {
HttpURLConnection urlconnection = null;
OutputStream bos = null;
URL url = new URL(uri);
urlconnection = openConnection(url, headers, "PUT");
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
bos = new BufferedOutputStream(urlconnection.getOutputStream());
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int i;
// read byte by byte until end of stream
while ((i = bis.read()) > 0) {
bos.write(i);
}
bos.close();
int responseCode = urlconnection.getResponseCode();
// Error messages below.
if (responseCode >= 400) {
String message = readErrorStream(urlconnection);
throw new IOException("Error uploading " + file.getName() + " : " + message);
}
}
public String createGenomeSpaceDirectory(URL url, String body) throws IOException {
HttpURLConnection urlconnection = null;
OutputStream bos = null;
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Content-Length", String.valueOf(body.getBytes().length));
urlconnection = openConnection(url, headers, "PUT");
urlconnection.setDoOutput(true);
urlconnection.setDoInput(true);
bos = new BufferedOutputStream(urlconnection.getOutputStream());
bos.write(body.getBytes());
bos.close();
int responseCode = urlconnection.getResponseCode();
// Error messages below.
StringBuffer buf = new StringBuffer();
InputStream inputStream;
if (responseCode >= 200 && responseCode < 300) {
inputStream = urlconnection.getInputStream();
} else {
inputStream = urlconnection.getErrorStream();
}
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String nextLine;
while ((nextLine = br.readLine()) != null) {
buf.append(nextLine);
buf.append('\n');
}
inputStream.close();
if (responseCode >= 200 && responseCode < 300) {
return buf.toString();
} else {
throw new IOException("Error creating GS directory: " + buf.toString());
}
}
/**
* Code for disabling SSL certification
*/
private void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (NoSuchAlgorithmException e) {
} catch (KeyManagementException e) {
}
}
private String readContents(InputStream is) throws IOException {
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int b;
while ((b = bis.read()) >= 0) {
bos.write(b);
}
return new String(bos.toByteArray());
}
private String readErrorStream(HttpURLConnection connection) throws IOException {
InputStream inputStream = null;
try {
inputStream = connection.getErrorStream();
if (inputStream == null) {
return null;
}
return readContents(inputStream);
} finally {
if (inputStream != null) inputStream.close();
}
}
public HttpURLConnection delete(URL url) throws IOException {
return openConnection(url, Collections.<String, String>emptyMap(), "DELETE");
}
HttpURLConnection openConnection(URL url, Map<String, String> requestProperties) throws IOException {
return openConnection(url, requestProperties, "GET");
}
private HttpURLConnection openConnection(URL url, Map<String, String> requestProperties, String method) throws IOException {
return openConnection(url, requestProperties, method, 0);
}
/**
* The "real" connection method
*
* @param url
* @param requestProperties
* @param method
* @return
* @throws java.io.IOException
*/
private HttpURLConnection openConnection(
URL url, Map<String, String> requestProperties, String method, int redirectCount) throws IOException {
//Encode query string portions
url = StringUtils.encodeURLQueryString(url);
if (log.isTraceEnabled()) {
log.trace(url);
}
//Encode base portions. Right now just spaces, most common case
//TODO This is a hack and doesn't work for all characters which need it
if (StringUtils.countChar(url.toExternalForm(), ' ') > 0) {
String newPath = url.toExternalForm().replaceAll(" ", "%20");
url = new URL(newPath);
}
Proxy sysProxy = null;
boolean igvProxySettingsExist = proxySettings != null && proxySettings.useProxy;
//Only check for system proxy if igv proxy settings not found
if (!igvProxySettingsExist) {
sysProxy = getSystemProxy(url.toExternalForm());
}
boolean useProxy = sysProxy != null || igvProxySettingsExist;
HttpURLConnection conn;
if (useProxy) {
Proxy proxy = sysProxy;
if (igvProxySettingsExist) {
if (proxySettings.type == Proxy.Type.DIRECT) {
proxy = Proxy.NO_PROXY;
} else {
proxy = new Proxy(proxySettings.type, new InetSocketAddress(proxySettings.proxyHost, proxySettings.proxyPort));
}
}
conn = (HttpURLConnection) url.openConnection(proxy);
if (igvProxySettingsExist && proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) {
byte[] bytes = (proxySettings.user + ":" + proxySettings.pw).getBytes();
String encodedUserPwd = String.valueOf(Base64Coder.encode(bytes));
conn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
}
} else {
conn = (HttpURLConnection) url.openConnection();
}
if (GSUtils.isGenomeSpace(url)) {
conn.setRequestProperty("Accept", "application/json,text/plain");
} else {
conn.setRequestProperty("Accept", "text/plain");
}
//There seems to be a bug with JWS caches
//So we avoid caching
//This default is persistent, really should be available statically but isn't
conn.setDefaultUseCaches(false);
conn.setUseCaches(false);
conn.setConnectTimeout(Globals.CONNECT_TIMEOUT);
conn.setReadTimeout(Globals.READ_TIMEOUT);
conn.setRequestMethod(method);
conn.setRequestProperty("Connection", "Keep-Alive");
if (requestProperties != null) {
for (Map.Entry<String, String> prop : requestProperties.entrySet()) {
conn.setRequestProperty(prop.getKey(), prop.getValue());
}
}
conn.setRequestProperty("User-Agent", Globals.applicationString());
if (method.equals("PUT")) {
return conn;
} else {
int code = conn.getResponseCode();
if (log.isDebugEnabled()) {
//logHeaders(conn);
}
// Redirects. These can occur even if followRedirects == true if there is a change in protocol,
// for example http -> https.
if (code >= 300 && code < 400) {
if (redirectCount > MAX_REDIRECTS) {
throw new IOException("Too many redirects");
}
String newLocation = conn.getHeaderField("Location");
log.debug("Redirecting to " + newLocation);
return openConnection(new URL(newLocation), requestProperties, method, ++redirectCount);
}
// TODO -- handle other response codes.
else if (code >= 400) {
String message;
if (code == 404) {
message = "File not found: " + url.toString();
throw new FileNotFoundException(message);
} else if (code == 401) {
// Looks like this only happens when user hits "Cancel".
// message = "Not authorized to view this file";
// JOptionPane.showMessageDialog(null, message, "HTTP error", JOptionPane.ERROR_MESSAGE);
redirectCount = MAX_REDIRECTS + 1;
return null;
} else {
message = conn.getResponseMessage();
}
String details = readErrorStream(conn);
log.error("URL: " + url.toExternalForm() + ". error stream: " + details);
log.error("Code: " + code + ". " + message);
HttpResponseException exc = new HttpResponseException(code);
throw exc;
}
}
return conn;
}
//Used for testing sometimes, please do not delete
private void logHeaders(HttpURLConnection conn) {
Map<String, List<String>> headerFields = conn.getHeaderFields();
log.debug("Headers for " + conn.getURL());
for (Map.Entry<String, List<String>> header : headerFields.entrySet()) {
log.debug(header.getKey() + ": " + StringUtils.join(header.getValue(), ","));
}
}
public void setDefaultPassword(String defaultPassword) {
this.defaultPassword = defaultPassword.toCharArray();
}
public void setDefaultUserName(String defaultUserName) {
this.defaultUserName = defaultUserName;
}
public void clearDefaultCredentials() {
this.defaultPassword = null;
this.defaultUserName = null;
}
/**
* Test to see if this client can successfully retrieve a portion of a remote file using the byte-range header.
* This is not a test of the server, but the client. In some environments the byte-range header gets removed
* by filters after the request is made by IGV.
*
* @return
*/
public boolean useByteRange(URL url) {
if (BYTE_RANGE_DISABLED) return false;
// We can test byte-range success for hosts we can reach.
synchronized (byteRangeTestMap) {
final String host = url.getHost();
if (byteRangeTestMap.containsKey(host)) {
return byteRangeTestMap.get(host);
} else {
SeekableStream str = null;
try {
boolean byteRangeTestSuccess = true;
if (host.contains("broadinstitute.org")) {
byteRangeTestSuccess = testBroadHost(host);
} else {
// Non-broad URL
int l = (int) Math.min(1000, HttpUtils.getInstance().getContentLength(url));
if (l > 100) {
byte[] firstBytes = new byte[l];
str = new IGVSeekableHTTPStream(url);
str.readFully(firstBytes);
int end = firstBytes.length;
int start = end - 100;
str.seek(start);
int len = end - start;
byte[] buffer = new byte[len];
int n = 0;
while (n < len) {
int count = str.read(buffer, n, len - n);
if (count < 0)
throw new EOFException();
n += count;
}
for (int i = 0; i < len; i++) {
if (buffer[i] != firstBytes[i + start]) {
byteRangeTestSuccess = false;
break;
}
}
} else {
// Too small a sample to test, or unknown content length. Return "true" but don't record
// this host as tested.
return true;
}
}
if (byteRangeTestSuccess) {
log.info("Range-byte request succeeded");
} else {
log.info("Range-byte test failed -- problem with client network environment.");
}
byteRangeTestMap.put(host, byteRangeTestSuccess);
return byteRangeTestSuccess;
} catch (IOException e) {
log.error("Error while testing byte range " + e.getMessage());
// We could not reach the test server, so we can't know if this client can do byte-range tests or
// not. Take the "optimistic" view.
return true;
} finally {
if (str != null) try {
str.close();
} catch (IOException e) {
log.error("Error closing stream (" + url.toExternalForm() + ")", e);
}
}
}
}
}
private boolean testBroadHost(String host) throws IOException {
// Test broad urls for successful byte range requests.
log.info("Testing range-byte request on host: " + host);
String testURL;
if (host.startsWith("igvdata.broadinstitute.org")) {
// Amazon cloud front
testURL = "http://igvdata.broadinstitute.org/genomes/seq/hg19/chr12.txt";
} else if (host.startsWith("igv.broadinstitute.org")) {
// Amazon S3
testURL = "http://igv.broadinstitute.org/genomes/seq/hg19/chr12.txt";
} else {
// All others
testURL = "http:
}
byte[] expectedBytes = {'T', 'C', 'G', 'C', 'T', 'T', 'G', 'A', 'A', 'C', 'C', 'C', 'G', 'G',
'G', 'A', 'G', 'A', 'G', 'G'};
IGVSeekableHTTPStream str = null;
try {
str = new IGVSeekableHTTPStream(new URL(testURL));
str.seek(25350000);
byte[] buffer = new byte[80000];
str.read(buffer);
String result = new String(buffer);
for (int i = 0; i < expectedBytes.length; i++) {
if (buffer[i] != expectedBytes[i]) {
return false;
}
}
return true;
} finally {
if (str != null) str.close();
}
}
public void shutdown() {
// Do any cleanup required here
}
/**
* Checks if the string is a URL (not necessarily remote, can be any protocol)
*
* @param f
* @return
*/
public static boolean isURL(String f) {
return f.startsWith("http:") || f.startsWith("ftp:") || f.startsWith("https:") || URLmatcher.matcher(f).matches();
}
public static Map<String, String> parseQueryString(String query) {
String[] params = query.split("&");
Map<String, String> map = new HashMap<String, String>();
for (String param : params) {
String[] name_val = param.split("=", 2);
if (name_val.length == 2) {
map.put(name_val[0], name_val[1]);
}
}
return map;
}
public static class ProxySettings {
boolean auth = false;
String user;
String pw;
boolean useProxy;
String proxyHost;
int proxyPort = -1;
Proxy.Type type;
public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort) {
this(useProxy, user, pw, auth, proxyHost, proxyPort, Proxy.Type.HTTP);
this.auth = auth;
}
public ProxySettings(boolean useProxy, String user, String pw, boolean auth, String proxyHost, int proxyPort, Proxy.Type proxyType) {
this.auth = auth;
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.pw = pw;
this.useProxy = useProxy;
this.user = user;
this.type = proxyType;
}
}
/**
* The default authenticator
*/
public class IGVAuthenticator extends Authenticator {
Hashtable<String, PasswordAuthentication> pwCache = new Hashtable<String, PasswordAuthentication>();
HashSet<String> cacheAttempts = new HashSet<String>();
/**
* Called when password authentication is needed.
*
* @return
*/
@Override
protected synchronized PasswordAuthentication getPasswordAuthentication() {
RequestorType type = getRequestorType();
String urlString = getRequestingURL().toString();
boolean isProxyChallenge = type == RequestorType.PROXY;
// Cache user entered PWs. In normal use this shouldn't be necessary as credentials are cached upstream,
// but if loading many files in parallel (e.g. from sessions) calls to this method can queue up before the
// user enters their credentials, causing needless reentry.
String pKey = type.toString() + getRequestingProtocol() + getRequestingHost();
PasswordAuthentication pw = pwCache.get(pKey);
if (pw != null) {
// Prevents infinite loop if credentials are incorrect
if (cacheAttempts.contains(urlString)) {
cacheAttempts.remove(urlString);
} else {
cacheAttempts.add(urlString);
return pw;
}
}
if (isProxyChallenge) {
if (proxySettings.auth && proxySettings.user != null && proxySettings.pw != null) {
return new PasswordAuthentication(proxySettings.user, proxySettings.pw.toCharArray());
}
}
if (defaultUserName != null && defaultPassword != null) {
return new PasswordAuthentication(defaultUserName, defaultPassword);
}
Frame owner = IGV.hasInstance() ? IGV.getMainFrame() : null;
boolean isGenomeSpace = GSUtils.isGenomeSpace(getRequestingURL());
if (isGenomeSpace) {
// If we are being challenged by GS the token must be bad/expired
GSUtils.logout();
}
LoginDialog dlg = new LoginDialog(owner, isGenomeSpace, urlString, isProxyChallenge);
dlg.setVisible(true);
if (dlg.isCanceled()) {
return null;
} else {
final String userString = dlg.getUsername();
final char[] userPass = dlg.getPassword();
if (isProxyChallenge) {
proxySettings.user = userString;
proxySettings.pw = new String(userPass);
}
pw = new PasswordAuthentication(userString, userPass);
pwCache.put(pKey, pw);
return pw;
}
}
}
/**
* Runnable for downloading a file from a URL.
* Downloading is buffered, and can be cancelled (between buffers)
* via {@link #cancel(boolean)}
*/
public class URLDownloader implements Runnable {
private ProgressMonitor monitor = null;
private final URL srcUrl;
private final File outputFile;
private volatile boolean started = false;
private volatile boolean done = false;
private volatile boolean cancelled = false;
private volatile RunnableResult result;
public URLDownloader(String url, File outputFile) throws MalformedURLException {
this.srcUrl = new URL(url);
this.outputFile = outputFile;
}
@Override
public void run() {
if (this.cancelled) {
return;
}
started = true;
try {
this.result = doDownload();
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
this.done();
}
}
/**
* Return the result. Must be called after run is complete
*
* @return
*/
public RunnableResult getResult() {
if (!this.done) throw new IllegalStateException("Must wait for run to finish before getting result");
return this.result;
}
private RunnableResult doDownload() throws IOException {
log.info("Downloading " + srcUrl + " to " + outputFile.getAbsolutePath());
HttpURLConnection conn = openConnection(this.srcUrl, null);
long contentLength = -1;
String contentLengthString = conn.getHeaderField("Content-Length");
if (contentLengthString != null) {
contentLength = Long.parseLong(contentLengthString);
}
InputStream is = null;
OutputStream out = null;
long downloaded = 0;
long downSinceLast = 0;
String curStatus;
String msg1 = String.format("downloaded of %s total", contentLength >= 0 ? bytesToByteCountString(contentLength) : "unknown");
int perc = 0;
try {
is = conn.getInputStream();
out = new FileOutputStream(outputFile);
byte[] buf = new byte[64 * 1024];
int counter = 0;
int interval = 100;
int bytesRead = 0;
while (!this.cancelled && (bytesRead = is.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
downloaded += bytesRead;
downSinceLast += bytesRead;
counter = (counter + 1) % interval;
if (counter == 0 && this.monitor != null) {
curStatus = String.format("%s %s", bytesToByteCountString(downloaded), msg1);
this.monitor.updateStatus(curStatus);
if (contentLength >= 0) {
perc = (int) ((downSinceLast * 100) / contentLength);
this.monitor.fireProgressChange(perc);
if (perc >= 1) downSinceLast = 0;
}
}
}
log.info("Download complete. Total bytes downloaded = " + downloaded);
} catch (IOException e) {
readErrorStream(conn);
throw e;
} finally {
if (is != null) is.close();
if (out != null) {
out.flush();
out.close();
}
}
long fileLength = outputFile.length();
if (this.cancelled) return RunnableResult.CANCELLED;
boolean knownComplete = contentLength == fileLength;
//Assume success if file length not known
if (knownComplete || contentLength < 0) {
if (this.monitor != null) {
this.monitor.fireProgressChange(100);
this.monitor.updateStatus("Done");
}
return RunnableResult.SUCCESS;
} else {
return RunnableResult.FAILURE;
}
}
protected void done() {
this.done = true;
}
public boolean isDone() {
return this.done;
}
/**
* See {@link java.util.concurrent.FutureTask#cancel(boolean)}
*
* @param mayInterruptIfRunning
* @return
*/
public boolean cancel(boolean mayInterruptIfRunning) {
if (this.started && !mayInterruptIfRunning) {
return false;
}
this.cancelled = true;
return true;
}
public void setMonitor(ProgressMonitor monitor) {
this.monitor = monitor;
}
/**
* Convert bytes to human-readable string.
* e.g. 102894 -> 102.89 KB. If too big or too small,
* doesn't append a prefix just returns {@code bytes + " B"}
*
* @param bytes
* @return
*/
public String bytesToByteCountString(long bytes) {
int unit = 1000;
String prefs = "KMGT";
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
if (exp <= 0 || exp >= prefs.length()) return bytes + " B";
String pre = (prefs).charAt(exp - 1) + "";
return String.format("%.2f %sB", bytes / Math.pow(unit, exp), pre);
}
}
/**
* Provide override for unit tests
*/
public void setAuthenticator(Authenticator authenticator) {
Authenticator.setDefault(authenticator);
}
/**
* For unit tests
*/
public void resetAuthenticator() {
Authenticator.setDefault(new IGVAuthenticator());
}
/**
* Extension of CookieManager that grabs cookies from the GenomeSpace identity server to store locally.
* This is to support the GenomeSpace "single sign-on". Examples ...
* gs-username=igvtest; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/
* gs-token=HnR9rBShNO4dTXk8cKXVJT98Oe0jWVY+; Domain=.genomespace.org; Expires=Mon, 21-Jul-2031 03:27:23 GMT; Path=/
*/
static class IGVCookieManager extends CookieManager {
@Override
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.putAll(super.get(uri, requestHeaders));
if (GSUtils.isGenomeSpace(uri.toURL())) {
String token = GSUtils.getGSToken();
if (token != null) {
List<String> cookieList = headers.get("Cookie");
boolean needsTokenCookie = true;
if (cookieList == null) {
cookieList = new ArrayList<String>(1);
headers.put("Cookie", cookieList);
}
for (String cookie : cookieList) {
if (cookie.startsWith("gs-token")) {
needsTokenCookie = false;
break;
}
}
if (needsTokenCookie) {
cookieList.add("gs-token=" + token);
}
}
}
return Collections.unmodifiableMap(headers);
}
@Override
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
String urilc = uri.toString().toLowerCase();
if (urilc.contains("identity") && urilc.contains("genomespace")) {
List<String> cookies = responseHeaders.get("Set-Cookie");
if (cookies != null) {
for (String cstring : cookies) {
List<HttpCookie> cookieList = HttpCookie.parse(cstring);
for (HttpCookie cookie : cookieList) {
String cookieName = cookie.getName();
String value = cookie.getValue();
if (cookieName.equals("gs-token")) {
//log.debug("gs-token: " + value);
GSUtils.setGSToken(value);
} else if (cookieName.equals("gs-username")) {
//log.debug("gs-username: " + value);
GSUtils.setGSUser(value);
}
}
}
}
}
super.put(uri, responseHeaders);
}
}
}
|
package org.clapper.curn;
import org.clapper.util.logging.Logger;
import java.io.File;
import java.util.Collection;
/**
* <p>This static singleton class is used to allocate a new {@link Curn}
* object for RSS processing. Hiding the allocation behind a factory allows
* for various bootstrap activities, including the installation and use of
* a different class loader that adds the plug-in jars and directories
* to the load path at runtime.</p>
*
* @version <tt>$Revision$</tt>
*/
public class CurnFactory
{
/**
* For log messages
*/
private static Logger log = new Logger (CurnFactory.class);
/**
* Cannot be instantiated.
*/
private CurnFactory()
{
}
/**
* Create a new {@link Curn} object. The resulting object will be
* loaded via a different class loader. This method also implicitly
* loads the plug-ins.
*
* @return the <tt>Curn</tt> object
*
* @throws CurnException on error
*/
public static Curn newCurn()
throws CurnException
{
// Load the plug-ins.
PlugInManager.loadPlugIns();
return new Curn();
}
}
|
package org.jcodings.transcode;
import static org.jcodings.util.CaseInsensitiveBytesHash.caseInsensitiveEquals;
import org.jcodings.Encoding;
import org.jcodings.Ptr;
import org.jcodings.exception.InternalException;
public final class EConv implements EConvFlags {
int flags;
public byte[] source, destination; // source/destination encoding names
boolean started = false;
public byte[] replacementString;
public int replacementLength;
public byte[] replacementEncoding;
Buffer inBuf = new Buffer();
public EConvElement[] elements;
public int numTranscoders;
int numFinished;
public Transcoding lastTranscoding;
public final LastError lastError = new LastError();
public Encoding sourceEncoding, destinationEncoding;
@Override
public String toString() {
return new String(source) + " => " + new String(destination);
}
EConv(int nHint) {
if (nHint <= 0) nHint = 1;
elements = new EConvElement[nHint];
lastError.result = EConvResult.SourceBufferEmpty;
}
public static final class EConvElement extends Buffer {
EConvElement(Transcoding transcoding) {
this.transcoding = transcoding;
lastResult = EConvResult.SourceBufferEmpty;
}
public final Transcoding transcoding;
EConvResult lastResult;
@Override
public String toString() {
String s = "EConv " + transcoding.toString() + "\n";
s += " last result: " + lastResult;
return s;
}
}
public static final class LastError {
public EConvResult result;
public Transcoding errorTranscoding;
public byte[] source, destination;
public byte[] errorBytes;
public int errorBytesP, errorBytesEnd;
public int readAgainLength;
void reset() {
result = null;
errorTranscoding = null;
source = destination = null;
errorBytes = null;
errorBytesP = errorBytesEnd = 0;
readAgainLength = 0;
}
@Override
public String toString() {
String s = "Last Error " + (source == null ? "null" : new String(source)) + " => " + (destination == null ? "null" : new String(destination))
+ "\n";
s += " result: " + result.toString() + "\n";
s += " error bytes: " + (errorBytes == null ? "null" : new String(errorBytes, errorBytesP, errorBytesP + errorBytesEnd)) + "\n";
s += " read again length: " + readAgainLength;
return s;
}
}
static final byte[] NULL_STRING = new byte[0];
static final int[] NULL_POINTER = new int[0];
static boolean decorator(byte[] source, byte[] destination) {
return source.length == 0;
}
/* rb_econv_add_transcoder_at */
void addTranscoderAt(Transcoder transcoder, int i) {
if (numTranscoders == elements.length) {
EConvElement[] tmp = new EConvElement[elements.length * 2];
System.arraycopy(elements, 0, tmp, 0, i);
System.arraycopy(elements, i, tmp, i + 1, elements.length - i);
elements = tmp;
} else {
System.arraycopy(elements, i, elements, i + 1, elements.length - i - 1);
}
elements[i] = new EConvElement(transcoder.transcoding(0));
elements[i].allocate(4096);
numTranscoders++;
if (!decorator(transcoder.source, transcoder.destination)) {
for (int j = numTranscoders - 1; i <= j; j
Transcoding tc = elements[j].transcoding;
Transcoder tr = tc.transcoder;
if (!decorator(tr.source, tr.destination)) {
lastTranscoding = tc;
break;
}
}
}
}
/* trans_sweep */
private int transSweep(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, int start) {
boolean try_ = true;
Ptr ipp = null;
Ptr opp = null;
while (try_) {
try_ = false;
for (int i = start; i < numTranscoders; i++) {
EConvElement te = elements[i];
final int is, os;
final byte[] ibytes, obytes;
EConvElement previousTE = null;
boolean ippIsStart = false;
boolean oppIsEnd = false;
if (i == 0) {
ipp = inPtr;
is = inStop;
ibytes = in;
} else {
previousTE = elements[i - 1];
ipp = new Ptr(previousTE.dataStart);
ippIsStart = true;
is = previousTE.dataEnd;
ibytes = previousTE.bytes;
}
if (i == numTranscoders - 1) {
opp = outPtr;
os = outStop;
obytes = out;
} else {
if (te.bufStart != te.dataStart) {
int len = te.dataEnd - te.dataStart;
int off = te.dataStart - te.bufStart;
System.arraycopy(te.bytes, te.dataStart, te.bytes, te.bufStart, len);
te.dataStart = te.bufStart;
te.dataEnd -= off;
}
opp = new Ptr(te.dataEnd);
oppIsEnd = true;
os = te.bufEnd;
obytes = te.bytes;
}
int f = flags;
if (numFinished != i) f |= PARTIAL_INPUT;
if (i == 0 && (flags & AFTER_OUTPUT) != 0) {
start = 1;
flags &= ~AFTER_OUTPUT;
}
if (i != 0) f &= ~AFTER_OUTPUT;
int iold = ipp.p;
int oold = opp.p;
EConvResult res;
te.lastResult = res = te.transcoding.convert(ibytes, ipp, is, obytes, opp, os, f);
if (ippIsStart) previousTE.dataStart = ipp.p;
if (oppIsEnd) te.dataEnd = opp.p;
if (iold != ipp.p || oold != opp.p) try_ = true;
switch (res) {
case InvalidByteSequence:
case IncompleteInput:
case UndefinedConversion:
case AfterOutput:
return i;
case DestinationBufferFull:
case SourceBufferEmpty:
break;
case Finished:
numFinished = i + 1;
break;
}
}
}
return -1;
}
/* rb_trans_conv */
private EConvResult transConv(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, Ptr resultPositionPtr) {
// null check
if (elements[0].lastResult == EConvResult.AfterOutput) elements[0].lastResult = EConvResult.SourceBufferEmpty;
for (int i = numTranscoders - 1; 0 <= i; i
switch (elements[i].lastResult) {
case InvalidByteSequence:
case IncompleteInput:
case UndefinedConversion:
case AfterOutput:
case Finished:
return transConvNeedReport(in, inPtr, inStop, out, outPtr, outStop, flags, resultPositionPtr, i + 1, i);
case DestinationBufferFull:
case SourceBufferEmpty:
break;
default:
throw new InternalException("unexpected transcode last result");
}
}
/* /^[sd]+$/ is confirmed. but actually /^s*d*$/. */
if (elements[numTranscoders - 1].lastResult == EConvResult.DestinationBufferFull && (flags & AFTER_OUTPUT) != 0) {
EConvResult res = transConv(NULL_STRING, Ptr.NULL, 0, out, outPtr, outStop, (flags & ~AFTER_OUTPUT) | PARTIAL_INPUT, resultPositionPtr);
return res.isSourceBufferEmpty() ? EConvResult.AfterOutput : res;
}
return transConvNeedReport(in, inPtr, inStop, out, outPtr, outStop, flags, resultPositionPtr, 0, -1);
}
private EConvResult transConvNeedReport(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags, Ptr resultPositionPtr,
int sweepStart, int needReportIndex) {
do {
needReportIndex = transSweep(in, inPtr, inStop, out, outPtr, outStop, flags, sweepStart);
sweepStart = needReportIndex + 1;
} while (needReportIndex != -1 && needReportIndex != numTranscoders - 1);
for (int i = numTranscoders - 1; i >= 0; i
if (elements[i].lastResult != EConvResult.SourceBufferEmpty) {
EConvResult res = elements[i].lastResult;
switch (res) {
case InvalidByteSequence:
case IncompleteInput:
case UndefinedConversion:
case AfterOutput:
elements[i].lastResult = EConvResult.SourceBufferEmpty;
}
if (resultPositionPtr != null) resultPositionPtr.p = i;
return res;
}
}
if (resultPositionPtr != null) resultPositionPtr.p = -1;
return EConvResult.SourceBufferEmpty;
}
/* rb_econv_convert0 */
private EConvResult convertInternal(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags) {
lastError.reset();
EConvResult res;
int len;
if (numTranscoders == 0) {
if (inBuf.bytes != null && inBuf.dataStart != inBuf.dataEnd) {
if (outStop - outPtr.p < inBuf.dataEnd - inBuf.dataStart) {
len = outStop - outPtr.p;
System.arraycopy(inBuf, inBuf.dataStart, out, outPtr.p, len);
outPtr.p = outStop;
inBuf.dataStart += len;
return convertInternalResult(EConvResult.DestinationBufferFull, null);
}
len = inBuf.dataEnd - inBuf.dataStart;
System.arraycopy(inBuf, inBuf.dataStart, out, outPtr.p, len);
outPtr.p += len;
inBuf.dataStart = inBuf.dataEnd = inBuf.bufStart;
if ((flags & AFTER_OUTPUT) != 0) return convertInternalResult(EConvResult.AfterOutput, null);
}
if (outStop - outPtr.p < inStop - inPtr.p) {
len = outStop - outPtr.p;
} else {
len = inStop - inPtr.p;
}
if (len > 0 && (flags & AFTER_OUTPUT) != 0) {
out[outPtr.p++] = in[inPtr.p++];
return convertInternalResult(EConvResult.AfterOutput, null);
}
System.arraycopy(in, inPtr.p, out, outPtr.p, len);
outPtr.p += len;
inPtr.p += len;
if (inPtr.p != inStop) {
res = EConvResult.DestinationBufferFull;
} else if ((flags & PARTIAL_INPUT) != 0) {
res = EConvResult.SourceBufferEmpty;
} else {
res = EConvResult.Finished;
}
return convertInternalResult(res, null);
}
boolean hasOutput = false;
EConvElement elem = elements[numTranscoders - 1];
if (elem.bytes != null) {
int dataStart = elem.dataStart;
int dataEnd = elem.dataEnd;
byte[] data = elem.bytes;
if (dataStart != dataEnd) {
if (outStop - outPtr.p < dataEnd - dataStart) {
len = outStop - outPtr.p;
System.arraycopy(data, dataStart, out, outPtr.p, len);
outPtr.p = outStop;
elem.dataStart += len;
return convertInternalResult(EConvResult.DestinationBufferFull, null);
}
len = dataEnd - dataStart;
System.arraycopy(data, dataStart, out, outPtr.p, len);
outPtr.p += len;
elem.dataStart = elem.dataEnd = elem.bufStart;
hasOutput = true;
}
}
Ptr resultPosition = new Ptr(0);
if (inBuf != null && inBuf.dataStart != inBuf.dataEnd) {
Ptr inDataStartPtr = new Ptr(inBuf.dataStart);
res = transConv(inBuf.bytes, inDataStartPtr, inBuf.dataEnd, out, outPtr, outStop, (flags & ~AFTER_OUTPUT) | PARTIAL_INPUT, resultPosition);
inBuf.dataStart = inDataStartPtr.p;
if (!res.isSourceBufferEmpty()) return convertInternalResult(EConvResult.SourceBufferEmpty, resultPosition);
}
if (hasOutput && (flags & AFTER_OUTPUT) != 0 && inPtr.p != inStop) {
inStop = inPtr.p;
res = transConv(in, inPtr, inStop, out, outPtr, outStop, flags, resultPosition);
if (res.isSourceBufferEmpty()) res = EConvResult.AfterOutput;
} else if ((flags & AFTER_OUTPUT) != 0 || numTranscoders == 1) {
res = transConv(in, inPtr, inStop, out, outPtr, outStop, flags, resultPosition);
} else {
flags |= AFTER_OUTPUT;
do {
res = transConv(in, inPtr, inStop, out, outPtr, outStop, flags, resultPosition);
} while (res.isAfterOutput());
}
return convertInternalResult(res, resultPosition);
}
private EConvResult convertInternalResult(EConvResult res, Ptr resultPosition) {
lastError.result = res;
switch (res) {
case InvalidByteSequence:
case IncompleteInput:
case UndefinedConversion:
Transcoding errorTranscoding = elements[resultPosition.p].transcoding;
lastError.errorTranscoding = errorTranscoding;
lastError.source = errorTranscoding.transcoder.source;
lastError.destination = errorTranscoding.transcoder.destination;
lastError.errorBytes = errorTranscoding.readBuf;
lastError.errorBytesP = 0;
lastError.errorBytesEnd = errorTranscoding.recognizedLength;
lastError.readAgainLength = errorTranscoding.readAgainLength;
}
return res;
}
/* rb_econv_convert */
public EConvResult convert(byte[] in, Ptr inPtr, int inStop, byte[] out, Ptr outPtr, int outStop, int flags) {
started = true;
// null check
resume: while (true) {
EConvResult ret = convertInternal(in, inPtr, inStop, out, outPtr, outStop, flags);
if (ret.isInvalidByteSequence() || ret.isIncompleteInput()) {
switch (this.flags & INVALID_MASK) {
case INVALID_REPLACE:
if (outputReplacementCharacter() == 0) continue resume;
}
}
if (ret.isUndefinedConversion()) {
switch (this.flags & UNDEF_MASK) {
case UNDEF_REPLACE:
if (outputReplacementCharacter() == 0) continue resume;
break;
case UNDEF_HEX_CHARREF:
if (outputHexCharref() == 0) continue resume;
break;
}
}
return ret;
}
}
/* output_hex_charref */
private int outputHexCharref() {
final byte[] utfBytes;
final int utfP;
int utfLen;
if (caseInsensitiveEquals(lastError.source, "UTF-32BE".getBytes())) {
utfBytes = lastError.errorBytes;
utfP = lastError.errorBytesP;
utfLen = lastError.errorBytesEnd - lastError.errorBytesP;
} else {
Ptr utfLenA = new Ptr();
byte[] utfBuf = new byte[1024];
utfBytes = allocateConvertedString(lastError.source, "UTF-32BE".getBytes(), lastError.errorBytes, lastError.errorBytesP, lastError.errorBytesEnd
- lastError.errorBytesP, utfBuf, utfLenA);
if (utfBytes == null) return -1;
utfP = 0;
utfLen = utfLenA.p;
}
if (utfLen % 4 != 0) return -1;
int p = utfP;
while (4 <= utfLen) {
int u = 0; // long ??
u += (utfBytes[p] & 0xff) << 24;
u += (utfBytes[p + 1] & 0xff) << 16;
u += (utfBytes[p + 2] & 0xff) << 8;
u += (utfBytes[p + 3]);
byte[] charrefbuf = String.format("&#x%X;", u).getBytes(); // use faster sprintf ??
if (insertOutput(charrefbuf, charrefbuf.length, "US-ASCII".getBytes()) == -1) return -1;
p += 4;
utfLen -= 4;
}
return 0;
}
/* rb_econv_encoding_to_insert_output */
private byte[] encodingToInsertOutput() {
Transcoding transcoding = lastTranscoding;
if (transcoding == null) return NULL_STRING;
Transcoder transcoder = transcoding.transcoder;
return transcoder.compatibility.isEncoder() ? transcoder.source : transcoder.destination;
}
/* allocate_converted_string */
private static byte[] allocateConvertedString(byte[] source, byte[] destination, byte[] str, int strP, int strLen, byte[] callerDstBuf, Ptr dstLenPtr) {
int dstBufSize;
if (callerDstBuf != null) {
dstBufSize = callerDstBuf.length;
} else if (strLen == 0) {
dstBufSize = 1;
} else {
dstBufSize = strLen;
}
EConv ec = TranscoderDB.open(source, destination, 0);
if (ec == null) return null;
byte[] dstStr;
if (callerDstBuf != null) {
dstStr = callerDstBuf;
} else {
dstStr = new byte[dstBufSize];
}
int dstLen = 0;
Ptr sp = new Ptr(strP);
Ptr dp = new Ptr(dstLen);
EConvResult res = ec.convert(str, sp, strP + strLen, dstStr, dp, dstBufSize, 0);
dstLen = dp.p;
while (res.isDestinationBufferFull()) {
dstBufSize *= 2;
byte[] tmp = new byte[dstBufSize];
System.arraycopy(dstStr, 0, tmp, 0, dstBufSize / 2);
dstStr = tmp;
dp.p = dstLen;
res = ec.convert(str, sp, strP + strLen, dstStr, dp, dstBufSize, 0);
dstLen = dp.p;
}
if (!res.isFinished()) return null;
ec.close();
dstLenPtr.p = dstLen;
return dstStr;
}
/* rb_econv_insert_output */
public int insertOutput(byte[] str, int strLen, byte[] strEncoding) {
byte[] insertEncoding = encodingToInsertOutput();
byte[] insertBuf = null;
started = true;
if (strLen == 0) return 0;
final byte[] insertStr;
final int insertLen;
if (caseInsensitiveEquals(insertEncoding, strEncoding)) {
insertStr = str;
insertLen = strLen;
} else {
Ptr insertLenP = new Ptr();
insertBuf = new byte[4096];
insertStr = allocateConvertedString(strEncoding, insertEncoding, str, 0, strLen, insertBuf, insertLenP);
insertLen = insertLenP.p;
if (insertStr == null) return -1;
}
int need = insertLen;
final int lastTranscodingIndex = numTranscoders - 1;
final Transcoding transcoding;
Buffer buf;
if (numTranscoders == 0) {
transcoding = null;
buf = inBuf;
} else if (elements[lastTranscodingIndex].transcoding.transcoder.compatibility.isEncoder()) {
transcoding = elements[lastTranscodingIndex].transcoding;
need += transcoding.readAgainLength;
if (need < insertLen) return -1;
if (lastTranscodingIndex == 0) {
buf = inBuf;
} else {
buf = elements[lastTranscodingIndex - 1];
}
} else {
transcoding = elements[lastTranscodingIndex].transcoding;
buf = elements[lastTranscodingIndex];
}
if (buf == null) {
buf = new Buffer();
buf.allocate(need);
} else if ((buf.bufEnd - buf.dataEnd) < need) {
System.arraycopy(buf.bytes, buf.dataStart, buf.bytes, buf.bufStart, buf.dataEnd - buf.dataStart);
buf.dataEnd = buf.dataStart + (buf.dataEnd - buf.dataStart);
buf.dataStart = buf.bufStart;
if ((buf.bufEnd - buf.dataEnd) < need) {
int s = (buf.dataEnd - buf.bufStart) + need;
if (need > s) return -1;
byte[] tmp = new byte[s];
System.arraycopy(buf.bytes, buf.bufStart, tmp, 0, s);
buf.bytes = tmp;
buf.dataStart = 0;
buf.dataEnd = buf.dataEnd - buf.bufStart;
buf.bufStart = 0;
buf.bufEnd = 0;
}
}
System.arraycopy(insertStr, 0, buf.bytes, buf.dataEnd, insertLen);
buf.dataEnd += insertLen;
if (transcoding != null && transcoding.transcoder.compatibility.isEncoder()) {
System.arraycopy(transcoding.readBuf, transcoding.recognizedLength, buf.bytes, buf.dataEnd, transcoding.readAgainLength);
buf.dataEnd = transcoding.readAgainLength;
transcoding.readAgainLength = 0;
}
return 0;
}
/* rb_econv_close */
public void close() {
for (int i = 0; i < numTranscoders; i++) {
elements[i].transcoding.close();
}
}
/* rb_econv_putbackable */
public int putbackable() {
return numTranscoders == 0 ? 0 : elements[0].transcoding.readAgainLength;
}
/* rb_econv_putback */
public void putback(byte[] bytes, int p, int n) {
if (numTranscoders == 0 || n == 0) return;
Transcoding transcoding = elements[0].transcoding;
System.arraycopy(transcoding.readBuf, transcoding.recognizedLength + transcoding.readAgainLength - n, bytes, p, n);
transcoding.readAgainLength -= n;
}
/* rb_econv_add_converter */
public boolean addConverter(byte[] source, byte[] destination, int n) {
if (started) return false;
TranscoderDB.Entry entry = TranscoderDB.getEntry(source, destination);
if (entry == null) return false;
Transcoder transcoder = entry.getTranscoder();
if (transcoder == null) return false;
addTranscoderAt(transcoder, n);
return true;
}
/* rb_econv_decorate_at */
boolean decorateAt(byte[] decorator, int n) {
return addConverter(NULL_STRING, decorator, n);
}
/* rb_econv_decorate_at_last */
boolean decorateAtFirst(byte[] decorator) {
if (numTranscoders == 0) return decorateAt(decorator, 0);
Transcoder transcoder = elements[0].transcoding.transcoder;
if (!decorator(transcoder.source, transcoder.destination) && transcoder.compatibility.isDecoder()) {
return decorateAt(decorator, 1);
}
return decorateAt(decorator, 0);
}
/* rb_econv_decorate_at_last */
boolean decorateAtLast(byte[] decorator) {
if (numTranscoders == 0) return decorateAt(decorator, 0);
Transcoder transcoder = elements[numTranscoders - 1].transcoding.transcoder;
if (!decorator(transcoder.source, transcoder.destination) && transcoder.compatibility.isDecoder()) {
return decorateAt(decorator, numTranscoders - 1);
}
return decorateAt(decorator, numTranscoders);
}
/* rb_econv_binmode */
private void binmode() {
Transcoder[] transcoders = new Transcoder[3];
int n = 0;
if ((flags & UNIVERSAL_NEWLINE_DECORATOR) != 0) {
TranscoderDB.Entry entry = TranscoderDB.getEntry(NULL_STRING, "universal_newline".getBytes());
if (entry.getTranscoder() != null) transcoders[n++] = entry.getTranscoder();
}
if ((flags & CRLF_NEWLINE_DECORATOR) != 0) {
TranscoderDB.Entry entry = TranscoderDB.getEntry(NULL_STRING, "crlf_newline".getBytes());
if (entry.getTranscoder() != null) transcoders[n++] = entry.getTranscoder();
}
if ((flags & CR_NEWLINE_DECORATOR) != 0) {
TranscoderDB.Entry entry = TranscoderDB.getEntry(NULL_STRING, "cr_newline".getBytes());
if (entry.getTranscoder() != null) transcoders[n++] = entry.getTranscoder();
}
int nTrans = numTranscoders;
int j = 0;
for (int i = 0; i < nTrans; i++) {
int k;
for (k = 0; k < n; k++) {
if (transcoders[k] == elements[i].transcoding.transcoder) break;
}
if (k == n) {
elements[j] = elements[i];
j++;
} else {
elements[i].transcoding.close();
numTranscoders
}
}
flags &= ~NEWLINE_DECORATOR_MASK;
}
/* econv_description, rb_econv_open_exc, make_econv_exception */
/* more_output_buffer */
/* make_replacement */
public int makeReplacement() {
if (replacementString != null) return 0;
byte[] insEnc = encodingToInsertOutput();
final byte[] replEnc;
final int len;
final byte[] replacement;
if (insEnc.length != 0) {
// Transcoding transcoding = lastTranscoding;
// Transcoder transcoder = transcoding.transcoder;
// Encoding enc = EncodingDB.getEncodings().get(transcoder.destination).getEncoding();
// get_replacement_character
if (caseInsensitiveEquals(insEnc, "UTF-8".getBytes())) {
len = 3;
replEnc = "UTF-8".getBytes();
replacement = new byte[] { (byte) 0xEF, (byte) 0xBF, (byte) 0xBD };
} else {
len = 1;
replEnc = "US-ASCII".getBytes();
replacement = new byte[] { '?' };
}
} else {
len = 1;
replEnc = NULL_STRING;
replacement = new byte[] { '?' };
}
replacementString = replacement;
replacementLength = len;
replacementEncoding = replEnc;
return 0;
}
/* rb_econv_set_replacement */
public int setReplacement(byte[] str, int p, int len, byte[] encname) {
byte[] encname2 = encodingToInsertOutput();
final byte[] str2;
final int p2 = 0;
final int len2;
if (caseInsensitiveEquals(encname, encname2)) {
str2 = new byte[len];
System.arraycopy(str, p, str2, 0, len);
len2 = len;
encname2 = encname;
} else {
Ptr len2p = new Ptr();
str2 = allocateConvertedString(encname, encname2, str, p, len, null, len2p);
if (str == null) return -1;
len2 = len2p.p;
}
replacementString = str2;
replacementLength = len2;
replacementEncoding = encname2;
return 0;
}
/* output_replacement_character */
int outputReplacementCharacter() {
if (makeReplacement() == -1) return -1;
if (insertOutput(replacementString, replacementLength, replacementEncoding) == -1) return -1;
return 0;
}
public String toStringFull() {
String s = "EConv " + new String(source) + " => " + new String(destination) + "\n";
s += " started: " + started + "\n";
s += " replacement string: " + (replacementString == null ? "null" : new String(replacementString, 0, replacementLength)) + "\n";
s += " replacement encoding: " + (replacementEncoding == null ? "null" : new String(replacementEncoding)) + "\n";
s += "\n";
for (int i = 0; i < numTranscoders; i++) {
s += " element " + i + ": " + elements[i].toString() + "\n";
}
s += "\n";
s += " lastTranscoding: " + lastTranscoding + "\n";
s += " last error: " + (lastError == null ? "null" : lastError.toString());
return s;
}
}
|
// $Id: MERGE2.java,v 1.23 2005/09/15 10:19:05 belaban Exp $
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.View;
import org.jgroups.stack.Protocol;
import org.jgroups.util.Promise;
import org.jgroups.util.Util;
import java.util.Properties;
import java.util.Vector;
/**
* Protocol to discover subgroups; e.g., existing due to a network partition (that healed). Example: group
* {p,q,r,s,t,u,v,w} is split into 3 subgroups {p,q}, {r,s,t,u} and {v,w}. This protocol will eventually send
* a MERGE event with the coordinators of each subgroup up the stack: {p,r,v}. Note that - depending on the time
* of subgroup discovery - there could also be 2 MERGE events, which first join 2 of the subgroups, and then the
* resulting group to the last subgroup. The real work of merging the subgroups into one larger group is done
* somewhere above this protocol (typically in the GMS protocol).<p>
* This protocol works as follows:
* <ul>
* <li>If coordinator: periodically retrieve the initial membership (using the FIND_INITIAL_MBRS event provided e.g.
* by PING or TCPPING protocols. This list contains {coord,addr} pairs.
* <li>If there is more than 1 coordinator:
* <ol>
* <li>Get all coordinators
* <li>Create a MERGE event with the list of coordinators as argument
* <li>Send the event up the stack
* </ol>
* </ul>
*
* <p>
*
* Requires: FIND_INITIAL_MBRS event from below<br>
* Provides: sends MERGE event with list of coordinators up the stack<br>
* @author Bela Ban, Oct 16 2001
*/
public class MERGE2 extends Protocol {
Address local_addr=null;
FindSubgroups task=null; // task periodically executing as long as we are coordinator
private final Object task_lock=new Object();
long min_interval=5000; // minimum time between executions of the FindSubgroups task
long max_interval=20000; // maximum time between executions of the FindSubgroups task
boolean is_coord=false;
final Promise find_promise=new Promise(); // to synchronize FindSubgroups.findInitialMembers() on
/** Use a new thread to send the MERGE event up the stack */
boolean use_separate_thread=false;
public String getName() {
return "MERGE2";
}
public long getMinInterval() {
return min_interval;
}
public void setMinInterval(long i) {
min_interval=i;
}
public long getMaxInterval() {
return max_interval;
}
public void setMaxInterval(long l) {
max_interval=l;
}
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("min_interval");
if(str != null) {
min_interval=Long.parseLong(str);
props.remove("min_interval");
}
str=props.getProperty("max_interval");
if(str != null) {
max_interval=Long.parseLong(str);
props.remove("max_interval");
}
if(min_interval <= 0 || max_interval <= 0) {
if(log.isErrorEnabled()) log.error("min_interval and max_interval have to be > 0");
return false;
}
if(max_interval <= min_interval) {
if(log.isErrorEnabled()) log.error("max_interval has to be greater than min_interval");
return false;
}
str=props.getProperty("use_separate_thread");
if(str != null) {
use_separate_thread=Boolean.valueOf(str).booleanValue();
props.remove("use_separate_thread");
}
if(props.size() > 0) {
log.error("MERGE2.setProperties(): the following properties are not recognized: " + props);
return false;
}
return true;
}
public Vector requiredDownServices() {
Vector retval=new Vector(1);
retval.addElement(new Integer(Event.FIND_INITIAL_MBRS));
return retval;
}
public void stop() {
is_coord=false;
stopTask();
}
/**
* This prevents the up-handler thread to be created, which is not needed in the protocol.
* DON'T REMOVE !
*/
public void startUpHandler() {
}
/**
* This prevents the down-handler thread to be created, which is not needed in the protocol.
* DON'T REMOVE !
*/
public void startDownHandler() {
}
public void up(Event evt) {
switch(evt.getType()) {
case Event.SET_LOCAL_ADDRESS:
local_addr=(Address)evt.getArg();
passUp(evt);
break;
case Event.FIND_INITIAL_MBRS_OK:
find_promise.setResult(evt.getArg());
passUp(evt); // could be needed by GMS
break;
default:
passUp(evt); // Pass up to the layer above us
break;
}
}
public void down(Event evt) {
Vector mbrs;
Address coord;
switch(evt.getType()) {
case Event.VIEW_CHANGE:
passDown(evt);
mbrs=((View)evt.getArg()).getMembers();
if(mbrs == null || mbrs.size() == 0 || local_addr == null) {
stopTask();
break;
}
coord=(Address)mbrs.elementAt(0);
if(coord.equals(local_addr)) {
is_coord=true;
startTask(); // start task if we became coordinator (doesn't start if already running)
}
else {
// if we were coordinator, but are no longer, stop task. this happens e.g. when we merge and someone
// else becomes the new coordinator of the merged group
if(is_coord) {
is_coord=false;
}
stopTask();
}
break;
default:
passDown(evt); // Pass on to the layer below us
break;
}
}
void startTask() {
synchronized(task_lock) {
if(task == null)
task=new FindSubgroups();
task.start();
}
}
void stopTask() {
synchronized(task_lock) {
if(task != null) {
task.stop(); // will cause timer to remove task from execution schedule
task=null;
}
}
}
/**
* Task periodically executing (if role is coordinator). Gets the initial membership and determines
* whether there are subgroups (multiple coordinators for the same group). If yes, it sends a MERGE event
* with the list of the coordinators up the stack
*/
private class FindSubgroups implements Runnable {
Thread thread=null;
public void start() {
if(thread == null || !thread.isAlive()) {
thread=new Thread(this, "MERGE2.FindSubgroups thread");
thread.setDaemon(true);
thread.start();
}
}
public void stop() {
if(thread != null) {
Thread tmp=thread;
thread=null;
tmp.interrupt(); // wakes up sleeping thread
find_promise.reset();
}
thread=null;
}
public void run() {
long interval;
Vector coords;
Vector initial_mbrs;
// if(log.isDebugEnabled()) log.debug("merge task started as I'm the coordinator");
while(thread != null && Thread.currentThread().equals(thread)) {
interval=computeInterval();
Util.sleep(interval);
if(thread == null) break;
initial_mbrs=findInitialMembers();
if(thread == null) break;
if(log.isDebugEnabled()) log.debug("initial_mbrs=" + initial_mbrs);
coords=detectMultipleCoordinators(initial_mbrs);
if(coords != null && coords.size() > 1) {
if(log.isDebugEnabled())
log.debug("found multiple coordinators: " + coords + "; sending up MERGE event");
final Event evt=new Event(Event.MERGE, coords);
if(use_separate_thread) {
Thread merge_notifier=new Thread() {
public void run() {
passUp(evt);
}
};
merge_notifier.setDaemon(true);
merge_notifier.setName("merge notifier thread");
merge_notifier.start();
}
else {
passUp(evt);
}
}
else {
if(trace)
log.trace("didn't find multiple coordinators in " + initial_mbrs + ", no need for merge");
}
}
if(trace)
log.trace("MERGE2.FindSubgroups thread terminated");
}
/**
* Returns a random value within [min_interval - max_interval]
*/
long computeInterval() {
return min_interval + Util.random(max_interval - min_interval);
}
/**
* Returns a list of PingRsp pairs.
*/
Vector findInitialMembers() {
PingRsp tmp=new PingRsp(local_addr, local_addr, true);
find_promise.reset();
passDown(Event.FIND_INITIAL_MBRS_EVT);
Vector retval=(Vector)find_promise.getResult(0); // wait indefinitely until response is received
if(retval != null && is_coord && local_addr != null && !retval.contains(tmp))
retval.add(tmp);
return retval;
}
/**
* Finds out if there is more than 1 coordinator in the initial_mbrs vector (contains PingRsp elements).
* @param initial_mbrs A list of PingRsp pairs
* @return Vector A list of the coordinators (Addresses) found. Will contain just 1 element for a correct
* membership, and more than 1 for multiple coordinators
*/
Vector detectMultipleCoordinators(Vector initial_mbrs) {
Vector ret=new Vector(11);
PingRsp rsp;
Address coord;
if(initial_mbrs == null) return null;
for(int i=0; i < initial_mbrs.size(); i++) {
rsp=(PingRsp)initial_mbrs.elementAt(i);
if(!rsp.is_server)
continue;
coord=rsp.getCoordAddress();
if(!ret.contains(coord))
ret.addElement(coord);
}
return ret;
}
}
}
|
// $Id: TUNNEL.java,v 1.45 2007/09/27 10:21:47 vlada Exp $
package org.jgroups.protocols;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.annotations.GuardedBy;
import org.jgroups.stack.RouterStub;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.Util;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TUNNEL extends TP {
private String router_host=null;
private int router_port=0;
private RouterStub stub;
long reconnect_interval=5000; /** time to wait in ms between reconnect attempts */
@GuardedBy("reconnectorLock")
private Future reconnectorFuture=null;
private final Lock reconnectorLock=new ReentrantLock();
public TUNNEL() {}
public String toString() {
return "Protocol TUNNEL(local_addr=" + local_addr + ')';
}
public String getName() {
return "TUNNEL";
}
public void init() throws Exception {
super.init();
if(stack != null && stack.timer != null)
timer=stack.timer;
else
throw new Exception("TUNNEL.init(): timer cannot be retrieved from protocol stack");
}
public void start() throws Exception {
//loopback turned on is mandatory
loopback = true;
stub = new RouterStub(router_host,router_port,bind_addr);
stub.setConnectionListener(new StubConnectionListener());
local_addr=stub.getLocalAddress();
if(additional_data != null && local_addr instanceof IpAddress)
((IpAddress)local_addr).setAdditionalData(additional_data);
super.start();
}
public void stop() {
super.stop();
teardownTunnel();
local_addr=null;
}
/** Setup the Protocol instance acording to the configuration string */
public boolean setProperties(Properties props) {
String str;
super.setProperties(props);
str=props.getProperty("router_host");
if(str != null) {
router_host=str;
props.remove("router_host");
}
str=props.getProperty("router_port");
if(str != null) {
router_port=Integer.parseInt(str);
props.remove("router_port");
}
if(log.isDebugEnabled()) {
log.debug("router_host=" + router_host + ";router_port=" + router_port);
}
if(router_host == null || router_port == 0) {
if(log.isErrorEnabled()) {
log.error("both router_host and router_port have to be set !");
return false;
}
}
str=props.getProperty("reconnect_interval");
if(str != null) {
reconnect_interval=Long.parseLong(str);
props.remove("reconnect_interval");
}
if(!props.isEmpty()) {
StringBuffer sb=new StringBuffer();
for(Enumeration e=props.propertyNames(); e.hasMoreElements();) {
sb.append(e.nextElement().toString());
if(e.hasMoreElements()) {
sb.append(", ");
}
}
if(log.isErrorEnabled()) log.error("The following properties are not recognized: " + sb);
return false;
}
return true;
}
/** Tears the TCP connection to the router down */
void teardownTunnel() {
stopReconnecting();
stub.disconnect();
}
public Object handleDownEvent(Event evt) {
Object retEvent=super.handleDownEvent(evt);
switch(evt.getType()) {
case Event.CONNECT:
case Event.CONNECT_WITH_STATE_TRANSFER:
try {
stub.connect(channel_name);
}
catch(Exception e) {
if(log.isErrorEnabled())
log.error("failed connecting to GossipRouter at " + router_host + ":" + router_port);
}
break;
case Event.DISCONNECT:
teardownTunnel();
break;
}
return retEvent;
}
private void startReconnecting() {
reconnectorLock.lock();
try {
if(reconnectorFuture == null || reconnectorFuture.isDone()) {
final Runnable reconnector = new Runnable(){
public void run() {
try{
stub.connect(channel_name);
}catch(Exception ex){
if(log.isTraceEnabled())
log.trace("failed reconnecting", ex);
}
}
};
reconnectorFuture=timer.scheduleWithFixedDelay(reconnector, 0, reconnect_interval, TimeUnit.MILLISECONDS);
}
}
finally {
reconnectorLock.unlock();
}
}
private void stopReconnecting() {
reconnectorLock.lock();
try {
if(reconnectorFuture != null) {
reconnectorFuture.cancel(true);
reconnectorFuture=null;
}
}
finally {
reconnectorLock.unlock();
}
}
private class StubConnectionListener implements RouterStub.ConnectionListener{
private volatile int currentState = RouterStub.STATUS_DISCONNECTED;
public void connectionStatusChange(int newState) {
if(currentState == RouterStub.STATUS_CONNECTED && newState == RouterStub.STATUS_CONNECTION_LOST){
startReconnecting();
}
else if(currentState != RouterStub.STATUS_CONNECTED && newState == RouterStub.STATUS_CONNECTED){
stopReconnecting();
Thread receiver = new Thread(Util.getGlobalThreadGroup(), new TunnelReceiver(), "TUNNEL receiver");
receiver.setDaemon(true);
receiver.start();
}
currentState = newState;
}
}
private class TunnelReceiver implements Runnable {
public void run() {
while(stub.isConnected()){
Address dest = null;
Address src = null;
int len;
byte[] data = null;
DataInputStream input = null;
try{
input = stub.getInputStream();
dest = Util.readAddress(input);
len = input.readInt();
if(len > 0){
data = new byte[len];
input.readFully(data, 0, len);
receive(dest, src, data, 0, len);
}
}catch(SocketException se){
//if(log.isWarnEnabled()) log.warn("failure in TUNNEL receiver thread", se);
}catch(IOException ioe){
//if(log.isWarnEnabled()) log.warn("failure in TUNNEL receiver thread", ioe);
}catch(Exception e){
if(log.isWarnEnabled())
log.warn("failure in TUNNEL receiver thread", e);
}
}
}
}
public void sendToAllMembers(byte[] data, int offset, int length) throws Exception {
stub.sendToAllMembers(data, offset, length);
}
public void sendToSingleMember(Address dest, byte[] data, int offset, int length) throws Exception {
stub.sendToSingleMember(dest, data, offset, length);
}
public String getInfo() {
if(stub!=null)
return stub.toString();
else
return "RouterStub not yet initialized";
}
public void postUnmarshalling(Message msg, Address dest, Address src, boolean multicast) {
msg.setDest(dest);
}
public void postUnmarshallingList(Message msg, Address dest, boolean multicast) {
msg.setDest(dest);
}
}
|
/*
* $Id: V3Voter.java,v 1.37 2007-04-11 22:01:44 smorabito Exp $
*/
package org.lockss.poller.v3;
import java.io.*;
import java.net.MalformedURLException;
import java.security.*;
import java.util.*;
import org.lockss.app.*;
import org.lockss.config.*;
import org.lockss.daemon.CachedUrlSetHasher;
import org.lockss.hasher.*;
import org.lockss.plugin.*;
import org.lockss.poller.*;
import org.lockss.poller.v3.V3Serializer.PollSerializerException;
import org.lockss.protocol.*;
import org.lockss.protocol.psm.*;
import org.lockss.repository.RepositoryNode;
import org.lockss.scheduler.*;
import org.lockss.scheduler.Schedule.*;
import org.lockss.util.*;
/**
* <p>Represents a voter in a V3 poll.</p>
*
* <p>State is maintained in a V3VoterState object, which is periodically
* serialized to disk so that polls may be resumed in case the daemon exits
* before the poll is over.</p>
*/
public class V3Voter extends BasePoll {
public static final int STATUS_INITIALIZED = 0;
public static final int STATUS_ACCEPTED_POLL = 1;
public static final int STATUS_HASHING = 2;
public static final int STATUS_VOTED = 3;
public static final int STATUS_NO_TIME = 4;
public static final int STATUS_COMPLETE = 5;
public static final int STATUS_EXPIRED = 6;
public static final int STATUS_ERROR = 7;
public static final String[] STATUS_STRINGS =
{
"Initialized", "Accepted Poll", "Hashing", "Voted",
"No Time Available", "Complete", "Expired w/o Voting", "Error"
};
static String PREFIX = Configuration.PREFIX + "poll.v3.";
/** The minimum number of peers to select for a nomination message.
* If there are fewer than this number of peers available to nominate,
* an empty nomination message will be sent. */
public static final String PARAM_MIN_NOMINATION_SIZE =
PREFIX + "minNominationSize";
public static final int DEFAULT_MIN_NOMINATION_SIZE = 1;
/** The minimum number of peers to select for a nomination message. */
public static final String PARAM_MAX_NOMINATION_SIZE =
PREFIX + "maxNominationSize";
public static final int DEFAULT_MAX_NOMINATION_SIZE = 5;
/** The maximum allowable number of simultaneous V3 Voters */
public static final String PARAM_MAX_SIMULTANEOUS_V3_VOTERS =
PREFIX + "maxSimultaneousV3Voters";
public static final int DEFAULT_MAX_SIMULTANEOUS_V3_VOTERS = 60;
/**
* If false, do not serve any repairs via V3.
*/
public static final String PARAM_ALLOW_V3_REPAIRS =
PREFIX + "allowV3Repairs";
public static final boolean DEFAULT_ALLOW_V3_REPAIRS = true;
/**
* Directory in which to store message data.
*/
public static final String PARAM_V3_MESSAGE_REL_DIR =
V3Poller.PARAM_V3_MESSAGE_REL_DIR;
public static final String DEFAULT_V3_MESSAGE_REL_DIR =
V3Poller.DEFAULT_V3_MESSAGE_REL_DIR;
/**
* Extra time added to the poll deadline (as sent by the poller) to
* wait for a receipt message.
*/
public static final String PARAM_RECEIPT_PADDING = PREFIX + "receiptPadding";
public static final long DEFAULT_RECEIPT_PADDING = 1000 * 60 * 10; // 10m
private PsmInterp stateMachine;
private VoterUserData voterUserData;
private LockssRandom theRandom = new LockssRandom();
private LockssDaemon theDaemon;
private V3VoterSerializer pollSerializer;
private PollManager pollManager;
private IdentityManager idManager;
private boolean continuedPoll = false;
private int nomineeCount;
private File stateDir;
private int blockErrorCount = 0;
private int maxBlockErrorCount = V3Poller.DEFAULT_MAX_BLOCK_ERROR_COUNT;
// Task used to reserve time for hashing at the start of the poll.
// This task is cancelled before the real hash is scheduled.
private SchedulableTask task;
private static final Logger log = Logger.getLogger("V3Voter");
/**
* <p>Upon receipt of a request to participate in a poll, create a new
* V3Voter. The voter will not start running until {@link #startPoll()}
* is called by {@link org.lockss.poller.v3.V3PollFactory}</p>
*/
public V3Voter(LockssDaemon daemon, V3LcapMessage msg)
throws V3Serializer.PollSerializerException {
this.theDaemon = daemon;
long padding =
CurrentConfig.getTimeIntervalParam(V3Voter.PARAM_RECEIPT_PADDING,
V3Voter.DEFAULT_RECEIPT_PADDING);
long duration = msg.getDuration() + padding;
log.debug3("Creating V3 Voter for poll: " + msg.getKey() +
"; duration=" + duration);
pollSerializer = new V3VoterSerializer(theDaemon);
// Determine the proper location for the V3 message dir.
List dSpaceList =
CurrentConfig.getList(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST);
String relPluginPath =
CurrentConfig.getParam(PARAM_V3_MESSAGE_REL_DIR,
DEFAULT_V3_MESSAGE_REL_DIR);
maxBlockErrorCount =
CurrentConfig.getIntParam(V3Poller.PARAM_MAX_BLOCK_ERROR_COUNT,
V3Poller.DEFAULT_MAX_BLOCK_ERROR_COUNT);
if (dSpaceList == null || dSpaceList.size() == 0) {
log.error(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST +
" not specified, not configuring V3 message dir.");
} else {
stateDir = new File((String)dSpaceList.get(0), relPluginPath);
}
if (stateDir == null ||
(!stateDir.exists() && !stateDir.mkdir()) ||
!stateDir.canWrite()) {
throw new IllegalArgumentException("Configured V3 data directory " +
stateDir +
" does not exist or cannot be " +
"written to.");
}
try {
this.voterUserData = new VoterUserData(new PollSpec(msg), this,
msg.getOriginatorId(),
msg.getKey(),
duration,
msg.getHashAlgorithm(),
msg.getPollerNonce(),
makeVoterNonce(),
msg.getEffortProof(),
stateDir);
voterUserData.setVoteDeadline(TimeBase.nowMs() + msg.getVoteDuration());
} catch (IOException ex) {
log.critical("IOException while trying to create VoterUserData: ", ex);
stopPoll();
}
this.idManager = theDaemon.getIdentityManager();
this.pollManager = daemon.getPollManager();
int min = CurrentConfig.getIntParam(PARAM_MIN_NOMINATION_SIZE,
DEFAULT_MIN_NOMINATION_SIZE);
int max = CurrentConfig.getIntParam(PARAM_MAX_NOMINATION_SIZE,
DEFAULT_MAX_NOMINATION_SIZE);
if (min > max) {
throw new IllegalArgumentException("Impossible nomination size range: "
+ (max - min));
} else if (min == max) {
log.debug2("Minimum nominee size is same as maximum nominee size: " +
min);
nomineeCount = min;
} else {
int r = theRandom.nextInt(max - min);
nomineeCount = min + r;
}
log.debug2("Will choose " + nomineeCount
+ " outer circle nominees to send to poller");
stateMachine = makeStateMachine(voterUserData);
checkpointPoll();
}
/**
* <p>Restore a V3Voter from a previously saved poll. This method is called
* by {@link org.lockss.poller.PollManager} when the daemon starts up if a
* serialized voter is found.</p>
*/
public V3Voter(LockssDaemon daemon, File pollDir)
throws V3Serializer.PollSerializerException {
this.theDaemon = daemon;
this.pollSerializer = new V3VoterSerializer(theDaemon, pollDir);
this.voterUserData = pollSerializer.loadVoterUserData();
this.pollManager = daemon.getPollManager();
this.continuedPoll = true;
// Restore transient state.
PluginManager plugMgr = theDaemon.getPluginManager();
CachedUrlSet cus = plugMgr.findCachedUrlSet(voterUserData.getAuId());
if (cus == null) {
throw new NullPointerException("CUS for AU " + voterUserData.getAuId() +
" is null!");
}
// Restore transient state
voterUserData.setCachedUrlSet(cus);
voterUserData.setPollSpec(new PollSpec(cus, Poll.V3_POLL));
voterUserData.setVoter(this);
stateMachine = makeStateMachine(voterUserData);
}
private PsmInterp makeStateMachine(final VoterUserData ud) {
PsmMachine machine =
VoterStateMachineFactory.getMachine(getVoterActionsClass());
PsmInterp interp = new PsmInterp(machine, ud);
interp.setCheckpointer(new PsmInterp.Checkpointer() {
public void checkpoint(PsmInterpStateBean resumeStateBean) {
voterUserData.setPsmState(resumeStateBean);
checkpointPoll();
}
});
return interp;
}
/**
* Provides a default no-arg constructor to be used for unit testing.
*/
protected V3Voter() {
}
/**
* <p>Reserve enough schedule time to hash our content and send our vote.</p>
*
* @return True if time could be scheduled, false otherwise.
*/
public boolean reserveScheduleTime() {
// XXX: We need to reserve some padding for the estimated time it will
// take to send the message. 'estimatedHashDuration' is probably way
// too much for this, but a better estimate would require taking into
// account the number of URLs and versions that we expect to hash, since
// the message size is proportional to the number of VoteBlock.Versions
long voteDeadline = voterUserData.getVoteDeadline();
long estimatedHashDuration = getCachedUrlSet().estimatedHashDuration();
long now = TimeBase.nowMs();
// Ensure the vote deadline has not already passed.
if (voteDeadline < now) {
log.warning("In poll " + getKey() + " called by peer "
+ voterUserData.getPollerId()
+ ", vote deadline (" + voteDeadline + ") has already "
+ "passed! Can't reserve schedule time.");
return false;
}
if (estimatedHashDuration > (voteDeadline - now)) {
log.warning("In poll " + getKey() + " called by peer " +
voterUserData.getPollerId() +
", my estimated hash duration (" + estimatedHashDuration +
"ms) is too long to complete within the voting period (" +
(voteDeadline - now) + "ms)");
return false;
}
Deadline earliestStart = Deadline.at(now + estimatedHashDuration);
Deadline latestFinish =
Deadline.at(voterUserData.getVoteDeadline() - estimatedHashDuration);
log.debug("Voter " + getKey() + ": Earliest Start = " +
earliestStart + "; Latest Finish = " + latestFinish);
TaskCallback tc = new TaskCallback() {
public void taskEvent(SchedulableTask task, EventType type) {
// do nothing... yet!
}
};
// Keep a hold of the task we're scheduling.
this.task = new StepTask(earliestStart, latestFinish,
estimatedHashDuration,
tc, this) {
public int step(int n) {
// finish immediately, in case we start running
setFinished();
return n;
}
};
boolean suc = theDaemon.getSchedService().scheduleTask(task);
if (!suc) {
String msg = "No time for V3 Voter in poll " + getKey() + ". " +
" Requested time for step task with earliest start at " +
earliestStart +", latest finish at " + latestFinish + ", " +
"with an estimated hash duration of " + estimatedHashDuration +
"ms as of " + TimeBase.nowDate();
voterUserData.setErrorDetail(msg);
log.warning(msg);
}
return suc;
}
/**
* <p>Start the V3Voter running and participate in the poll. Called by
* {@link org.lockss.poller.v3.V3PollFactory} when a vote request message
* has been received, and by {@link org.lockss.poller.PollManager} when
* restoring serialized voters.</p>
*/
public void startPoll() {
log.debug("Starting poll " + voterUserData.getPollKey());
Deadline pollDeadline = null;
if (!continuedPoll) {
// Skip deadline sanity check if this is a restored poll.
pollDeadline = Deadline.at(voterUserData.getDeadline());
} else {
pollDeadline = Deadline.restoreDeadlineAt(voterUserData.getDeadline());
}
// If this poll has already expired, don't start it.
if (pollDeadline.expired()) {
log.info("Not restoring expired voter for poll " +
voterUserData.getPollKey());
stopPoll(STATUS_EXPIRED);
return;
}
// First, see if we have time to participate. If not, there's no
// point in going on.
if (reserveScheduleTime()) {
long estimatedHashTime = getCachedUrlSet().estimatedHashDuration();
long voteDeadline = voterUserData.getVoteDeadline();
if (voteDeadline >= pollDeadline.getExpirationTime()) {
log.warning("Voting deadline (" + voteDeadline + ") is later than " +
"the poll deadline (" + pollDeadline.getExpirationTime() +
"). Can't participate in poll " + getKey());
stopPoll(STATUS_EXPIRED);
return;
}
log.debug("Found enough time to participate in poll " + getKey());
} else {
log.warning("Not enough time found to participate in poll " + getKey());
stopPoll(STATUS_NO_TIME);
return;
}
// Register a callback for the end of the poll.
TimerQueue.schedule(pollDeadline, new PollTimerCallback(), this);
// Register a callback for the end of the voting period. We must have
// voted by this time, or we can't participate.
TimerQueue.schedule(Deadline.at(voterUserData.getVoteDeadline()),
new TimerQueue.Callback() {
public void timerExpired(Object cookie) {
// In practice, we must prevent this from happening. Unfortunately,
// due to the nature of the scheduler and the wide variety of machines
// in the field, it is quite possible for us to still be hashing when
// the vote deadline has arrived.
// It's the poller's responsibility to ensure that it compensates for
// slow machines by padding the vote deadline as much as necessary to
// compensate for slow machines.
if (!voterUserData.hashingDone()) {
log.warning("Vote deadline has passed before my hashing was done " +
"in poll " + getKey() + ". Stopping the poll.");
stopPoll(V3Voter.STATUS_NO_TIME);
}
}
}, this);
// Resume or start the state machine running.
if (continuedPoll) {
try {
stateMachine.resume(voterUserData.getPsmState());
} catch (PsmException e) {
log.warning("Error resuming poll.", e);
abortPoll();
}
} else {
try {
stateMachine.start();
} catch (PsmException e) {
log.warning("Error starting poll.", e);
abortPoll();
}
}
}
/**
* Stop the poll and tell the {@link PollManager} to let go of us.
*
* @param status The final status code of the poll, for the status table.
*/
public void stopPoll(final int status) {
if (voterUserData.isPollActive()) {
voterUserData.setActivePoll(false);
} else {
return;
}
if (task != null && !task.isExpired()) {
log.debug2("Cancelling poll time reservation task");
task.cancel();
}
voterUserData.setStatus(status);
// Clean up after the serializer
pollSerializer.closePoll();
pollManager.closeThePoll(voterUserData.getPollKey());
log.debug2("Closed poll " + voterUserData.getPollKey() + " with status " +
getStatusString() );
release();
}
/**
* Stop the poll with STATUS_COMPLETE.
*/
public void stopPoll() {
stopPoll(STATUS_COMPLETE);
}
/**
* Stop the poll with STATUS_ERROR.
*/
private void abortPoll() {
stopPoll(STATUS_ERROR);
}
/**
* Generate a random nonce.
*
* @return A random array of 20 bytes.
*/
private byte[] makeVoterNonce() {
byte[] secret = new byte[20];
theRandom.nextBytes(secret);
return secret;
}
private Class getVoterActionsClass() {
return VoterActions.class;
}
/**
* Send a message to the poller.
*/
void sendMessageTo(V3LcapMessage msg, PeerIdentity id)
throws IOException {
pollManager.sendMessageTo(msg, id);
}
/**
* Handle an incoming V3LcapMessage.
*/
public void receiveMessage(LcapMessage message) {
// It's quite possible to receive a message after we've decided
// to close the poll, but before the PollManager knows we're closed.
if (voterUserData.isPollCompleted()) return;
V3LcapMessage msg = (V3LcapMessage)message;
PeerIdentity sender = msg.getOriginatorId();
PsmMsgEvent evt = V3Events.fromMessage(msg);
log.debug3("Received message: " + message.getOpcodeString() + " " + message);
try {
stateMachine.handleEvent(evt);
} catch (PsmException e) {
log.warning("State machine error", e);
abortPoll();
}
// Finally, clean up after the V3LcapMessage
msg.delete();
}
/**
* Generate a list of outer circle nominees.
*/
public void nominatePeers() {
// XXX: 'allPeers' should probably contain only peers that have agreed with
// us in the past for this au.
Collection allPeers = idManager.getTcpPeerIdentities();
allPeers.remove(voterUserData.getPollerId()); // Never nominate the poller
if (nomineeCount <= allPeers.size()) {
Collection nominees =
CollectionUtil.randomSelection(allPeers, nomineeCount);
// VoterUserData expects the collection to be KEYS, not PeerIdentities.
ArrayList nomineeStrings = new ArrayList();
for (Iterator iter = nominees.iterator(); iter.hasNext(); ) {
PeerIdentity id = (PeerIdentity)iter.next();
nomineeStrings.add(id.getIdString());
}
voterUserData.setNominees(nomineeStrings);
log.debug2("Nominating the following peers: " + nomineeStrings);
} else {
log.warning("Not enough peers to nominate. Need " + nomineeCount +
", only know about " + allPeers.size());
}
checkpointPoll();
}
/**
* Create an array of byte arrays containing hasher initializer bytes for
* this voter. The result will be an array of two byte arrays: The first
* has no initializing bytes, and will be used for the plain hash. The
* second is constructed by concatenating the poller nonce and voter nonce,
* and will be used for the challenge hash.
*
* @return Block hasher initialization bytes.
*/
private byte[][] initHasherByteArrays() {
return new byte[][] {
{}, // Plain Hash
ByteArray.concat(voterUserData.getPollerNonce(),
voterUserData.getVoterNonce()) // Challenge Hash
};
}
/**
* Create the message digesters for this voter's hasher -- one for
* the plain hash, one for the challenge hash.
*
* @return An array of MessageDigest objects to be used by the BlockHasher.
*/
private MessageDigest[] initHasherDigests() throws NoSuchAlgorithmException {
String hashAlg = voterUserData.getHashAlgorithm();
if (hashAlg == null) {
hashAlg = LcapMessage.DEFAULT_HASH_ALGORITHM;
}
return new MessageDigest[] {
MessageDigest.getInstance(hashAlg),
MessageDigest.getInstance(hashAlg)
};
}
/**
* Schedule a hash.
*/
boolean generateVote() throws NoSuchAlgorithmException {
log.debug("Scheduling vote hash for poll " + voterUserData.getPollKey());
CachedUrlSetHasher hasher = new BlockHasher(voterUserData.getCachedUrlSet(),
initHasherDigests(),
initHasherByteArrays(),
new BlockEventHandler());
HashService hashService = theDaemon.getHashService();
Deadline hashDeadline = task.getLatestFinish();
// Cancel the old task.
task.cancel();
// Schedule the hash using the old task's latest finish as the deadline.
boolean scheduled =
hashService.scheduleHash(hasher, hashDeadline,
new HashingCompleteCallback(), null);
if (scheduled) {
log.debug("Successfully scheduled time for vote in poll " +
getKey());
} else {
log.debug("Unable to schedule time for vote. Dropping " +
"out of poll " + getKey());
}
return scheduled;
}
/**
* Called by the HashService callback when hashing for this CU is
* complete.
*/
public void hashComplete() {
log.debug("Hashing complete for poll " + voterUserData.getPollKey());
// If we've received a vote request, send our vote right away. Otherwise,
// wait for a vote request.
voterUserData.hashingDone(true);
try {
if (voterUserData.voteRequested()) {
stateMachine.handleEvent(V3Events.evtReadyToVote);
} else {
stateMachine.handleEvent(V3Events.evtWaitVoteRequest);
}
} catch (PsmException e) {
log.warning("State machine error", e);
abortPoll();
}
}
/*
* Append the results of the block hasher to the VoteBlocks for this
* voter.
*
* Called by the BlockHasher's event handler callback when hashing is complete
* for one block.
*/
public void blockHashComplete(HashBlock block) {
// Add each hash block version to this vote block.
VoteBlock vb = new VoteBlock(block.getUrl());
Iterator hashVersionIter = block.versionIterator();
while(hashVersionIter.hasNext()) {
HashBlock.Version ver = (HashBlock.Version)hashVersionIter.next();
byte[] plainDigest = ver.getHashes()[0];
byte[] challengeDigest = ver.getHashes()[1];
vb.addVersion(ver.getFilteredOffset(),
ver.getFilteredLength(),
ver.getUnfilteredOffset(),
ver.getUnfilteredLength(),
plainDigest,
challengeDigest);
}
// Add this vote block to our hash block container.
VoteBlocks blocks = voterUserData.getVoteBlocks();
try {
blocks.addVoteBlock(vb);
} catch (IOException ex) {
log.error("Unexpected IO Exception trying to add vote block " +
vb.getUrl() + " in poll " + getKey(), ex);
if (++blockErrorCount > maxBlockErrorCount) {
log.critical("Too many errors while trying to create my vote blocks, " +
"aborting participation in poll " + getKey());
abortPoll();
}
}
}
public void setMessage(LcapMessage msg) {
voterUserData.setPollMessage(msg);
}
public long getCreateTime() {
return voterUserData.getCreateTime();
}
public PeerIdentity getCallerID() {
return voterUserData.getPollerId();
}
public File getStateDir() {
return pollSerializer.pollDir;
}
// Not used by V3.
protected boolean isErrorState() {
return false;
}
// Not used by V3.
public boolean isMyPoll() {
// Always return false
return false;
}
public PollSpec getPollSpec() {
return voterUserData.getPollSpec();
}
public CachedUrlSet getCachedUrlSet() {
return voterUserData.getCachedUrlSet();
}
public int getVersion() {
return voterUserData.getPollVersion();
}
public LcapMessage getMessage() {
return voterUserData.getPollMessage();
}
public String getKey() {
return voterUserData.getPollKey();
}
public Deadline getDeadline() {
return Deadline.restoreDeadlineAt(voterUserData.getDeadline());
}
public Deadline getVoteDeadline() {
return Deadline.restoreDeadlineAt(voterUserData.getVoteDeadline());
}
public long getDuration() {
return voterUserData.getDuration();
}
public byte[] getPollerNonce() {
return voterUserData.getPollerNonce();
}
public byte[] getVoterNonce() {
return voterUserData.getVoterNonce();
}
public PollTally getVoteTally() {
throw new UnsupportedOperationException("V3Voter does not have a tally.");
}
private class HashingCompleteCallback implements HashService.Callback {
/**
* Called when the timer expires or hashing is complete.
*
* @param cookie data supplied by caller to schedule()
*/
public void hashingFinished(CachedUrlSet cus, Object cookie,
CachedUrlSetHasher hasher, Exception e) {
if (e == null) {
hashComplete();
} else {
log.warning("Hash failed : " + e.getMessage(), e);
abortPoll();
}
}
}
private class BlockEventHandler implements BlockHasher.EventHandler {
public void blockStart(HashBlock block) {
log.debug2("Poll " + getKey() + ": Starting hash for block "
+ block.getUrl());
}
public void blockDone(HashBlock block) {
log.debug2("Poll " + getKey() + ": Ending hash for block "
+ block.getUrl());
blockHashComplete(block);
}
}
public int getType() {
return Poll.V3_POLL;
}
public LockssApp getLockssDaemon() {
return theDaemon;
}
public ArchivalUnit getAu() {
return voterUserData.getCachedUrlSet().getArchivalUnit();
}
public PeerIdentity getPollerId() {
return voterUserData.getPollerId();
}
public boolean isPollActive() {
return voterUserData.isPollActive();
}
public boolean isPollCompleted() {
return voterUserData.isPollCompleted();
}
public VoterUserData getVoterUserData() {
return voterUserData;
}
public String getStatusString() {
return V3Voter.STATUS_STRINGS[voterUserData.getStatus()];
}
IdentityManager getIdentityManager() {
return this.idManager;
}
/**
* Returns true if we will serve a repair to the given peer for the
* given AU and URL.
*/
boolean serveRepairs(PeerIdentity pid, ArchivalUnit au, String url) {
try {
RepositoryNode node = AuUtil.getRepositoryNode(au, url);
boolean previousAgreement = node.hasAgreement(pid);
if (previousAgreement) {
log.debug("Previous agreement found for peer " + pid + " on URL "
+ url);
} else {
log.debug("No previous agreement found for peer " + pid + " on URL "
+ url);
}
boolean allowRepairs =
CurrentConfig.getBooleanParam(PARAM_ALLOW_V3_REPAIRS,
DEFAULT_ALLOW_V3_REPAIRS);
return(previousAgreement && allowRepairs);
} catch (MalformedURLException ex) {
// Log the error, but certainly don't serve the repair.
log.error("serveRepairs: The URL " + url + " appears to be malformed. "
+ "Cannot serve repairs for this URL.");
return false;
}
}
/**
* Checkpoint the current state of the voter.
*/
void checkpointPoll() {
try {
pollSerializer.saveVoterUserData(voterUserData);
} catch (PollSerializerException ex) {
log.warning("Unable to save voter state.");
}
}
private class PollTimerCallback implements TimerQueue.Callback {
/**
* Called when the timer for this poll expires.
*
* @param cookie data supplied by caller to schedule()
*/
public void timerExpired(Object cookie) {
stopPoll();
}
public String toString() {
return "V3 Voter " + getKey();
}
}
/**
* Release unneeded resources.
*/
public void release() {
voterUserData.release();
stateDir = null;
task = null;
pollManager = null;
idManager = null;
pollSerializer = null;
stateMachine = null;
theDaemon = null;
}
}
|
package org.mapyrus.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.ScrollPane;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.URL;
import java.util.concurrent.LinkedBlockingQueue;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import org.mapyrus.Constants;
import org.mapyrus.ContextStack;
import org.mapyrus.FileOrURL;
import org.mapyrus.ImageSelection;
import org.mapyrus.Interpreter;
import org.mapyrus.MapyrusException;
import org.mapyrus.MapyrusMessages;
import org.mapyrus.Mutex;
/**
* Mapyrus GUI, allowing user to edit and run commands and see the output on the screen.
*/
public class MapyrusFrame implements MapyrusEventListener
{
/*
* Font for command input and output.
*/
private static Font m_fixedFont = new Font("Monospaced", Font.PLAIN, 12);
private Mutex m_mutex;
private JFrame m_frame;
private MapyrusEditorPanel m_editorPanel;
private JTextArea m_outputTextArea;
private Thread m_outputThread;
private JPanel m_displayPanel;
private LinkedBlockingQueue<Integer> m_actionQueue = null;
private Thread m_actionThread;
private BufferedImage m_displayImage;
private File m_lastOpenedDirectory;
public MapyrusFrame(String []filenames)
{
setLookAndFeel();
createActionQueue();
/*
* Create frame maximised to fill the whole screen.
*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
m_frame = new JFrame(Constants.PROGRAM_NAME + " " + Constants.getVersion());
m_frame.setPreferredSize(screenSize);
m_mutex = new Mutex();
m_mutex.lock();
m_frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
});
Container contentPane = m_frame.getContentPane();
contentPane.setLayout(new BorderLayout());
/*
* Add menubar and menu options.
*/
MapyrusMenuBar menuBar = new MapyrusMenuBar();
menuBar.addListener(this);
contentPane.add(menuBar, BorderLayout.NORTH);
/*
* Add display panel, toolbar, text editor panel, output panel.
*/
JSplitPane splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
JSplitPane splitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
m_displayPanel = new JPanel(){
static final long serialVersionUID = 0x3302;
public void paintComponent(Graphics g)
{
/*
* Double-buffering. Redisplay image that Mapyrus has drawn.
*/
super.paintComponent(g);
if (m_displayPanel != null && m_displayImage != null)
g.drawImage(m_displayImage, 0, 0, null);
}
};
m_displayPanel.setPreferredSize(screenSize);
splitPane1.add(m_displayPanel);
JPanel toolBarAndEditorPanel = new JPanel();
toolBarAndEditorPanel.setLayout(new BorderLayout());
MapyrusToolBar toolBar = new MapyrusToolBar();
toolBar.addListener(this);
toolBarAndEditorPanel.add(toolBar, BorderLayout.NORTH);
m_editorPanel = new MapyrusEditorPanel();
m_editorPanel.setFont(m_fixedFont);
toolBarAndEditorPanel.add(m_editorPanel, BorderLayout.CENTER);
splitPane2.add(toolBarAndEditorPanel);
m_outputTextArea = new JTextArea(2, 80);
m_outputTextArea.setBackground(Color.WHITE);
m_outputTextArea.setFont(m_fixedFont);
m_outputTextArea.setEditable(false);
JScrollPane outputPane = new JScrollPane(m_outputTextArea);
splitPane2.add(outputPane);
splitPane1.add(splitPane2);
contentPane.add(splitPane1, BorderLayout.CENTER);
m_frame.pack();
/*
* Show mostly the display panel and only a few lines of the editor
* and output.
*/
splitPane1.setDividerLocation(0.60);
m_frame.setVisible(true);
/*
* Add each file as a tab.
*/
if (filenames != null)
{
for (int i = 0; i < filenames.length; i++)
{
m_editorPanel.createTab(filenames[i], null);
}
}
else
{
m_editorPanel.createTab(null, null);
InputStreamReader r = null;
try
{
/*
* Set some sample commands for the user to experiment with.
*/
URL commandsUrl = this.getClass().getResource("commands.txt");
r = new InputStreamReader(commandsUrl.openConnection().getInputStream());
StringBuffer commands = new StringBuffer();
int c;
while ((c = r.read()) != -1)
commands.append((char)c);
m_editorPanel.appendToSelectedTextArea(commands.toString());
/*
* Run the sample commands too.
*/
actionPerformed(MapyrusEventListener.RUN_ACTION);
}
catch (IOException e)
{
/*
* Oh well, just start with an empty tab then.
*/
}
finally
{
try
{
if (r != null)
r.close();
}
catch (IOException e)
{
}
}
}
m_editorPanel.addChangeListener(new ChangeListener(){
public void stateChanged(ChangeEvent e)
{
/*
* Re-interpret commands in current tab and display output.
*/
}
});
waitForClose();
}
/**
* Create new window displaying image.
* @param title tile for window.
* @param image image to display in window.
*/
public MapyrusFrame(String title, BufferedImage image)
{
setLookAndFeel();
createActionQueue();
m_displayImage = image;
m_frame = new JFrame(title);
Container contentPane = m_frame.getContentPane();
contentPane.setLayout(new BorderLayout());
/*
* Add menubar and menu options.
*/
MapyrusMenuBar menuBar = new MapyrusMenuBar();
menuBar.addListener(this);
contentPane.add(menuBar, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon(image);
final JLabel label = new JLabel(icon);
/*
* Put image on an icon, putting it in a scrollable area if it is bigger
* than the screen.
*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (image.getWidth() > screenSize.getWidth() ||
image.getHeight() > screenSize.getHeight() - 50)
{
ScrollPane pane = new ScrollPane();
pane.add(label);
contentPane.add(pane, BorderLayout.CENTER);
}
else
{
contentPane.add(label, BorderLayout.CENTER);
}
m_mutex = new Mutex();
m_mutex.lock();
m_frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
});
m_frame.pack();
m_frame.setVisible(true);
waitForClose();
}
private void setLookAndFeel()
{
try
{
/*
* Set operating system specific LookAndFeel.
*/
String className = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(className);
}
catch (UnsupportedLookAndFeelException e)
{
}
catch (ClassNotFoundException e)
{
}
catch (IllegalAccessException e)
{
}
catch (InstantiationException e)
{
}
}
private void createActionQueue()
{
/*
* Create or recreate queue of actions from GUI.
*/
if (m_actionQueue != null)
m_actionQueue.clear();
else
m_actionQueue = new LinkedBlockingQueue<Integer>();
/*
* Create another thread to read this queue and process
* actions so that the GUI is not blocked.
*/
m_actionThread = new Thread(){
public void run()
{
try
{
processActions();
}
catch (InterruptedException e)
{
}
}
};
m_actionThread.start();
}
public void actionPerformed(int actionCode)
{
if (actionCode == MapyrusEventListener.STOP_ACTION ||
actionCode == MapyrusEventListener.EXIT_ACTION)
{
/*
* Interrupt any action that is already running,
* clear queue and restart thread that handles events.
*
* This ensures that event is handled immediately.
*/
m_actionThread.interrupt();
if (m_outputThread != null)
{
m_outputThread.interrupt();
m_outputThread = null;
}
createActionQueue();
}
/*
* Add action to queue.
*/
try
{
m_actionQueue.put(Integer.valueOf(actionCode));
}
catch (InterruptedException e)
{
}
}
public void processActions() throws InterruptedException
{
while (true)
{
Integer actionCode = m_actionQueue.take().intValue();
if (actionCode == MapyrusEventListener.NEW_TAB_ACTION)
{
/*
* Create new tab in editor panel.
*/
if (m_editorPanel != null)
m_editorPanel.createTab(null, null);
}
else if (actionCode == MapyrusEventListener.OPEN_FILE_ACTION)
{
/*
* Show file chooser dialog for user to select a file
* from, show it in a new tab and the output in the
* display window.
*/
openFile();
}
else if (actionCode == MapyrusEventListener.COPY_ACTION)
{
/*
* Copy display panel output to clipboard.
*/
ImageSelection imageSelection = new ImageSelection(m_displayImage);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(imageSelection, null);
}
else if (actionCode == MapyrusEventListener.EXPORT_ACTION)
{
exportToPNG();
}
else if (actionCode == MapyrusEventListener.RUN_ACTION)
{
runCommands();
}
else if (actionCode == MapyrusEventListener.CLOSE_TAB_ACTION)
{
/*
* Close currently open tab.
*/
if (m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
boolean status = true;
if (m_editorPanel.isSelectedTabEdited())
status = saveTab(true);
if (status)
m_editorPanel.closeSelectedTab();
}
}
else if (actionCode == MapyrusEventListener.SAVE_TAB_ACTION)
{
/*
* Save currently open tab.
*/
if (m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
saveTab(false);
}
}
else if (actionCode == MapyrusEventListener.EXIT_ACTION)
{
/*
* If any changes saved successfully then we can exit.
*/
if (saveAndExit())
m_mutex.unlock();
}
else if (actionCode == MapyrusEventListener.ONLINE_HELP_ACTION)
{
/*
* Show HTML GUI help page.
*/
JFrame helpFrame = new JFrame();
try
{
JEditorPane helpPane = new JEditorPane();
helpPane.setEditable(false);
URL helpUrl = this.getClass().getResource("onlinehelp.html");
helpPane.setPage(helpUrl);
helpFrame.getContentPane().add(helpPane);
helpFrame.setPreferredSize(new Dimension(600, 600));
helpFrame.pack();
helpFrame.setVisible(true);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
helpFrame.dispose();
}
}
else if (actionCode == MapyrusEventListener.ABOUT_ACTION)
{
StringBuffer sb = new StringBuffer();
sb.append(Constants.PROGRAM_NAME).append(" ").append(Constants.getVersion());
sb.append(", ").append(Constants.getReleaseDate());
sb.append(" ").append(Constants.WEB_SITE);
sb.append(Constants.LINE_SEPARATOR);
sb.append(Constants.LINE_SEPARATOR);
String []license = Constants.getLicense();
for (int i = 0; i < license.length; i++)
sb.append(license[i]).append(Constants.LINE_SEPARATOR);
JOptionPane.showMessageDialog(m_frame, sb.toString(),
Constants.PROGRAM_NAME, JOptionPane.INFORMATION_MESSAGE);
}
}
}
/*
* File filter limiting file selection to PNG images.
*/
private class PNGImageFilter extends FileFilter
{
public boolean accept(File f)
{
boolean retval = f.isDirectory();
if (!retval)
{
String name = f.getName();
retval = name.endsWith(".png") || name.endsWith(".PNG");
}
return(retval);
}
public String getDescription()
{
return(MapyrusMessages.get(MapyrusMessages.PNG_IMAGE_FILES));
}
}
/**
* Open file with Mapyrus commands in new tab.
*/
private void openFile()
{
if (m_editorPanel != null)
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
chooser.setCurrentDirectory(m_lastOpenedDirectory);
int status = chooser.showOpenDialog(m_frame);
if (status == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile.getParentFile();
String filename = selectedFile.getPath();
m_editorPanel.createTab(filename, null);
}
}
}
/**
* Export image to a PNG file.
*/
private void exportToPNG()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setMultiSelectionEnabled(false);
fileChooser.setFileFilter(new PNGImageFilter());
fileChooser.setSelectedFile(m_lastOpenedDirectory);
int retval = fileChooser.showSaveDialog(m_frame);
if (retval == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile;
try
{
FileOutputStream outStream = new FileOutputStream(selectedFile);
ImageIO.write(m_displayImage, "png", outStream);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
selectedFile.delete();
}
}
}
/**
* Run commands in currently selected tab, showing output in display window.
*/
private void runCommands() throws InterruptedException
{
String contents = m_editorPanel.getSelectedTabContents();
if (contents.length() > 0)
{
try
{
String title = m_editorPanel.getSelectedTabTitle();
FileOrURL f = new FileOrURL(new StringReader(contents), title);
Dimension displayDim = m_displayPanel.getSize();
m_displayPanel.getGraphics().clearRect(0, 0, displayDim.width, displayDim.height);
m_displayImage = new BufferedImage((int)displayDim.getWidth(),
(int)displayDim.getHeight(), BufferedImage.TYPE_4BYTE_ABGR);
Interpreter interpreter = new Interpreter();
ContextStack context = new ContextStack();
context.setOutputFormat(m_displayImage, "");
ByteArrayInputStream stdin = new ByteArrayInputStream(new byte[]{});
PipedOutputStream outStream = new PipedOutputStream();
final PipedInputStream inStream = new PipedInputStream(outStream);
m_outputTextArea.setText("");
/*
* Create thread to read Mapyrus output and append it
* to the output panel.
*/
m_outputThread = new Thread(){
public void run()
{
try
{
byte []buf = new byte[256];
int nBytes;
while ((nBytes = inStream.read(buf)) > 0)
{
String s = new String(buf, 0, nBytes);
int caretPosition = m_outputTextArea.getCaretPosition();
m_outputTextArea.append(s);
/*
* Ensure last lines of output are displayed.
*/
m_outputTextArea.setCaretPosition(caretPosition + s.length());
m_outputTextArea.repaint();
}
}
catch (IOException e)
{
/*
* Reading pipes so should be no IOExceptions.
*/
m_outputTextArea.append(e.getMessage());
}
}
};
m_outputThread.start();
PrintStream p = new PrintStream(outStream);
interpreter.interpret(context, f, stdin, p);
p.close();
if (m_outputThread != null)
{
m_outputThread.join();
m_outputThread = null;
}
m_outputTextArea.repaint();
m_displayPanel.repaint();
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
catch (MapyrusException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(), Constants.PROGRAM_NAME,
JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Block until window is closed.
*/
private void waitForClose()
{
m_mutex.lock();
}
/**
* Save selected tab to a file.
* @param promptSave first show dialog asking user if they want to save.
* @return false if user changes their mind and decides not to save tab.
*/
private boolean saveTab(boolean promptSave)
{
int status = JOptionPane.OK_OPTION;
String filename = m_editorPanel.getSelectedTabFilename();
if (promptSave)
{
String message = MapyrusMessages.get(MapyrusMessages.SAVE_CHANGES_IN_TAB) +
" " + m_editorPanel.getSelectedTabTitle();
if (!filename.startsWith(MapyrusMessages.get(MapyrusMessages.UNTITLED)))
{
message = message + "\n" +
MapyrusMessages.get(MapyrusMessages.TO_FILE) + " " +
filename;
}
status = JOptionPane.showConfirmDialog(m_frame,
message + "?", Constants.PROGRAM_NAME, JOptionPane.YES_NO_CANCEL_OPTION);
}
if (status == JOptionPane.CANCEL_OPTION)
{
return(false);
}
else if (status == JOptionPane.OK_OPTION)
{
/*
* Find filename for this tab.
*/
if (filename.startsWith(MapyrusMessages.get(MapyrusMessages.UNTITLED)))
{
/*
* Give user a chance to specify a different filename.
*/
do
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
chooser.setSelectedFile(new File(m_lastOpenedDirectory, filename));
status = chooser.showSaveDialog(m_frame);
if (status != JFileChooser.APPROVE_OPTION)
return(false);
File selectedFile = chooser.getSelectedFile();
m_lastOpenedDirectory = selectedFile.getParentFile();
filename = selectedFile.getPath();
if (selectedFile.exists())
{
/*
* Check that the user wants to overwrite this file.
*/
status = JOptionPane.showConfirmDialog(m_frame,
MapyrusMessages.get(MapyrusMessages.OVERWRITE) + " " + filename +"?",
Constants.PROGRAM_NAME,
JOptionPane.YES_NO_OPTION);
}
}
while (status != JOptionPane.YES_OPTION);
}
FileWriter f = null;
try
{
/*
* Write the tab contents to file.
*/
f = new FileWriter(filename);
String contents = m_editorPanel.getSelectedTabContents();
f.write(contents);
f.flush();
}
catch (IOException e)
{
JOptionPane.showMessageDialog(m_frame, e.getMessage(),
Constants.PROGRAM_NAME, JOptionPane.ERROR_MESSAGE);
return(false);
}
finally
{
try
{
f.close();
}
catch (IOException e)
{
}
}
}
return(true);
}
/**
* Ask user if they want to save any edited tabs before exiting.
* @return true if all tabs saved and/or closed.
*/
private boolean saveAndExit()
{
boolean retval = true;
while (retval && m_editorPanel != null && m_editorPanel.getTabCount() > 0)
{
if (m_editorPanel.isSelectedTabEdited())
retval = saveTab(true);
if (retval)
m_editorPanel.closeSelectedTab();
}
return(retval);
}
}
|
package org.nutz.mvc.impl;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.nutz.Nutz;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.Ioc2;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Encoding;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Stopwatch;
import org.nutz.lang.Strings;
import org.nutz.lang.util.Context;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionChainMaker;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.Loading;
import org.nutz.mvc.LoadingException;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.Setup;
import org.nutz.mvc.UrlMapping;
import org.nutz.mvc.ViewMaker;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.ChainBy;
import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Localization;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.annotation.UrlMappingBy;
import org.nutz.mvc.annotation.Views;
import org.nutz.mvc.config.AtMap;
import org.nutz.mvc.view.DefaultViewMaker;
import org.nutz.resource.Scans;
public class NutLoading implements Loading {
private static final Log log = Logs.getLog(NutLoading.class);
public UrlMapping load(NutConfig config) {
if (log.isInfoEnabled()) {
log.infof("Nutz Version : %s ", Nutz.version());
log.infof("Nutz.Mvc[%s] is initializing ...", config.getAppName());
}
if (log.isDebugEnabled()) {
log.debug("Web Container Information:");
log.debugf(" - Default Charset : %s", Encoding.defaultEncoding());
log.debugf(" - Current . path : %s", new File(".").getAbsolutePath());
log.debugf(" - Java Version : %s", System.getProperties().get("java.version"));
log.debugf(" - File separator : %s", System.getProperties().get("file.separator"));
log.debugf(" - Timezone : %s", System.getProperties().get("user.timezone"));
}
UrlMapping mapping;
config.getServletContext().setAttribute(AtMap.class.getName(), new AtMap());
Stopwatch sw = Stopwatch.begin();
try {
/*
* MainModule
*/
Class<?> mainModule = config.getMainModule();
createContext(config);
/*
* Ioc
*/
createIoc(config, mainModule);
/*
* UrlMapping
*/
mapping = createUrlMapping(config);
if (log.isInfoEnabled())
log.infof("Build URL mapping by %s ...", mapping);
ViewMaker[] makers = createViewMakers(mainModule);
ActionChainMaker maker = createChainMaker(config, mainModule);
ActionInfo mainInfo = Loadings.createInfo(mainModule);
Set<Class<?>> modules = scanModules(mainModule);
for (Class<?> module : modules) {
ActionInfo moduleInfo = Loadings.createInfo(module).mergeWith(mainInfo);
for (Method method : module.getMethods()) {
/*
* public @At
*/
if (!Modifier.isPublic(method.getModifiers())
|| !method.isAnnotationPresent(At.class))
continue;
ActionInfo info = Loadings.createInfo(method).mergeWith(moduleInfo);
info.setViewMakers(makers);
mapping.add(maker, info, config);
}
}
evalLocalization(config, mainModule);
/*
* Setup
*/
evalSetup(config, mainModule);
}
catch (Exception e) {
if (log.isErrorEnabled())
log.error("Error happend during start serivce!", e);
throw Lang.wrapThrow(e, LoadingException.class);
}
// ~ Done ^_^
sw.stop();
if (log.isInfoEnabled())
log.infof("Nutz.Mvc[%s] is up in %sms", config.getAppName(), sw.getDuration());
return mapping;
}
private static void createContext(NutConfig config) {
// Filter Adaptor ${app.root}
Context context = Lang.context();
context.set("app.root", config.getAppRoot());
if (log.isDebugEnabled()) {
log.debugf(">> app.root = %s", config.getAppRoot());
}
for (Entry<String,String> entry : System.getenv().entrySet())
context.set("env."+entry.getKey(), entry.getValue());
for (Entry<Object,Object> entry : System.getProperties().entrySet())
context.set("sys."+entry.getKey(), entry.getValue());
if (log.isTraceEnabled()) {
log.tracef(">>\nCONTEXT %s", Json.toJson(context, JsonFormat.nice()));
}
config.getServletContext().setAttribute(Loading.CONTEXT_NAME, context);
}
private UrlMapping createUrlMapping(NutConfig config) throws Exception {
UrlMappingBy umb = config.getMainModule().getAnnotation(UrlMappingBy.class);
if (umb != null) {
String value = umb.value();
System.out.println(config.getIoc());
if ((!Strings.isBlank(value)) && value.startsWith("ioc:"))
return config.getIoc().get(UrlMapping.class, value.substring(4));
else
return (UrlMapping) Lang.loadClass(umb.value()).newInstance();
}
return new UrlMappingImpl();
}
private ActionChainMaker createChainMaker(NutConfig config, Class<?> mainModule) {
ChainBy ann = mainModule.getAnnotation(ChainBy.class);
ActionChainMaker maker = null == ann ? new NutActionChainMaker()
: Loadings.evalObj(config, ann.type(), ann.args());
if (log.isDebugEnabled())
log.debugf("@ChainBy(%s)", maker.getClass().getName());
return maker;
}
private void evalSetup(NutConfig config, Class<?> mainModule) throws Exception {
SetupBy sb = mainModule.getAnnotation(SetupBy.class);
if (null != sb) {
if (log.isInfoEnabled())
log.info("Setup application...");
Setup setup = sb.value().newInstance();
config.setAttributeIgnoreNull(Setup.class.getName(), setup);
setup.init(config);
}
}
private void evalLocalization(NutConfig config, Class<?> mainModule) {
Localization lc = mainModule.getAnnotation(Localization.class);
if (null != lc) {
if (log.isDebugEnabled())
log.debugf("Localization message: '%s'", lc.value());
Map<String, Map<String, String>> msgss = Mirror.me(lc.type()).born().load(lc.value());
config.setAttributeIgnoreNull(Localization.class.getName(), msgss);
} else if (log.isDebugEnabled()) {
log.debug("!!!Can not find localization message resource");
}
}
private Set<Class<?>> scanModules(Class<?> mainModule) {
Modules ann = mainModule.getAnnotation(Modules.class);
boolean scan = null == ann ? false : ann.scanPackage();
List<Class<?>> list = new LinkedList<Class<?>>();
list.add(mainModule);
if (null != ann) {
for (Class<?> module : ann.value()) {
list.add(module);
}
}
Set<Class<?>> modules = new HashSet<Class<?>>();
for (Class<?> type : list) {
if (scan) {
if (log.isDebugEnabled())
log.debugf(" > scan '%s'", type.getPackage().getName());
List<Class<?>> subs = Scans.me().scanPackage(type);
for (Class<?> sub : subs) {
if (isModule(sub)) {
if (log.isDebugEnabled())
log.debugf(" >> add '%s'", sub.getName());
modules.add(sub);
} else if (log.isTraceEnabled()) {
log.tracef(" >> ignore '%s'", sub.getName());
}
}
}
else {
if (isModule(type)) {
if (log.isDebugEnabled())
log.debugf(" > add '%s'", type.getName());
modules.add(type);
} else if (log.isTraceEnabled()) {
log.tracef(" > ignore '%s'", type.getName());
}
}
}
return modules;
}
private ViewMaker[] createViewMakers(Class<?> mainModule) throws Exception {
Views vms = mainModule.getAnnotation(Views.class);
ViewMaker[] makers;
int i = 0;
if (null != vms) {
makers = new ViewMaker[vms.value().length + 1];
for (; i < vms.value().length; i++)
makers[i] = vms.value()[i].newInstance();
} else {
makers = new ViewMaker[1];
}
makers[i] = new DefaultViewMaker();
if (log.isDebugEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append(makers[0].getClass().getSimpleName());
for (i = 1; i < makers.length; i++)
sb.append(',').append(makers[i].getClass().getSimpleName());
log.debugf("@Views(%s)", sb);
}
return makers;
}
private void createIoc(NutConfig config, Class<?> mainModule) throws Exception {
IocBy ib = mainModule.getAnnotation(IocBy.class);
if (null != ib) {
if (log.isDebugEnabled())
log.debugf("@IocBy(%s)", ib.type().getName());
Ioc ioc = ib.type().newInstance().create(config, ib.args());
// Ioc2 ValueMaker
if (ioc instanceof Ioc2) {
((Ioc2) ioc).addValueProxyMaker(new ServletValueProxyMaker(config.getServletContext()));
}
// Ioc
config.setAttributeIgnoreNull(Ioc.class.getName(), ioc);
} else if (log.isDebugEnabled())
log.debug("!!!Your application without @IocBy supporting");
}
private static boolean isModule(Class<?> classZ) {
int classModify = classZ.getModifiers();
if(!Modifier.isPublic(classModify) || Modifier.isAbstract(classModify)
|| Modifier.isInterface(classModify))
return false;
for (Method method : classZ.getMethods())
if (method.isAnnotationPresent(At.class))
return true;
return false;
}
public void depose(NutConfig config) {
if (log.isInfoEnabled())
log.infof("Nutz.Mvc[%s] is deposing ...", config.getAppName());
Stopwatch sw = Stopwatch.begin();
// Firstly, upload the user customized desctroy
try {
Setup setup = config.getAttributeAs(Setup.class, Setup.class.getName());
if (null != setup)
setup.destroy(config);
}
catch (Exception e) {
throw new LoadingException(e);
}
// If the application has Ioc, depose it
Ioc ioc = config.getIoc();
if (null != ioc)
ioc.depose();
// Done, print info
sw.stop();
if (log.isInfoEnabled())
log.infof("Nutz.Mvc[%s] is down in %sms", config.getAppName(), sw.getDuration());
}
}
|
package org.pentaho.di.job;
/**
* Contains the description of a job-entry of a job-entry plugin, what jars to
* load, the icon, etc.
*
* @since 2005-may-09
* @author Matt
*
*/
public class JobPlugin
{
public static final int TYPE_ALL = 0;
public static final int TYPE_NATIVE = 1;
public static final int TYPE_PLUGIN = 2;
private int type;
private String id;
private JobEntryType jobType;
private String description;
private String tooltip;
private String directory;
private String jarfiles[];
private String icon_filename;
private String classname;
public JobPlugin(int type, String id, JobEntryType jobType, String tooltip, String directory,
String jarfiles[], String icon_filename, String classname)
{
this.type = type;
this.id = id;
this.jobType = jobType;
this.description = jobType.getDescription();
this.tooltip = tooltip;
this.directory = directory;
this.jarfiles = jarfiles;
this.icon_filename = icon_filename;
this.classname = classname;
}
public JobPlugin(int type, String id, String description, String tooltip, String directory,
String jarfiles[], String icon_filename, String classname)
{
this.type = type;
this.id = id;
this.jobType = null;
this.description = description;
this.tooltip = tooltip;
this.directory = directory;
this.jarfiles = jarfiles;
this.icon_filename = icon_filename;
this.classname = classname;
}
public int getType()
{
return type;
}
public boolean isNative()
{
return type == TYPE_NATIVE;
}
public boolean isPlugin()
{
return type == TYPE_PLUGIN;
}
/**
* @return The ID (code String) of the job or job-plugin.
*/
public String getID()
{
return id;
}
public String getDescription()
{
return description;
}
public JobEntryType getJobType()
{
return jobType;
}
public String getTooltip()
{
return tooltip;
}
public String getDirectory()
{
return directory;
}
public String[] getJarfiles()
{
return jarfiles;
}
public String getIconFilename()
{
return icon_filename;
}
public void setIconFilename(String filename)
{
icon_filename = filename;
}
public String getClassname()
{
return classname;
}
public int hashCode()
{
return id.hashCode();
}
public boolean equals(Object obj)
{
return getID().equals(((JobPlugin) obj).getID());
}
public String toString()
{
return getClass().getName()+": " + id + "(" + (type==TYPE_NATIVE?"NATIVE":"PLUGIN") + ")";
}
}
|
package org.sprite2d.apps.pp;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.util.Locale;
import org.sprite2d.apps.pp.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Base application logic
*
* @author Arthur Bikmullin (devolonter)
* @version 1.15
*
*/
public class Painter extends Activity {
public static final int BACKUP_OPENED_ONLY_FROM_OTHER = 10;
public static final int BACKUP_OPENED_ALWAYS = 20;
public static final int BACKUP_OPENED_NEVER = 100;
public static final int BEFORE_EXIT_SUBMIT = 10;
public static final int BEFORE_EXIT_SAVE = 20;
public static final int BEFORE_EXIT_NO_ACTION = 100;
public static final int SHORTCUTS_VOLUME_BRUSH_SIZE = 10;
public static final int SHORTCUTS_VOLUME_UNDO_REDO = 20;
public static final int ACTION_SAVE_AND_EXIT = 1;
public static final int ACTION_SAVE_AND_RETURN = 2;
public static final int ACTION_SAVE_AND_SHARE = 3;
public static final int ACTION_SAVE_AND_ROTATE = 4;
public static final int ACTION_SAVE_AND_OPEN = 5;
public static final int REQUEST_OPEN = 1;
private static final String SETTINGS_STORAGE = "settings";
public static final String PICTURE_MIME = "image/png";
public static final String PICTURE_PREFIX = "picture_";
public static final String PICTURE_EXT = ".png";
private PainterCanvas mCanvas;
private SeekBar mBrushSize;
private SeekBar mBrushBlurRadius;
private Spinner mBrushBlurStyle;
private LinearLayout mPresetsBar;
private LinearLayout mPropertiesBar;
private RelativeLayout mSettingsLayout;
private PainterSettings mSettings;
private boolean mIsNewFile = true;
private boolean mOpenLastFile = true;
private int mVolumeButtonsShortcuts;
private class SaveTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog = ProgressDialog.show(Painter.this,
Painter.this.getString(R.string.saving_title),
Painter.this.getString(R.string.saving_to_sd), true);
protected String doInBackground(Void... none) {
Painter.this.mCanvas.getThread().freeze();
String pictureName = Painter.this.getUniquePictureName(Painter.this
.getSaveDir());
Painter.this.saveBitmap(pictureName);
Painter.this.mSettings.preset = Painter.this.mCanvas
.getCurrentPreset();
Painter.this.saveSettings();
return pictureName;
}
protected void onPostExecute(String pictureName) {
Uri uri = Uri.fromFile(new File(pictureName));
Painter.this.sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
dialog.hide();
Painter.this.mCanvas.getThread().activate();
}
}
private class SetWallpaperTask extends AsyncTask<Void, Void, Boolean> {
private ProgressDialog mDialog = ProgressDialog.show(Painter.this,
Painter.this.getString(R.string.wallpaper_title),
Painter.this.getString(R.string.aply_wallpaper), true);
protected Boolean doInBackground(Void... none) {
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(Painter.this);
Display display = getWindowManager().getDefaultDisplay();
int wallpaperWidth = display.getWidth() * 2;
int wallpaperHeight = display.getHeight();
Bitmap currentBitmap = Painter.this.mCanvas.getThread().getBitmap();
Bitmap wallpaperBitmap = Bitmap.createBitmap(wallpaperWidth,
wallpaperHeight, Bitmap.Config.ARGB_8888);
// wait bitmap
while (wallpaperBitmap == null) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
return false;
}
}
final Canvas wallpaperCanvas = new Canvas(wallpaperBitmap);
wallpaperCanvas.drawColor(Painter.this.mCanvas.getThread()
.getBackgroundColor());
wallpaperCanvas.drawBitmap(currentBitmap,
(wallpaperWidth - currentBitmap.getWidth()) / 2,
(wallpaperHeight - currentBitmap.getHeight()) / 2, null);
try {
wallpaperManager.setBitmap(wallpaperBitmap);
return true;
} catch (IOException e) {
return false;
}
}
protected void onPostExecute(Boolean success) {
this.mDialog.hide();
if (success) {
Toast.makeText(Painter.this, R.string.wallpaper_setted,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(Painter.this, R.string.wallpaper_error,
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
this.setContentView(R.layout.main);
this.mCanvas = (PainterCanvas) this.findViewById(R.id.canvas);
this.loadSettings();
this.mBrushSize = (SeekBar) this.findViewById(R.id.brush_size);
this.mBrushSize
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (seekBar.getProgress() > 0) {
Painter.this.mCanvas.setPresetSize(seekBar
.getProgress());
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
Painter.this.resetPresets();
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (progress > 0) {
if (fromUser) {
Painter.this.mCanvas.setPresetSize(seekBar
.getProgress());
}
} else {
Painter.this.mBrushSize.setProgress(1);
}
}
});
this.mBrushBlurRadius = (SeekBar) this
.findViewById(R.id.brush_blur_radius);
this.mBrushBlurRadius
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
Painter.this.updateBlurSeek(seekBar.getProgress());
if (seekBar.getProgress() > 0) {
Painter.this.setBlur();
} else {
Painter.this.mCanvas.setPresetBlur(null, 0);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
Painter.this.resetPresets();
}
public void onProgressChanged(SeekBar seekBar,
int progress, boolean fromUser) {
if (fromUser) {
Painter.this.updateBlurSeek(progress);
if (progress > 0) {
Painter.this.setBlur();
} else {
Painter.this.mCanvas.setPresetBlur(null, 0);
}
}
}
});
this.mBrushBlurStyle = (Spinner) this
.findViewById(R.id.brush_blur_style);
this.mBrushBlurStyle
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View v,
int position, long id) {
if (id > 0) {
Painter.this.updateBlurSpinner(id);
Painter.this.setBlur();
} else {
Painter.this.mBrushBlurRadius.setProgress(0);
Painter.this.mCanvas.setPresetBlur(null, 0);
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
this.mPresetsBar = (LinearLayout) this.findViewById(R.id.presets_bar);
this.mPresetsBar.setVisibility(View.INVISIBLE);
this.mPropertiesBar = (LinearLayout) this
.findViewById(R.id.properties_bar);
this.mPropertiesBar.setVisibility(View.INVISIBLE);
this.mSettingsLayout = (RelativeLayout) this
.findViewById(R.id.settings_layout);
this.updateControls();
this.setActivePreset(this.mCanvas.getCurrentPreset().type);
}
@Override
protected void onResume() {
super.onResume();
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
String lang = preferences.getString(
this.getString(R.string.preferences_language), null);
if (lang != null) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
this.getBaseContext().getResources()
.updateConfiguration(config, null);
}
this.mOpenLastFile = preferences.getBoolean(
this.getString(R.string.preferences_last_file), true);
this.mVolumeButtonsShortcuts = Integer.parseInt(preferences.getString(
this.getString(R.string.preferences_volume_shortcuts),
String.valueOf(SHORTCUTS_VOLUME_BRUSH_SIZE)));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = this.getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_brush:
this.enterBrushSetup();
break;
case R.id.menu_save:
this.savePicture(Painter.ACTION_SAVE_AND_RETURN);
break;
case R.id.menu_clear:
if (this.mCanvas.isChanged()) {
this.showDialog(R.id.dialog_clear);
} else {
this.clear();
}
break;
case R.id.menu_share:
this.share();
break;
case R.id.menu_rotate:
this.rotate();
break;
case R.id.menu_open:
this.open();
break;
case R.id.menu_undo:
this.mCanvas.undo();
break;
case R.id.menu_preferences:
this.showPreferences();
break;
case R.id.menu_set_wallpaper:
new SetWallpaperTask().execute();
break;
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
MenuItem undo = menu.findItem(R.id.menu_undo);
if (this.mCanvas.canUndo()) {
undo.setTitle(R.string.menu_undo);
undo.setEnabled(true);
} else if (this.mCanvas.canRedo()) {
undo.setTitle(R.string.menu_redo);
undo.setEnabled(true);
} else {
undo.setTitle(R.string.menu_undo);
undo.setEnabled(false);
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (this.mCanvas.isSetup()) {
this.exitBrushSetup();
return true;
} else if (this.mCanvas.isChanged()
|| (!this.mIsNewFile && !new File(
this.mSettings.lastPicture).exists())) {
this.mSettings.preset = this.mCanvas.getCurrentPreset();
this.saveSettings();
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int beforeExit = Integer.parseInt(preferences.getString(
this.getString(R.string.preferences_before_exit),
String.valueOf(BEFORE_EXIT_SUBMIT)));
if (this.mCanvas.isChanged()
&& beforeExit == BEFORE_EXIT_SUBMIT) {
this.showDialog(R.id.dialog_exit);
} else if (beforeExit == BEFORE_EXIT_SAVE) {
this.savePicture(Painter.ACTION_SAVE_AND_EXIT);
} else {
return super.onKeyDown(keyCode, event);
}
return true;
}
break;
case KeyEvent.KEYCODE_MENU:
if (this.mCanvas.isSetup()) {
return true;
}
break;
case KeyEvent.KEYCODE_VOLUME_UP:
switch (this.mVolumeButtonsShortcuts) {
case SHORTCUTS_VOLUME_BRUSH_SIZE:
this.mCanvas
.setPresetSize(this.mCanvas.getCurrentPreset().size + 1);
if (this.mCanvas.isSetup()) {
this.updateControls();
}
break;
case SHORTCUTS_VOLUME_UNDO_REDO:
if (!this.mCanvas.isSetup()) {
if (this.mCanvas.canRedo()) {
this.mCanvas.undo();
}
}
break;
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
switch (this.mVolumeButtonsShortcuts) {
case SHORTCUTS_VOLUME_BRUSH_SIZE:
this.mCanvas
.setPresetSize(this.mCanvas.getCurrentPreset().size - 1);
if (this.mCanvas.isSetup()) {
this.updateControls();
}
break;
case SHORTCUTS_VOLUME_UNDO_REDO:
if (!this.mCanvas.isSetup()) {
if (this.mCanvas.canUndo()) {
this.mCanvas.undo();
}
}
break;
}
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case R.id.dialog_clear:
return this.createDialogClear();
case R.id.dialog_exit:
return this.createDialogExit();
case R.id.dialog_share:
return this.createDialogShare();
case R.id.dialog_open:
return this.createDialogOpen();
default:
return super.onCreateDialog(id);
}
}
@Override
protected void onStop() {
this.mSettings.preset = this.mCanvas.getCurrentPreset();
this.saveSettings();
super.onStop();
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
switch (requestCode) {
case Painter.REQUEST_OPEN:
if (resultCode == Activity.RESULT_OK) {
Uri uri = intent.getData();
String path = "";
if (uri != null) {
if (uri.toString().toLowerCase().startsWith("content:
path = "file://" + this.getRealPathFromURI(uri);
} else {
path = uri.toString();
}
URI file_uri = URI.create(path);
if (file_uri != null) {
File picture = new File(file_uri);
if (picture.exists()) {
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeFile(picture
.getAbsolutePath());
Config bitmapConfig = bitmap.getConfig();
if (!bitmapConfig
.equals(Bitmap.Config.ARGB_8888)) {
bitmap = null;
}
} catch (Exception e) {
}
if (bitmap != null) {
if (bitmap.getWidth() > bitmap.getHeight()) {
this.mSettings.orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else if (bitmap.getWidth() != bitmap
.getHeight()) {
this.mSettings.orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else {
this.mSettings.orientation = this
.getRequestedOrientation();
}
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
int backupOption = Integer
.parseInt(preferences.getString(
this.getString(R.string.preferences_backup_openeded_file),
String.valueOf(BACKUP_OPENED_ONLY_FROM_OTHER)));
String pictureName = null;
switch (backupOption) {
case BACKUP_OPENED_ONLY_FROM_OTHER:
if (!picture
.getParentFile()
.getName()
.equals(this
.getString(R.string.app_name))) {
pictureName = FileSystem.copyFile(
picture.getAbsolutePath(),
this.getSaveDir()
+ picture.getName());
} else {
pictureName = picture.getAbsolutePath();
}
break;
case BACKUP_OPENED_ALWAYS:
pictureName = FileSystem.copyFile(
picture.getAbsolutePath(),
this.getSaveDir()
+ picture.getName());
break;
case BACKUP_OPENED_NEVER:
pictureName = picture
.getAbsolutePath();
break;
}
if (pictureName != null) {
this.mSettings.lastPicture = pictureName;
this.saveSettings();
this.restart();
} else {
Toast.makeText(this,
R.string.file_not_found,
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, R.string.invalid_file,
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, R.string.file_not_found,
Toast.LENGTH_SHORT).show();
}
}
}
}
break;
}
}
public void changeBrushColor(View v) {
new ColorPickerDialog(this,
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
Painter.this.mCanvas.setPresetColor(color);
}
}, Painter.this.mCanvas.getCurrentPreset().color).show();
}
public Bitmap getLastPicture() {
Bitmap savedBitmap = null;
if (!this.mOpenLastFile && !this.mSettings.forceOpenFile) {
this.mSettings.lastPicture = null;
this.mIsNewFile = true;
return savedBitmap;
}
this.mSettings.forceOpenFile = false;
if (this.mSettings.lastPicture != null) {
if (new File(this.mSettings.lastPicture).exists()) {
savedBitmap = BitmapFactory
.decodeFile(this.mSettings.lastPicture);
this.mIsNewFile = false;
} else {
this.mSettings.lastPicture = null;
}
}
return savedBitmap;
}
public void setPreset(View v) {
switch (v.getId()) {
case R.id.preset_pencil:
this.mCanvas.setPreset(new BrushPreset(BrushPreset.PENCIL,
this.mCanvas.getCurrentPreset().color));
break;
case R.id.preset_brush:
this.mCanvas.setPreset(new BrushPreset(BrushPreset.BRUSH,
this.mCanvas.getCurrentPreset().color));
break;
case R.id.preset_marker:
this.mCanvas.setPreset(new BrushPreset(BrushPreset.MARKER,
this.mCanvas.getCurrentPreset().color));
break;
case R.id.preset_pen:
this.mCanvas.setPreset(new BrushPreset(BrushPreset.PEN,
this.mCanvas.getCurrentPreset().color));
break;
}
this.resetPresets();
this.setActivePreset(v);
this.updateControls();
}
public void resetPresets() {
LinearLayout wrapper = (LinearLayout) this.mPresetsBar.getChildAt(0);
for (int i = wrapper.getChildCount() - 1; i >= 0; i
wrapper.getChildAt(i).setBackgroundColor(Color.WHITE);
}
}
public void savePicture(int action) {
if (!this.isStorageAvailable()) {
return;
}
final int taskAction = action;
new SaveTask() {
protected void onPostExecute(String pictureName) {
Painter.this.mIsNewFile = false;
if (taskAction == Painter.ACTION_SAVE_AND_SHARE) {
Painter.this.startShareActivity(pictureName);
}
if (taskAction == Painter.ACTION_SAVE_AND_OPEN) {
Painter.this.startOpenActivity();
}
super.onPostExecute(pictureName);
if (taskAction == Painter.ACTION_SAVE_AND_EXIT) {
Painter.this.finish();
}
if (taskAction == Painter.ACTION_SAVE_AND_ROTATE) {
Painter.this.rotateScreen();
}
}
}.execute();
}
private void enterBrushSetup() {
this.mSettingsLayout.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Painter.this.mCanvas.setVisibility(View.INVISIBLE);
Painter.this.setPanelVerticalSlide(mPresetsBar, -1.0f, 0.0f,
300);
Painter.this.setPanelVerticalSlide(mPropertiesBar, 1.0f, 0.0f,
300, true);
Painter.this.mCanvas.setup(true);
}
}, 10);
}
private void exitBrushSetup() {
this.mSettingsLayout.setBackgroundColor(Color.WHITE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Painter.this.mCanvas.setVisibility(View.INVISIBLE);
Painter.this.setPanelVerticalSlide(mPresetsBar, 0.0f, -1.0f,
300);
Painter.this.setPanelVerticalSlide(mPropertiesBar, 0.0f, 1.0f,
300, true);
Painter.this.mCanvas.setup(false);
}
}, 10);
}
private Dialog createDialogClear() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.clear_bitmap_prompt);
alert.setCancelable(false);
alert.setTitle(R.string.clear_bitmap_prompt_title);
alert.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.clear();
}
});
alert.setNegativeButton(R.string.no, null);
return alert.create();
}
private Dialog createDialogExit() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.exit_app_prompt);
alert.setCancelable(false);
alert.setTitle(R.string.exit_app_prompt_title);
alert.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.savePicture(Painter.ACTION_SAVE_AND_EXIT);
}
});
alert.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.finish();
}
});
return alert.create();
}
private Dialog createDialogOpen() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.open_prompt);
alert.setCancelable(false);
alert.setTitle(R.string.open_prompt_title);
alert.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.savePicture(Painter.ACTION_SAVE_AND_OPEN);
}
});
alert.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.startOpenActivity();
}
});
return alert.create();
}
private Dialog createDialogShare() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.share_prompt);
alert.setCancelable(false);
alert.setTitle(R.string.share_prompt_title);
alert.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this.savePicture(Painter.ACTION_SAVE_AND_SHARE);
}
});
alert.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Painter.this
.startShareActivity(Painter.this.mSettings.lastPicture);
}
});
return alert.create();
}
private void updateControls() {
this.mBrushSize.setProgress((int) this.mCanvas.getCurrentPreset().size);
if (this.mCanvas.getCurrentPreset().blurStyle != null) {
this.mBrushBlurStyle
.setSelection(this.mCanvas.getCurrentPreset().blurStyle
.ordinal() + 1);
this.mBrushBlurRadius
.setProgress(this.mCanvas.getCurrentPreset().blurRadius);
} else {
this.mBrushBlurStyle.setSelection(0);
this.mBrushBlurRadius.setProgress(0);
}
}
private void setPanelVerticalSlide(LinearLayout layout, float from,
float to, int duration) {
this.setPanelVerticalSlide(layout, from, to, duration, false);
}
private void setPanelVerticalSlide(LinearLayout layout, float from,
float to, int duration, boolean last) {
Animation animation = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
0.0f, Animation.RELATIVE_TO_SELF, from,
Animation.RELATIVE_TO_SELF, to);
animation.setDuration(duration);
animation.setFillAfter(true);
animation.setInterpolator(this, android.R.anim.decelerate_interpolator);
final float listenerFrom = Math.abs(from);
final float listenerTo = Math.abs(to);
final boolean listenerLast = last;
final View listenerLayout = layout;
if (listenerFrom > listenerTo) {
listenerLayout.setVisibility(View.VISIBLE);
}
animation.setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
if (listenerFrom < listenerTo) {
listenerLayout.setVisibility(View.INVISIBLE);
if (listenerLast) {
Painter.this.mCanvas.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Painter.this.mSettingsLayout
.setVisibility(View.GONE);
}
}, 10);
}
} else {
if (listenerLast) {
Painter.this.mCanvas.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
Painter.this.mSettingsLayout
.setBackgroundColor(Color.TRANSPARENT);
}
}, 10);
}
}
}
});
layout.setAnimation(animation);
}
private void share() {
if (!this.isStorageAvailable()) {
return;
}
if (this.mCanvas.isChanged() || this.mIsNewFile) {
if (this.mIsNewFile) {
this.savePicture(Painter.ACTION_SAVE_AND_SHARE);
} else {
this.showDialog(R.id.dialog_share);
}
} else {
this.startShareActivity(this.mSettings.lastPicture);
}
}
private void startShareActivity(String pictureName) {
Uri uri = Uri.fromFile(new File(pictureName));
Intent i = new Intent(Intent.ACTION_SEND);
i.setType(Painter.PICTURE_MIME);
i.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(i,
getString(R.string.share_image_title)));
}
private void updateBlurSpinner(long blur_style) {
if (blur_style > 0 && this.mBrushBlurRadius.getProgress() < 1) {
this.mBrushBlurRadius.setProgress(1);
}
}
private void updateBlurSeek(int progress) {
if (progress > 0) {
if (this.mBrushBlurStyle.getSelectedItemId() < 1) {
this.mBrushBlurStyle.setSelection(1);
}
} else {
this.mBrushBlurStyle.setSelection(0);
}
}
private void setBlur() {
this.mCanvas.setPresetBlur(
(int) this.mBrushBlurStyle.getSelectedItemId(),
mBrushBlurRadius.getProgress());
}
private void setActivePreset(int preset) {
if (preset > 0 && preset != BrushPreset.CUSTOM) {
LinearLayout wrapper = (LinearLayout) this.mPresetsBar
.getChildAt(0);
this.highlightActivePreset(wrapper.getChildAt(preset - 1));
}
}
private void setActivePreset(View v) {
this.highlightActivePreset(v);
}
private void highlightActivePreset(View v) {
v.setBackgroundColor(0xe5e5e5);
}
private void clear() {
this.mCanvas.getThread().clearBitmap();
this.mCanvas.changed(false);
this.clearSettings();
this.mIsNewFile = true;
this.updateControls();
}
private void rotate() {
this.mSettings.forceOpenFile = true;
if (!this.mIsNewFile || this.mCanvas.isChanged()) {
this.savePicture(Painter.ACTION_SAVE_AND_ROTATE);
} else {
this.rotateScreen();
}
}
private void rotateScreen() {
if (this.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
this.mSettings.orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
this.saveSettings();
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else {
this.mSettings.orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
this.saveSettings();
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private boolean isStorageAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
Toast.makeText(this, R.string.sd_card_not_writeable,
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.sd_card_not_available,
Toast.LENGTH_SHORT).show();
}
return false;
}
private String getUniquePictureName(String path) {
if (this.mSettings.lastPicture != null) {
return this.mSettings.lastPicture;
}
String prefix = Painter.PICTURE_PREFIX;
String ext = Painter.PICTURE_EXT;
String pictureName = "";
int suffix = 1;
pictureName = path + prefix + suffix + ext;
while (new File(pictureName).exists()) {
pictureName = path + prefix + suffix + ext;
suffix++;
}
this.mSettings.lastPicture = pictureName;
return pictureName;
}
private void loadSettings() {
this.mSettings = new PainterSettings();
SharedPreferences settings = this.getSharedPreferences(
Painter.SETTINGS_STORAGE, Context.MODE_PRIVATE);
this.mSettings.orientation = settings.getInt(
this.getString(R.string.settings_orientation),
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
if (this.getRequestedOrientation() != this.mSettings.orientation) {
this.setRequestedOrientation(this.mSettings.orientation);
}
this.mSettings.lastPicture = settings.getString(
this.getString(R.string.settings_last_picture), null);
int type = settings.getInt(
this.getString(R.string.settings_brush_type), BrushPreset.PEN);
if (type == BrushPreset.CUSTOM) {
this.mSettings.preset = new BrushPreset(
settings.getFloat(
this.getString(R.string.settings_brush_size), 2),
settings.getInt(
this.getString(R.string.settings_brush_color),
Color.BLACK),
settings.getInt(
this.getString(R.string.settings_brush_blur_style),
0),
settings.getInt(
this.getString(R.string.settings_brush_blur_radius),
0));
this.mSettings.preset.setType(type);
} else {
this.mSettings.preset = new BrushPreset(type, settings.getInt(
this.getString(R.string.settings_brush_color), Color.BLACK));
}
this.mCanvas.setPreset(this.mSettings.preset);
this.mSettings.forceOpenFile = settings.getBoolean(
this.getString(R.string.settings_force_open_file), false);
}
private String getSaveDir() {
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath()
+ "/"
+ this.getString(R.string.app_name)
+ "/";
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
return path;
}
private void saveBitmap(String pictureName) {
try {
this.mCanvas.saveBitmap(pictureName);
this.mCanvas.changed(false);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
private void saveSettings() {
SharedPreferences settings = this.getSharedPreferences(
Painter.SETTINGS_STORAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
try {
PackageInfo pack = this.getPackageManager().getPackageInfo(
this.getPackageName(), 0);
editor.putInt(this.getString(R.string.settings_version),
pack.versionCode);
} catch (NameNotFoundException e) {
}
editor.putInt(this.getString(R.string.settings_orientation),
this.mSettings.orientation);
editor.putString(this.getString(R.string.settings_last_picture),
this.mSettings.lastPicture);
editor.putFloat(this.getString(R.string.settings_brush_size),
this.mSettings.preset.size);
editor.putInt(this.getString(R.string.settings_brush_color),
this.mSettings.preset.color);
editor.putInt(
this.getString(R.string.settings_brush_blur_style),
(this.mSettings.preset.blurStyle != null) ? this.mSettings.preset.blurStyle
.ordinal() + 1 : 0);
editor.putInt(this.getString(R.string.settings_brush_blur_radius),
this.mSettings.preset.blurRadius);
editor.putInt(this.getString(R.string.settings_brush_type),
this.mSettings.preset.type);
editor.putBoolean(this.getString(R.string.settings_force_open_file),
this.mSettings.forceOpenFile);
editor.commit();
}
private void clearSettings() {
this.mSettings.lastPicture = null;
this.deleteFile(Painter.SETTINGS_STORAGE);
}
private void open() {
if (!this.isStorageAvailable()) {
return;
}
this.mSettings.forceOpenFile = true;
if (this.mCanvas.isChanged()) {
this.showDialog(R.id.dialog_open);
} else {
this.startOpenActivity();
}
}
private void startOpenActivity() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(Uri.fromFile(new File(this.getSaveDir())),
Painter.PICTURE_MIME);
this.startActivityForResult(
Intent.createChooser(intent,
this.getString(R.string.open_prompt_title)),
Painter.REQUEST_OPEN);
}
private void restart() {
Intent intent = this.getIntent();
this.overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
this.finish();
this.overridePendingTransition(0, 0);
this.startActivity(intent);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index).replace(" ", "%20");
}
private void showPreferences() {
Intent intent = new Intent();
intent.setClass(this, PainterPreferences.class);
startActivity(intent);
}
}
|
package org.terifan.raccoon;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Spliterator;
import java.util.Spliterators.AbstractSpliterator;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import org.terifan.raccoon.io.IManagedBlockDevice;
import org.terifan.raccoon.io.IPhysicalBlockDevice;
import org.terifan.raccoon.io.ManagedBlockDevice;
import org.terifan.raccoon.io.SecureBlockDevice;
import org.terifan.raccoon.io.UnsupportedVersionException;
import org.terifan.raccoon.io.MemoryBlockDevice;
import org.terifan.raccoon.io.AccessCredentials;
import org.terifan.raccoon.io.BlobOutputStream;
import org.terifan.raccoon.io.FileBlockDevice;
import org.terifan.raccoon.util.Assert;
import org.terifan.raccoon.util.ByteArrayBuffer;
import org.terifan.raccoon.util.Log;
import org.terifan.security.messagedigest.MurmurHash3;
public final class Database implements AutoCloseable
{
private final static int EXTRA_DATA_CHECKSUM_SEED = 0xf49209b1;
private final static long RACCOON_DB_IDENTITY = 0x726163636f6f6e00L; // 'raccoon\0'
private final static BlockSizeParam DEFAULT_BLOCK_SIZE = new BlockSizeParam(4096);
private final static int RACCOON_DB_VERSION = 1;
private final ReentrantReadWriteLock mReadWriteLock = new ReentrantReadWriteLock();
private final Lock mReadLock = mReadWriteLock.readLock();
private final Lock mWriteLock = mReadWriteLock.writeLock();
private IManagedBlockDevice mBlockDevice;
private final HashMap<Class,Supplier> mFactories;
private final HashMap<Class,Initializer> mInitializers;
private final Map<TableMetadata,Table> mOpenTables;
private final TableMetadataProvider mTableMetadatas;
private final TransactionCounter mTransactionId;
private Table mSystemTable;
private boolean mChanged;
private Object[] mProperties;
private TableMetadata mSystemTableMetadata;
private boolean mCloseDeviceOnCloseDatabase;
private Database()
{
mOpenTables = Collections.synchronizedMap(new HashMap<>());
mTableMetadatas = new TableMetadataProvider();
mFactories = new HashMap<>();
mTransactionId = new TransactionCounter();
mInitializers = new HashMap<>();
}
public static Database open(File aFile, OpenOption aOpenOptions, Object... aParameters) throws IOException, UnsupportedVersionException
{
FileBlockDevice fileBlockDevice = null;
try
{
if (aFile.exists())
{
if (aOpenOptions == OpenOption.CREATE_NEW)
{
if (!aFile.delete())
{
throw new IOException("Failed to delete existing file: " + aFile);
}
}
else if ((aOpenOptions == OpenOption.READ_ONLY || aOpenOptions == OpenOption.OPEN) && aFile.length() == 0)
{
throw new IOException("File is empty.");
}
}
else if (aOpenOptions == OpenOption.OPEN || aOpenOptions == OpenOption.READ_ONLY)
{
throw new IOException("File not found: " + aFile);
}
boolean newFile = !aFile.exists();
BlockSizeParam blockSizeParam = getParameter(BlockSizeParam.class, aParameters, DEFAULT_BLOCK_SIZE);
fileBlockDevice = new FileBlockDevice(aFile, blockSizeParam.getValue(), aOpenOptions == OpenOption.READ_ONLY);
return init(fileBlockDevice, newFile, true, aParameters);
}
catch (Throwable e)
{
if (fileBlockDevice != null)
{
try
{
fileBlockDevice.close();
}
catch (Exception ee)
{
}
}
throw e;
}
}
/**
*
* @param aParameters
* AccessCredentials
*/
public static Database open(IPhysicalBlockDevice aBlockDevice, OpenOption aOpenOptions, Object... aParameters) throws IOException, UnsupportedVersionException
{
Assert.fail((aOpenOptions == OpenOption.READ_ONLY || aOpenOptions == OpenOption.OPEN) && aBlockDevice.length() == 0, "Block device is empty.");
boolean create = aBlockDevice.length() == 0 || aOpenOptions == OpenOption.CREATE_NEW;
return init(aBlockDevice, create, false, aParameters);
}
private static Database init(IPhysicalBlockDevice aBlockDevice, boolean aCreate, boolean aCloseDeviceOnCloseDatabase, Object[] aParameters) throws IOException
{
AccessCredentials accessCredentials = getParameter(AccessCredentials.class, aParameters, null);
ManagedBlockDevice device;
if (aBlockDevice instanceof IManagedBlockDevice)
{
if (accessCredentials != null)
{
throw new IllegalArgumentException("The BlockDevice provided cannot be secured, ensure that the BlockDevice it writes to is a secure BlockDevice.");
}
device = (ManagedBlockDevice)aBlockDevice;
}
else if (accessCredentials == null)
{
Log.d("creating a managed block device");
device = new ManagedBlockDevice(aBlockDevice);
}
else
{
Log.d("creating a secure block device");
device = new ManagedBlockDevice(new SecureBlockDevice(aBlockDevice, accessCredentials));
}
Database db;
if (aCreate)
{
db = create(device, aParameters);
}
else
{
db = open(device, aParameters);
}
db.mCloseDeviceOnCloseDatabase = aCloseDeviceOnCloseDatabase;
return db;
}
private static Database create(IManagedBlockDevice aBlockDevice, Object[] aParameters) throws IOException
{
Log.i("create database");
Log.inc();
if (aBlockDevice.length() > 0)
{
aBlockDevice.setExtraData(null);
aBlockDevice.clear();
aBlockDevice.commit();
}
Database db = new Database();
db.mProperties = aParameters;
db.mBlockDevice = aBlockDevice;
db.mSystemTableMetadata = new TableMetadata(TableMetadata.class, null);
db.mSystemTable = new Table(db, db.mSystemTableMetadata, null);
db.mChanged = true;
db.updateSuperBlock();
db.commit();
Log.dec();
return db;
}
private static Database open(IManagedBlockDevice aBlockDevice, Object[] aParameters) throws IOException, UnsupportedVersionException
{
Database db = new Database();
Log.i("open database");
Log.inc();
byte[] extraData = aBlockDevice.getExtraData();
if (extraData == null || extraData.length < 20)
{
throw new UnsupportedVersionException("This block device does not contain a Raccoon database (bad extra data length) ("+(extraData==null?null:extraData.length)+")");
}
ByteArrayBuffer buffer = new ByteArrayBuffer(extraData);
if (MurmurHash3.hash_x86_32(buffer.array(), 4, buffer.capacity()-4, EXTRA_DATA_CHECKSUM_SEED) != buffer.readInt32())
{
throw new UnsupportedVersionException("This block device does not contain a Raccoon database (bad extra checksum)");
}
long identity = buffer.readInt64();
int version = buffer.readInt32();
if (identity != RACCOON_DB_IDENTITY)
{
throw new UnsupportedVersionException("This block device does not contain a Raccoon database (bad extra identity)");
}
if (version != RACCOON_DB_VERSION)
{
throw new UnsupportedVersionException("Unsupported database version: provided: " + version + ", expected: " + RACCOON_DB_VERSION);
}
db.mTransactionId.set(buffer.readInt64());
db.mProperties = aParameters;
db.mBlockDevice = aBlockDevice;
db.mSystemTableMetadata = new TableMetadata(TableMetadata.class, null);
db.mSystemTable = new Table(db, db.mSystemTableMetadata, buffer.crop().array());
Log.dec();
return db;
}
private Table openTable(Class aType, Object aDiscriminator, OpenOption aOptions)
{
checkOpen();
Assert.notEquals(aType.getName(), TableMetadata.class.getName());
return openTable(mTableMetadatas.getOrCreate(aType, aDiscriminator), aOptions);
}
private Table openTable(TableMetadata aTableMetadata, OpenOption aOptions)
{
Table table = mOpenTables.get(aTableMetadata);
if (table == null)
{
Log.i("open table '%s' with option %s", aTableMetadata.getTypeName(), aOptions);
Log.inc();
boolean tableExists = mSystemTable.get(aTableMetadata);
if (!tableExists && (aOptions == OpenOption.OPEN || aOptions == OpenOption.READ_ONLY))
{
return null;
}
aTableMetadata.initialize();
table = new Table(this, aTableMetadata, aTableMetadata.getPointer());
if (!tableExists)
{
mSystemTable.save(aTableMetadata);
}
mOpenTables.put(aTableMetadata, table);
Log.dec();
}
if (aOptions == OpenOption.CREATE_NEW)
{
table.clear();
}
return table;
}
private void checkOpen() throws IllegalStateException
{
Assert.notNull(mSystemTable, "Database is closed");
}
public boolean isChanged()
{
checkOpen();
for (Table table : mOpenTables.values())
{
if (table.isChanged())
{
return true;
}
}
return false;
}
/**
* Persists all pending changes. It's necessary to commit changes on a regular basis to avoid data loss.
*/
public boolean commit()
{
checkOpen();
mWriteLock.lock();
try
{
Log.i("commit database");
Log.inc();
for (java.util.Map.Entry<TableMetadata,Table> entry : mOpenTables.entrySet())
{
if (entry.getValue().commit())
{
Log.i("table updated '%s'", entry.getKey());
mSystemTable.save(entry.getKey());
mChanged = true;
}
}
boolean changed = mChanged;
if (mChanged)
{
mSystemTable.commit();
updateSuperBlock();
try
{
mBlockDevice.commit();
}
catch (IOException e)
{
throw new DatabaseIOException(e);
}
mChanged = false;
assert integrityCheck() == null : integrityCheck();
}
Log.dec();
return changed;
}
finally
{
mWriteLock.unlock();
}
}
/**
* Reverts all pending changes.
*/
public void rollback() throws IOException
{
checkOpen();
mWriteLock.lock();
try
{
Log.i("rollback");
Log.inc();
for (Table table : mOpenTables.values())
{
table.rollback();
}
mSystemTable.rollback();
mBlockDevice.rollback();
Log.dec();
}
finally
{
mWriteLock.unlock();
}
}
private void updateSuperBlock()
{
Log.i("update SuperBlock");
mTransactionId.increment();
ByteArrayBuffer buffer = new ByteArrayBuffer(100);
buffer.writeInt32(0); // leave space for checksum
buffer.writeInt64(RACCOON_DB_IDENTITY);
buffer.writeInt32(RACCOON_DB_VERSION);
buffer.writeInt64(mTransactionId.get());
if (mSystemTableMetadata.getPointer()!=null) buffer.write(mSystemTableMetadata.getPointer());
buffer.trim();
int checksum = MurmurHash3.hash_x86_32(buffer.array(), 4, buffer.position() - 4, EXTRA_DATA_CHECKSUM_SEED);
buffer.position(0).writeInt32(checksum);
mBlockDevice.setExtraData(buffer.array());
}
@Override
public void close() throws IOException
{
if (mBlockDevice == null)
{
return;
}
mWriteLock.lock();
try
{
if (mSystemTable != null)
{
Log.i("close database");
for (Table table : mOpenTables.values())
{
table.close();
}
mOpenTables.clear();
mSystemTable.close();
mSystemTable = null;
}
if (mCloseDeviceOnCloseDatabase)
{
mBlockDevice.close();
}
mBlockDevice = null;
}
finally
{
mWriteLock.unlock();
}
}
/**
* Saves an entity.
*
* @return
* true if the entity didn't previously existed.
*/
public boolean save(Object aEntity)
{
mWriteLock.lock();
try
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.CREATE);
return table.save(aEntity);
}
finally
{
mWriteLock.unlock();
}
}
/**
* Retrieves an entity.
*
* @return
* true if the entity was found.
*/
public boolean tryGet(Object aEntity)
{
mReadLock.lock();
try
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.OPEN);
if (table == null)
{
return false;
}
return table.get(aEntity);
}
finally
{
mReadLock.unlock();
}
}
/**
*
* @throws NoSuchEntityException
* if the entity cannot be found
*/
public <T> T get(T aEntity) throws DatabaseException
{
Assert.notNull(aEntity, "Argument is null");
mReadLock.lock();
try
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.OPEN);
if (table == null)
{
throw new NoSuchEntityException("No table exists matching type " + aEntity.getClass());
}
if (!table.get(aEntity))
{
throw new NoSuchEntityException("No entity exists matching key");
}
return aEntity;
}
finally
{
mReadLock.unlock();
}
}
/**
* Removes the entity.
*
* @return
* true if the entity was removed.
*/
public boolean remove(Object aEntity)
{
mWriteLock.lock();
try
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.OPEN);
if (table == null)
{
return false;
}
return table.remove(aEntity);
}
finally
{
mWriteLock.unlock();
}
}
/**
* Remove all entries of the entities type.
*/
public void clear(Class aType)
{
clearImpl(aType, null);
}
/**
* Remove all entries of the entities type and possible it's discriminator.
*/
public void clear(Object aEntity)
{
clearImpl(aEntity.getClass(), aEntity);
}
private void clearImpl(Class aType, Object aEntity)
{
mWriteLock.lock();
try
{
Table table = openTable(aType, aEntity, OpenOption.OPEN);
if (table != null)
{
table.clear();
}
}
finally
{
mWriteLock.unlock();
}
}
/**
* The contents of the stream is associated with the key found in the entity provided. The stream will persist the entity when it's closed.
*/
public BlobOutputStream saveBlob(Object aEntity)
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.CREATE);
return table.saveBlob(aEntity);
}
/**
* Save the contents of the stream with the key defined by the entity provided.
*/
public boolean save(Object aKeyEntity, InputStream aInputStream)
{
mWriteLock.lock();
try
{
Table table = openTable(aKeyEntity.getClass(), aKeyEntity, OpenOption.CREATE);
return table.save(aKeyEntity, aInputStream);
}
finally
{
mWriteLock.unlock();
}
}
/**
* Return an InputStream to the value associated to the key defined by the entity provided.
*/
public InputStream read(Object aEntity)
{
mReadLock.lock();
try
{
Table table = openTable(aEntity.getClass(), aEntity, OpenOption.OPEN);
if (table == null)
{
return null;
}
byte[] buffer;
try (InputStream in = table.read(aEntity))
{
if (in == null)
{
return null;
}
buffer = Streams.readAll(in);
}
return new ByteArrayInputStream(buffer);
}
catch (IOException e)
{
throw new DatabaseIOException(e);
}
finally
{
mReadLock.unlock();
}
}
public <T> Iterable<T> iterable(Class<T> aType)
{
return iterable(aType, null);
}
public <T> Iterable<T> iterable(Class<T> aType, T aDiscriminator)
{
Table table = openTable(aType, aDiscriminator, OpenOption.OPEN);
if (table == null)
{
return null;
}
return ()->table.iterator();
}
public <T> Iterator<T> iterator(Class<T> aType)
{
return iterator(aType, null);
}
public <T> Iterator<T> iterator(Class<T> aType, T aDiscriminator)
{
mReadLock.lock();
try
{
Table table = openTable(aType, aDiscriminator, OpenOption.OPEN);
if (table == null)
{
return null;
}
return table.iterator();
}
finally
{
mReadLock.unlock();
}
}
public <T> List<T> list(Class<T> aType)
{
return list(aType, null);
}
public <T> List<T> list(Class<T> aType, T aEntity)
{
mReadLock.lock();
try
{
Table table = openTable(aType, aEntity, OpenOption.OPEN);
if (table == null)
{
return new ArrayList<>();
}
return table.list(aType);
}
finally
{
mReadLock.unlock();
}
}
public <T> Stream<T> stream(Class<T> aType)
{
return stream(aType, null);
}
public <T> Stream<T> stream(Class<T> aType, T aEntity)
{
mReadLock.lock();
try
{
Table table = openTable(aType, aEntity, OpenOption.OPEN);
// return empty stream when table not found
if (table == null)
{
return StreamSupport.stream(new AbstractSpliterator<T>(0, Spliterator.SIZED)
{
@Override
public boolean tryAdvance(Consumer<? super T> aConsumer)
{
return false;
}
}, false);
}
return table.stream();
// ArrayList<T> list = new ArrayList<>();
// table.iterator().forEachRemaining(e->list.add((T)e));
// return StreamSupport.stream(new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.IMMUTABLE | Spliterator.NONNULL)
// int i;
// @Override
// public boolean tryAdvance(Consumer<? super T> aConsumer)
// if (i == list.size())
// return false;
// aConsumer.accept(list.get(i++));
// return true;
// }, false);
}
finally
{
mReadLock.unlock();
}
}
// public ResultSet list(String aType)
// return list(aType, null);
// public ResultSet list(String aType, EntityMap aEntity)
// mReadLock.lock();
// try
//// Table table = openTable(aType, aEntity, OpenOption.OPEN);
//// if (table == null)
//// return new ResultSet();
//// return table.list(aType);
// return null;
// finally
// mReadLock.unlock();
/**
* Sets a Supplier associated with the specified type. The Supplier is used to create instances of specified types.
*
* E.g:
* mDatabase.setSupplier(Photo.class, ()->new Photo(PhotoAlbum.this));
*/
public <T> void setSupplier(Class<T> aType, Supplier<T> aSupplier)
{
mFactories.put(aType, aSupplier);
}
<T> Supplier<T> getSupplier(Class<T> aType)
{
return mFactories.get(aType);
}
public <T> void setInitializer(Class<T> aType, Initializer<T> aSupplier)
{
mInitializers.put(aType, aSupplier);
}
<T> Initializer<T> getInitializer(Class<T> aType)
{
return mInitializers.get(aType);
}
public IManagedBlockDevice getBlockDevice()
{
return mBlockDevice;
}
public TransactionCounter getTransactionId()
{
return mTransactionId;
}
public int size(Class aType)
{
mReadLock.lock();
try
{
Table table = openTable(aType, null, OpenOption.OPEN);
if (table == null)
{
return 0;
}
return table.size();
}
finally
{
mReadLock.unlock();
}
}
public int size(Object aDiscriminator)
{
Table table = openTable(aDiscriminator.getClass(), aDiscriminator, OpenOption.OPEN);
if (table == null)
{
return 0;
}
return table.size();
}
public String integrityCheck()
{
mWriteLock.lock();
try
{
for (Table table : mOpenTables.values())
{
String s = table.integrityCheck();
if (s != null)
{
return s;
}
}
return null;
}
finally
{
mWriteLock.unlock();
}
}
private static <E> E getParameter(Class aType, Object[] aParameters, E aDefaultValue)
{
if (aParameters != null)
{
for (Object param : aParameters)
{
if (param != null && aType.isAssignableFrom(param.getClass()))
{
return (E)param;
}
}
}
return aDefaultValue;
}
<E> E getParameter(Class<E> aType, E aDefaultParam)
{
return getParameter(aType, mProperties, aDefaultParam);
}
public List<Table> getTables()
{
checkOpen();
mReadLock.lock();
try
{
ArrayList<Table> tables = new ArrayList<>();
mSystemTable.list(TableMetadata.class).stream().forEach(e->tables.add(openTable((TableMetadata)e, OpenOption.OPEN)));
return tables;
}
finally
{
mReadLock.unlock();
}
}
public synchronized <T> List<T> getDiscriminators(Supplier<T> aSupplier)
{
mReadLock.lock();
try
{
ArrayList<T> result = new ArrayList<>();
String name = aSupplier.get().getClass().getName();
for (TableMetadata tableMetadata : (List<TableMetadata>)mSystemTable.list(TableMetadata.class))
{
tableMetadata.initialize(); // TODO: refactor??
if (name.equals(tableMetadata.getTypeName()))
{
T instance = aSupplier.get();
tableMetadata.getMarshaller().unmarshalDiscriminators(new ByteArrayBuffer(tableMetadata.getDiscriminatorKey()), instance);
result.add(instance);
}
}
return result;
}
finally
{
mReadLock.unlock();
}
}
public void scan()
{
Log.out.println(mSystemTable);
mSystemTable.scan();
for (Table table : getTables())
{
Log.out.println(table);
table.scan();
}
}
private static void dummy()
{
// this exists to ensure MemoryBlockDevice is included in distributions
MemoryBlockDevice blockDevice = new MemoryBlockDevice(512);
}
}
|
package organdonation.entities;
public class Human extends Entity {
public Human() {
}
}
|
package paintingwindow;
import paintinglogic.Logger;
import paintinglogic.PaintBrush;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
public class PaintingPanel extends JPanel implements MouseMotionListener, MouseListener {
public static Color canvasColour = new Color(238, 238, 238);
public static Color non_eraserColor = Color.BLACK;
PaintBrush brush = new PaintBrush(); //creates the PaintBrush to hold data about the current state of the brush.
Image circle, paintbucket, square, xMark, small, medium, big, huge, eraser;
BufferedImage canvas;
Graphics b;
int dynamicMouseX = 0, dynamicMouseY = 0;
public PaintingPanel() {
Logger.logCodeMessage("Setting size of window to 900x1000");
setSize(900, 1000); //set size to 900x1000 pixels
//load all images, such as brush size chooser, and other icons
try {
circle = ImageIO.read(new File("resource/circle.png"));
paintbucket = ImageIO.read(new File("resource/paintbucket.png"));
square = ImageIO.read(new File("resource/square.png"));
xMark = ImageIO.read(new File("resource/x.png"));
small = ImageIO.read(new File("resource/small.png"));
medium = ImageIO.read(new File("resource/medium.png"));
big = ImageIO.read(new File("resource/big.png"));
huge = ImageIO.read(new File("resource/hug.png"));
eraser = ImageIO.read(new File("resource/eraser.png"));
Logger.logOtherMessage("Canvas_Loader", "Loading the canvas...");
canvas = new BufferedImage(900, 850, BufferedImage.TYPE_4BYTE_ABGR); //creates the canvas to paint to.
b = canvas.getGraphics(); //gets a graphics object off of the canvas.
Logger.logOtherMessage("Canvas_Loader", "Succeeded.");
Logger.logOtherMessage("ImageLoader", "Succeeded.");
} catch (Exception e) { //if something goes wrong with loading images, such as missing files.
System.err.println("Error Reading images. Program will exit.");
Logger.logErrorMessage("Error reading in images.");
System.exit(-2);
}
addMouseMotionListener(this); //adds mouse listeners to the program
addMouseListener(this);
}
public void paint(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, getWidth(), 150);
g.setColor(Color.BLACK);
g.drawString("Painter Program", 10, 20);
g.drawString("Brushes:", 150, 20);
//g.drawImage(paintbucket, 150, 30, null);
g.drawImage(circle, 215, 30, null);
g.drawImage(square, 279, 30, null);
g.drawImage(eraser, 343, 30, null);
g.drawString("Set custom colour:", 790, 50);
g.setColor(Color.BLUE);
g.fillRect(820, 70, 50, 50);
g.setColor(Color.BLACK);
g.drawString("Clear all:", 10, 50);
g.drawImage(xMark, 10, 60, null);
g.drawImage(small, 150, 85, null);
g.drawImage(medium, 200, 85, null);
g.drawImage(big, 250, 85, null);
g.drawImage(huge, 320, 85, null);
g.drawString("Sizes:", 150, 100);
g.drawString("Colours:", 500, 30);
g.setColor(Color.RED);
g.fillRect(500, 40, 10, 10);
g.setColor(Color.BLUE);
g.fillRect(515, 40, 10, 10);
g.setColor(Color.orange);
g.fillRect(530, 40, 10, 10);
g.setColor(Color.yellow);
g.fillRect(545, 40, 10, 10);
g.setColor(Color.green);
g.fillRect(560, 40, 10, 10);
g.setColor(Color.black);
g.fillRect(575, 40, 10, 10);
g.setColor(Color.CYAN);
g.fillRect(590, 40, 10, 10);
g.setColor(Color.PINK);
g.fillRect(605, 40, 10, 10);
g.setColor(Color.MAGENTA);
g.fillRect(620, 40, 10, 10);
g.setColor(new Color(150, 70, 0)); //brown
g.fillRect(635, 40, 10, 10);
g.setColor(new Color(0, 0, 100)); //dark blue
g.fillRect(650, 40, 10, 10);
g.setColor(new Color(100, 100, 0)); //olive green
g.fillRect(665, 40, 10, 10);
g.setColor(Color.GRAY);
g.fillRect(680, 40, 10, 10);
g.setColor(new Color(232, 227, 163)); //tan
g.fillRect(695, 40, 10, 10);
g.setColor(new Color(163, 255, 210)); //light green
g.fillRect(710, 40, 10, 10);
//second line of colours--
g.setColor(new Color(67, 97, 178)); //navy blue
g.fillRect(500, 60, 10, 10);
g.setColor(new Color(110, 7, 0)); //dark red
g.fillRect(515, 60, 10, 10);
g.setColor(new Color(197, 232, 255)); //baby blue
g.fillRect(530, 60, 10, 10);
g.drawImage(canvas, 0, 150, null);
}
@Deprecated
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
brush.setDown(true);
dynamicMouseX = e.getX();
dynamicMouseY = e.getY();
/*if ((e.getX() >= 150 && e.getX() <= 150 + 64) && (e.getY() >= 30 && e.getY() <= 30 + 64)) { //if user clicks on the paint bucket option
brush.setShape(PaintBrush.FILL);
brush.setColor(non_eraserColor);
Logger.logUserMessage("Set brush shape to FILL."); todo implement filling. also remember to re-enable paintbukt icon
}*/
if ((e.getX() >= 215 && e.getX() <= 215 + 64) && (e.getY() >= 30 && e.getY() <= 30 + 64)) { //if user clicks on the circle brush option
brush.setShape(PaintBrush.CIRCLE);
brush.setColor(non_eraserColor);
Logger.logUserMessage("Set brush shape to CIRCLE.");
} else if ((e.getX() >= 279 && e.getX() <= 279 + 64) && (e.getY() >= 30 && e.getY() <= 30 + 64)) {//if user clicks on the square brush option
brush.setShape(PaintBrush.SQUARE);
brush.setColor(non_eraserColor);
Logger.logUserMessage("Set brush shape to SQUARE.");
} else if ((e.getX() >= 343 && e.getX() <= 343 + 64) && (e.getY() >= 30 && e.getY() <= 30 + 64)) {//if user clicks on the eraser option
brush.setShape(PaintBrush.ERASER);
Logger.logUserMessage("Set brush shape to ERASER.");
}
if ((e.getX() >= 150 && e.getX() <= 150 + 64) && (e.getY() >= 85 && e.getY() <= 85 + 64)) { //if user clicks on the small brush option
brush.setSize(PaintBrush.SMALL);
Logger.logUserMessage("Set brush SIZE to SMALL.");
} else if ((e.getX() >= 200 && e.getX() <= 200 + 64) && (e.getY() >= 85 && e.getY() <= 85 + 64)) { //if user clicks on the medium brush option
brush.setSize(PaintBrush.MEDIUM);
Logger.logUserMessage("Set brush size to MEDIUM.");
} else if ((e.getX() >= 250 && e.getX() <= 250 + 64) && (e.getY() >= 85 && e.getY() <= 85 + 64)) { //if user clicks on the big brush option
brush.setSize(PaintBrush.BIG);
Logger.logUserMessage("Set brush size to BIG.");
} else if ((e.getX() >= 320 && e.getX() <= 320 + 64) && (e.getY() >= 85 && e.getY() <= 85 + 64)) { //if user clicks on the huge brush option
brush.setSize(PaintBrush.HUGE);
Logger.logUserMessage("Set brush size to HUGE");
}
setCurrentPaint(brush); //sets the current paint based on the user's click.
if ((e.getX() >= 820 && e.getX() <= 870) && (e.getY() >= 70 && e.getY() <= 120)) {
getUserRGB(brush);
}
b.setColor(brush.getColor()); //sets the painting colour to the current colour of the brush
if (e.getY() > 150) {
repaint();
if (brush.getShape() == PaintBrush.CIRCLE && brush.isDown()) {
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillOval(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillOval(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillOval(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillOval(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
} else if (brush.getShape() == PaintBrush.SQUARE && brush.isDown()) {
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillRect(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillRect(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillRect(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillRect(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
} else if (brush.getShape() == PaintBrush.ERASER && brush.isDown()) {
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillRect(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillRect(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillRect(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillRect(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
brush.setDown(false);
dynamicMouseX = e.getX();
dynamicMouseY = e.getY();
if ((e.getX() >= 10 && e.getX() <= 74) && (e.getY() >= 60 && e.getY() <= 124)) { //if user clicks on the clearing X.
b.setColor(canvasColour);
b.fillRect(canvas.getMinX(), canvas.getMinY(), canvas.getWidth(), canvas.getHeight()); //fill a large rectangle to clear the screen
repaint();
//resets the canvas and brush paint back to black, the default.
brush.setColor(Color.BLACK);
b.setColor(brush.getColor());
brush.setShape(PaintBrush.CIRCLE);
brush.setSize(PaintBrush.SMALL);
Logger.logUserMessage("Cleared the canvas.");
}
}
@Deprecated
public void mouseEntered(MouseEvent e) {
}
@Deprecated
public void mouseExited(MouseEvent e) {
}
@Override
public void addNotify() {
super.addNotify();
requestFocus(); //brings the window to the screen.
Logger.logOtherMessage("Window", "Requesting focus on the window.");
}
@Override
public void mouseDragged(MouseEvent e) {
dynamicMouseX = e.getX();
dynamicMouseY = e.getY();
if (e.getY() > 150) {
b.setColor(brush.getColor());
repaint();
if (brush.getShape() == PaintBrush.CIRCLE && brush.isDown()) { //circle brush
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillOval(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillOval(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillOval(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillOval(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
} else if (brush.getShape() == PaintBrush.SQUARE && brush.isDown()) { //square brush
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillRect(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillRect(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillRect(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillRect(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
} else if (brush.getShape() == PaintBrush.ERASER && brush.isDown()) { //square brush.
switch (brush.getSize()) {
case PaintBrush.SMALL:
b.fillRect(e.getX() - 5, e.getY() - 150, 10, 10);
break;
case PaintBrush.MEDIUM:
b.fillRect(e.getX() - 25, e.getY() - 170, 50, 50);
break;
case PaintBrush.BIG:
b.fillRect(e.getX() - 45, e.getY() - 200, 90, 90);
break;
case PaintBrush.HUGE:
b.fillRect(e.getX() - 65, e.getY() - 210, 130, 130);
break;
}
}
}
repaint();
}
@Deprecated
public void mouseMoved(MouseEvent e) {
}
/**
* Method to fill an area with colour.
*
* @param g the graphics from paint
* @param color the colour to fill with
*/
private void fillWithColour(Graphics g, Color color, int startX, int startY) {
//todo recursive colour filling method
}
/**
* Method to set the current painting colour
*
* @param brush the brush from the panel
*/
private void setCurrentPaint(PaintBrush brush) {
if ((dynamicMouseX >= 500 && dynamicMouseX <= 510) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.RED);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to RED.");
} else if ((dynamicMouseX >= 515 && dynamicMouseX <= 525) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.BLUE);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to BLUE.");
} else if ((dynamicMouseX >= 530 && dynamicMouseX <= 540) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.orange);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to ORANGE.");
} else if ((dynamicMouseX >= 545 && dynamicMouseX <= 555) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.yellow);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to YELLOW.");
} else if ((dynamicMouseX >= 560 && dynamicMouseX <= 570) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.green);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to GREEN.");
} else if ((dynamicMouseX >= 575 && dynamicMouseX <= 585) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.black);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to BLACK.");
} else if ((dynamicMouseX >= 590 && dynamicMouseX <= 600) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.CYAN);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to CYAN.");
} else if ((dynamicMouseX >= 605 && dynamicMouseX <= 615) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.pink);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to PINK.");
} else if ((dynamicMouseX >= 620 && dynamicMouseX <= 630) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.MAGENTA);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to MAGENTA.");
} else if ((dynamicMouseX >= 635 && dynamicMouseX <= 645) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(new Color(150, 70, 0));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to BROWN.");
} else if ((dynamicMouseX >= 650 && dynamicMouseX <= 660) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(new Color(0, 0, 100));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to DARK_BLUE.");
} else if ((dynamicMouseX >= 665 && dynamicMouseX <= 675) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(new Color(100, 100, 0));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to OLIVE_GREEN.");
} else if ((dynamicMouseX >= 680 && dynamicMouseX <= 690) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(Color.GRAY);
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to GREY.");
} else if ((dynamicMouseX >= 695 && dynamicMouseX <= 705) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(new Color(232, 227, 163));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to TAN.");
} else if ((dynamicMouseX >= 710 && dynamicMouseX <= 720) && (dynamicMouseY >= 40 && dynamicMouseY <= 50)) {
brush.setColor(new Color(163, 255, 210));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to LIGHT_GREEN.");
} else if ((dynamicMouseX >= 500 && dynamicMouseX <= 510) && (dynamicMouseY >= 60 && dynamicMouseY <= 70)) {
brush.setColor(new Color(67, 97, 178));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to NAVY_BLUE");
} else if ((dynamicMouseX >= 515 && dynamicMouseX <= 525) && (dynamicMouseY >= 60 && dynamicMouseY <= 70)) {
brush.setColor(new Color(110, 8, 0));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to DARK_RED");
} else if ((dynamicMouseX >= 500 && dynamicMouseX <= 510) && (dynamicMouseY >= 60 && dynamicMouseY <= 70)) {
brush.setColor(new Color(197, 232, 255));
non_eraserColor = brush.getColor();
Logger.logUserMessage("Set the colour of the brush to BABY_BLUE");
}
}
/**
* Method to open a dialogue to let the user set their own colour.
*
* @param brush the paintbrush, to set the colour to.
*/
private void getUserRGB(PaintBrush brush) {
try {
int r = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter RED's value."));
int g = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter GREEN's value."));
int b = Integer.parseInt(JOptionPane.showInputDialog(null, "Please enter BLUE's value."));
//if numbers are too high or low, fix them.
if (r > 255) r = 255;
if (r < 0) r = 0;
if (g > 255) g = 255;
if (g < 0) g = 0;
if (b > 255) b = 255;
if (b < 0) b = 0;
brush.setColor(new Color(r, g, b));
} catch (Exception e) {
System.err.println("[Error] Color selector had an issue.");
Logger.logErrorMessage("Seems the colour selector had an issue. Ending it silently...");
}
}
}
|
package sk.lovasko.trnava.gui;
import sk.lovasko.trnava.renderer.Renderer;
import sk.lovasko.trnava.renderer.SerialRenderer;
import sk.lovasko.trnava.renderer.ParallelRenderer;
import sk.lovasko.trnava.strategy.Strategy;
import sk.lovasko.trnava.strategy.SineStrategy;
import sk.lovasko.trnava.strategy.HighContrastStrategy;
import sk.lovasko.trnava.strategy.GradientStrategy;
import sk.lovasko.trnava.palette.Palette;
import sk.lovasko.trnava.palette.SolidPalette;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.*;
final class DetailListener implements ActionListener
{
private final int detail;
private final Window window;
public
DetailListener (final int detail, final Window window)
{
this.detail = detail;
this.window = window;
}
public void
actionPerformed (ActionEvent ae)
{
window.max_limit = detail;
window.recompute();
}
}
public class Window extends JFrame
{
private boolean show_rect;
private int mouse_x;
private int mouse_y;
private int radius;
private double minx;
private double miny;
private double maxx;
private double maxy;
public int max_limit;
private Component component;
private Canvas canvas;
private BufferStrategy buffer_strategy;
private SerialRenderer serial_renderer;
private ParallelRenderer parallel_renderer;
private Renderer renderer;
private SineStrategy sine_strategy;
private HighContrastStrategy high_contrast_strategy;
private GradientStrategy gradient_strategy;
private Strategy strategy;
private SolidPalette white_black_solid_palette;
private Palette palette;
private JMenuBar menu_bar;
private JMenu renderer_menu;
private JMenu detail_menu;
private JMenu strategy_menu;
private JMenu palette_menu;
private JRadioButtonMenuItem serial_renderer_item;
private JRadioButtonMenuItem parallel_renderer_item;
private JRadioButtonMenuItem detail_very_low_item;
private JRadioButtonMenuItem detail_low_item;
private JRadioButtonMenuItem detail_medium_item;
private JRadioButtonMenuItem detail_high_item;
private JRadioButtonMenuItem detail_very_high_item;
private JRadioButtonMenuItem detail_ultra_high_item;
private JRadioButtonMenuItem sine_strategy_item;
private JRadioButtonMenuItem high_contrast_strategy_item;
private JRadioButtonMenuItem gradient_strategy_item;
private JRadioButtonMenuItem white_black_solid_palette_item;
@Override
public final void
paint(Graphics g)
{
g = buffer_strategy.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
super.paint(g);
if (show_rect)
{
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
0.5f));
g2d.setBackground(new Color(255, 170, 0, 128));
g2d.setColor(Color.yellow);
g2d.fillRect(mouse_x - radius / 2 * 3, mouse_y - radius, radius * 3,
radius * 2);
}
buffer_strategy.show();
}
private final void
set_defaults ()
{
minx = -2.0;
miny = -1.0;
maxx = 1.0;
maxy = 1.0;
max_limit = 50;
renderer = serial_renderer;
strategy = gradient_strategy;
palette = white_black_solid_palette;
radius = 50;
mouse_x = 0;
mouse_y = 0;
show_rect = true;
serial_renderer_item.setSelected(true);
gradient_strategy_item.setSelected(true);
detail_low_item.setSelected(true);
white_black_solid_palette_item.setSelected(true);
}
private final void
init_menubar ()
{
menu_bar = new JMenuBar();
renderer_menu = new JMenu("Renderer");
detail_menu = new JMenu("Detail");
strategy_menu = new JMenu("Paint strategy");
palette_menu = new JMenu("Color palette");
menu_bar.add(renderer_menu);
menu_bar.add(detail_menu);
menu_bar.add(strategy_menu);
menu_bar.add(palette_menu);
menu_bar.setVisible(true);
setJMenuBar(menu_bar);
}
private final void
init_renderer_menu ()
{
serial_renderer_item = new JRadioButtonMenuItem("Serial");
parallel_renderer_item = new JRadioButtonMenuItem("Parallel");
ButtonGroup renderer_group = new ButtonGroup();
renderer_group.add(serial_renderer_item);
renderer_group.add(parallel_renderer_item);
renderer_menu.add(serial_renderer_item);
renderer_menu.add(parallel_renderer_item);
serial_renderer_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
renderer = serial_renderer;
recompute();
}
});
parallel_renderer_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
renderer = parallel_renderer;
recompute();
}
});
}
private final void
init_detail_menu ()
{
detail_very_low_item = new JRadioButtonMenuItem("Very low");
detail_low_item = new JRadioButtonMenuItem("Low");
detail_medium_item = new JRadioButtonMenuItem("Medium");
detail_high_item = new JRadioButtonMenuItem("High");
detail_very_high_item = new JRadioButtonMenuItem("Very high");
detail_ultra_high_item = new JRadioButtonMenuItem("Ultra high");
ButtonGroup detail_group = new ButtonGroup();
detail_group.add(detail_very_low_item);
detail_group.add(detail_low_item);
detail_group.add(detail_medium_item);
detail_group.add(detail_high_item);
detail_group.add(detail_very_high_item);
detail_group.add(detail_ultra_high_item);
detail_menu.add(detail_very_low_item);
detail_menu.add(detail_low_item);
detail_menu.add(detail_medium_item);
detail_menu.add(detail_high_item);
detail_menu.add(detail_very_high_item);
detail_menu.add(detail_ultra_high_item);
detail_very_low_item.addActionListener(new DetailListener(15, this));
detail_low_item.addActionListener(new DetailListener(50, this));
detail_medium_item.addActionListener(new DetailListener(250, this));
detail_high_item.addActionListener(new DetailListener(500, this));
detail_very_high_item.addActionListener(new DetailListener(5000, this));
detail_ultra_high_item.addActionListener(new DetailListener(10000, this));
}
private final void
init_strategy_menu ()
{
high_contrast_strategy_item = new JRadioButtonMenuItem("High contrast");
gradient_strategy_item = new JRadioButtonMenuItem("Jump distance gradient");
sine_strategy_item = new JRadioButtonMenuItem("Sine of distance");
ButtonGroup strategy_group = new ButtonGroup();
strategy_group.add(high_contrast_strategy_item);
strategy_group.add(gradient_strategy_item);
strategy_group.add(sine_strategy_item);
strategy_menu.add(high_contrast_strategy_item);
strategy_menu.add(gradient_strategy_item);
strategy_menu.add(sine_strategy_item);
high_contrast_strategy_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
strategy = high_contrast_strategy;
recompute();
}
});
gradient_strategy_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
strategy = gradient_strategy;
recompute();
}
});
sine_strategy_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
strategy = sine_strategy;
recompute();
}
});
}
private final void
init_palette_menu ()
{
white_black_solid_palette_item = new JRadioButtonMenuItem("B&W");
ButtonGroup palette_group = new ButtonGroup();
palette_group.add(white_black_solid_palette_item);
white_black_solid_palette_item.addActionListener(new ActionListener()
{
public void
actionPerformed (ActionEvent ae)
{
palette = white_black_solid_palette;
recompute();
}
});
}
private final void
init_renderers ()
{
renderer = null;
serial_renderer = new SerialRenderer();
parallel_renderer = new ParallelRenderer(4, new Dimension(60, 40));
}
private final void
init_strategies ()
{
strategy = null;
sine_strategy = new SineStrategy();
high_contrast_strategy = new HighContrastStrategy();
gradient_strategy = new GradientStrategy();
}
private final void
init_palettes ()
{
palette = null;
white_black_solid_palette = new SolidPalette(Color.black.toRGB(),
Color.white.toRGB());
}
private final void
initialize ()
{
component = getGlassPane();
setTitle("Mandelbrot set");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
createBufferStrategy(2);
buffer_strategy = getBufferStrategy();
enableEvents(
AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK |
AWTEvent.MOUSE_WHEEL_EVENT_MASK);
}
public final void
recompute ()
{
Thread thread = new Thread()
{
public final void
run ()
{
canvas.image = renderer.render(minx, miny, maxx, maxy, max_limit,
strategy, palette, new Dimension(600, 400));
repaint();
}
};
thread.start();
}
public
Window ()
{
initialize();
init_menubar();
init_renderer_menu();
init_detail_menu();
init_strategy_menu();
init_palette_menu();
init_renderers();
init_strategies();
init_palettes();
set_defaults();
canvas = new Canvas();
add(canvas);
setSize(600, 400 + getJMenuBar().getHeight() + getInsets().top);
addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent me) {
if (me.getButton() == java.awt.event.MouseEvent.BUTTON1 && show_rect == true) {
int dx, dy;
dx = 0;
dy = getInsets().top + getJMenuBar().getHeight();
double ix = minx, ax = maxx, iy = miny, ay = maxy;
int startx = mouse_x - radius / 2 * 3;
int endx = mouse_x + radius / 2 * 3;
int starty = mouse_y - radius;
int endy = mouse_y + radius;
minx = ix + ((double) (startx - dx) * (ax - ix) / 600.0);
miny = iy + ((double) (starty - dy) * (ay - iy) / 400.0);
maxx = ix + ((double) (endx - dx) * (ax - ix) / 600.0);
maxy = iy + ((double) (endy - dy) * (ay - iy) / 400.0);
c.render(minx, miny, maxx, maxy, limit);
repaint();
} else if (me.getButton() == java.awt.event.MouseEvent.BUTTON2) {
show_rect = !show_rect;
repaint();
}
}
public void mousePressed(MouseEvent me) {
}
public void mouseReleased(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
});
addMouseMotionListener(new MouseMotionListener() {
public void mouseDragged(MouseEvent me) {
}
public void mouseMoved(MouseEvent me) {
mouse_x = me.getX();
mouse_y = me.getY();
if (mouse_x - radius / 2 * 3 < 0) {
mouse_x = 0 + radius / 2 * 3;
}
if (mouse_y - radius < getJMenuBar().getHeight() + getInsets().top) {
mouse_y = getInsets().top + getJMenuBar().getHeight() + radius;
}
if (mouse_x + radius / 2 * 3 > getWidth()) {
mouse_x = getWidth() - radius / 2 * 3;
}
if (mouse_y + radius > getHeight()) {
mouse_y = getHeight() - radius;
}
repaint();
}
});
addMouseWheelListener(new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent mwe) {
radius += mwe.getWheelRotation() * 4;
if (radius > 180) {
radius = 180;
}
if (radius < 20) {
radius = 20;
}
if (mouse_x - radius / 2 * 3 < 0) {
mouse_x = 0 + radius / 2 * 3;
}
if (mouse_y - radius < 0) {
mouse_y = 0 + radius;
}
if (mouse_x + radius / 2 * 3 > getWidth()) {
mouse_x = getWidth() - radius / 2 * 3;
}
if (mouse_y + radius > getHeight()) {
mouse_y = getHeight() - radius;
}
repaint();
}
});
c.render(minx, miny, maxx, maxy, limit);
repaint();
}
}
|
package guitests;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import org.junit.After;
import org.junit.Test;
import org.loadui.testfx.utils.FXTestUtils;
import prefs.Preferences;
import ui.RepositorySelector;
import ui.UI;
import ui.issuepanel.IssuePanel;
import util.events.UILogicRefreshEvent;
import util.events.UpdateDummyRepoEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class RangeTest extends UITest {
private static final int EVENT_DELAY = 500;
@Test
public void numberRangeTest() {
((TextField) find("#dummy/dummy_col0_filterTextField")).setText("id:>5");
click("#dummy/dummy_col0_filterTextField");
press(KeyCode.ENTER).release(KeyCode.ENTER);
sleep(EVENT_DELAY);
assertEquals(5, ((IssuePanel) find("#dummy/dummy_col0")).getIssueCount());
}
@Test
public void dateRangeTest() {
((TextField) find("#dummy/dummy_col0_filterTextField")).setText("created:>2002-12-31");
click("#dummy/dummy_col0_filterTextField");
press(KeyCode.ENTER).release(KeyCode.ENTER);
sleep(EVENT_DELAY);
assertEquals(6, ((IssuePanel) find("#dummy/dummy_col0")).getIssueCount());
}
}
|
package iris.ssrs;
import iris.ssrs.api.ArrayOfProperty;
import iris.ssrs.api.ArrayOfWarning;
import iris.ssrs.api.CredentialRetrievalEnum;
import iris.ssrs.api.DataSourceDefinition;
import iris.ssrs.api.ItemTypeEnum;
import iris.ssrs.api.ReportingService2005;
import iris.ssrs.api.ReportingService2005Soap;
import iris.ssrs.api.Warning;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
/**
* Adapter class for interacting with the SSRS service from ruby code.
*/
@SuppressWarnings( { "UnusedDeclaration" } )
public class SSRS
{
private static final Logger LOG = Logger.getLogger( SSRS.class.getName() );
private static final String PATH_SEPARATOR = "/";
private final ReportingService2005Soap _soap;
private final String _prefix;
/**
* Create an adapter for a specific service, acting on a particular path.
*
* @param wsdlURL the URL to the wsdl for the service
* @param prefix the prefix for all reports interacted with by this adapter
*/
public SSRS( final URL wsdlURL, final String prefix )
{
if ( null == wsdlURL )
{
throw new NullPointerException( "wsdlURL" );
}
if ( null == prefix )
{
throw new NullPointerException( "prefix" );
}
_prefix = prefix;
final QName qName =
new QName( "http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices",
"ReportingService2005" );
final ReportingService2005 service = new ReportingService2005( wsdlURL, qName );
_soap = service.getReportingService2005Soap();
}
/**
* A helper method to configure the logging.
* Used from jruby.
*/
public static void setupLogger( final boolean verbose )
{
LOG.setUseParentHandlers( false );
LOG.setLevel( verbose ? Level.ALL : Level.INFO );
final ConsoleHandler handler = new ConsoleHandler();
handler.setFormatter( new Formatter()
{
@Override
public String format( final LogRecord record )
{
return record.getMessage() + "\n";
}
} );
LOG.addHandler( handler );
}
/**
* Log a info message.
* Used from ruby code. (Not using LOG directly as overloading confuses ruby)
*/
public static void info( final String message )
{
LOG.info( message );
}
/**
* Log a warning message.
* Used from ruby code. (Not using LOG directly as overloading confuses ruby)
*/
public static void warning( final String message )
{
LOG.warning( message );
}
/**
* Create a data source at path with a specific connection string.
*/
public void createSQLDataSource( final String path, final String connectionString )
{
final DataSourceDefinition definition = new DataSourceDefinition();
definition.setConnectString( connectionString );
definition.setEnabled( true );
definition.setExtension( "SQL" );
definition.setImpersonateUser( false );
definition.setPrompt( null );
definition.setCredentialRetrieval( CredentialRetrievalEnum.NONE );
definition.setWindowsCredentials( false );
createDataSource( path, definition );
}
/**
* Create a data source at path with a using a complete data definition.
*/
public void createDataSource( final String path, final DataSourceDefinition definition )
{
info( "Creating DataSource " + path );
final String physicalName = toPhysicalFileName( path );
final String reportName = filenameFromPath( physicalName );
final String reportDir = dirname( physicalName );
final ItemTypeEnum type = _soap.getItemType( physicalName );
if ( ItemTypeEnum.UNKNOWN != type )
{
final String s = "Can not create data source as path " + path + " exists and is of type " + type + ".";
throw new IllegalStateException( s );
}
else
{
_soap.createDataSource( reportName, reportDir, false, definition, new ArrayOfProperty() );
}
}
/**
* Create a report at specific path from specified report file. Path must not exist.
*/
public void createReport( final String path, final File file )
{
info( "Creating Report " + path );
final String physicalName = toPhysicalFileName( path );
LOG.fine( "Creating Report with symbolic item " + path + " as " + physicalName );
final ItemTypeEnum type = _soap.getItemType( physicalName );
if ( ItemTypeEnum.UNKNOWN != type )
{
final String s = "Can not create report as path " + physicalName + " exists and is of type " + type + ".";
throw new IllegalStateException( s );
}
else
{
final byte[] bytes = readFully( path, file );
final String reportName = filenameFromPath( physicalName );
final String reportDir = dirname( physicalName );
LOG.finer( "Invoking createReport(name=" + reportName + ",parentDir=" + reportDir + ")" );
final ArrayOfWarning warnings =
_soap.createReport( reportName, reportDir, true, bytes, new ArrayOfProperty() );
if ( null != warnings )
{
final String message =
"createReport(name=" + reportName + ",parentDir=" + reportDir + ") from " + file.getAbsolutePath();
logWarnings( message, warnings );
}
}
}
/**
* Delete symbolic path and all sub elements. Will skip if no such path.
*/
public void delete( final String path )
{
info( "Deleting item " + path );
final String physicalName = toPhysicalFileName( path );
LOG.fine( "Deleting symbolic item " + path + " as " + physicalName );
final ItemTypeEnum type = _soap.getItemType( physicalName );
if ( ItemTypeEnum.UNKNOWN == type )
{
LOG.finer( "Skipping invocation of deleteItem(item=" + physicalName + ") as item does not exist." );
}
else
{
LOG.finer( "Invoking deleteItem(item=" + physicalName + ")" );
_soap.deleteItem( physicalName );
}
}
/**
* Create a directory node at specified path. Path must not exist.
*/
public void mkdir( final String filePath )
{
info( "Creating dir " + filePath );
final String physicalName = toPhysicalFileName( filePath );
LOG.fine( "Creating symbolic dir " + filePath + " as " + physicalName );
final StringBuilder path = new StringBuilder();
for ( final String dir : physicalName.substring( 1 ).split( PATH_SEPARATOR ) )
{
final String parentDir = ( path.length() == 0 ) ? PATH_SEPARATOR : path.toString();
final ItemTypeEnum type = _soap.getItemType( path.toString() + PATH_SEPARATOR + dir );
if ( ItemTypeEnum.UNKNOWN == type )
{
LOG.finer( "Invoking createFolder(dir=" + dir + ",parentDir=" + parentDir + ")" );
_soap.createFolder( dir, parentDir, new ArrayOfProperty() );
}
else if ( ItemTypeEnum.FOLDER != type )
{
final String s = "Path " + path + " exists and is not a folder but a " + type;
throw new IllegalStateException( s );
}
else
{
final String message =
"Skipping invocation of createFolder(dir=" + dir + ",parentDir=" + parentDir + ") as folder exists";
LOG.finer( message );
}
path.append( PATH_SEPARATOR );
path.append( dir );
}
}
private String filenameFromPath( final String path )
{
final int index = path.lastIndexOf( PATH_SEPARATOR );
if ( -1 == index )
{
return path;
}
else
{
return path.substring( index + 1 );
}
}
private String dirname( final String path )
{
final int index = path.lastIndexOf( PATH_SEPARATOR );
if ( -1 == index )
{
return "";
}
else
{
return path.substring( 0, index );
}
}
/**
* Return the fully qualified path for specified name.
*/
private String toPhysicalFileName( final String name )
{
return nameComponent( _prefix ) + nameComponent( name );
}
private String nameComponent( final String name )
{
if ( 0 == name.length() || PATH_SEPARATOR.equals( name ) )
{
return "";
}
else if ( name.startsWith( PATH_SEPARATOR ) )
{
return name;
}
else
{
return PATH_SEPARATOR + name;
}
}
private void logWarnings( final String message, final ArrayOfWarning warnings )
{
for ( final Warning warning : warnings.getWarning() )
{
warning( "Action '" + message + "' resulted in warning " +
" Code=" + warning.getCode() +
" ObjectName=" + warning.getObjectName() +
" ObjectType=" + warning.getObjectType() +
" Severity=" + warning.getSeverity() +
" Message=" + warning.getMessage() );
}
}
private byte[] readFully( final String name, final File file )
{
if ( !file.exists() )
{
final String message = "Report file " + file.getAbsolutePath() + " for " + name + " does not exist.";
throw new IllegalStateException( message );
}
try
{
final byte[] bytes = new byte[(int) file.length()];
new DataInputStream( new FileInputStream( file ) ).readFully( bytes );
return bytes;
}
catch ( IOException e )
{
throw new IllegalStateException( "Unable to load report file " + file.getAbsolutePath() );
}
}
}
|
package com.elmakers.mine.bukkit.essentials;
import com.elmakers.mine.bukkit.api.spell.SpellCategory;
import net.ess3.api.IEssentials;
import org.bukkit.inventory.ItemStack;
import com.earth2me.essentials.ItemDb;
import com.elmakers.mine.bukkit.magic.MagicController;
import com.elmakers.mine.bukkit.wand.Wand;
public class MagicItemDb extends ItemDb {
private final MagicController controller;
public MagicItemDb(final MagicController controller, final Object ess) {
super((IEssentials)ess);
this.controller = controller;
this.reloadConfig();
}
@Override
public ItemStack get(final String id) throws Exception
{
if (id.startsWith("m:")) {
String itemId = id.replace("m:", "");
return controller.createItem(itemId);
} if (id.startsWith("magic:")) {
String itemId = id.replace("magic:", "");
return controller.createItem(itemId);
} else if (id.equals("wand")) {
Wand wand = Wand.createWand(controller, "");
if (wand != null) {
return wand.getItem();
}
} else if (id.startsWith("wand:")) {
String wandId = id.replace("wand:", "");
Wand wand = Wand.createWand(controller, wandId.trim());
if (wand != null) {
return wand.getItem();
}
} else if (id.startsWith("w:")) {
String wandId = id.replace("w:", "");
Wand wand = Wand.createWand(controller, wandId.trim());
if (wand != null) {
return wand.getItem();
}
} else if (id.startsWith("book:")) {
String bookCategory = id.replace("book:", "");
SpellCategory category = null;
if (bookCategory.length() > 0 && !bookCategory.equalsIgnoreCase("all")) {
category = controller.getCategory(bookCategory);
}
ItemStack bookItem = controller.getSpellBook(category, 1);
if (bookItem != null) {
return bookItem;
}
} else if (id.startsWith("spell:")) {
String spellKey = id.replace("spell:", "");
ItemStack itemStack = Wand.createSpellItem(spellKey, controller, null, true);
if (itemStack != null) {
return itemStack;
}
} else if (id.startsWith("s:")) {
String spellKey = id.replace("s:", "");
ItemStack itemStack = Wand.createSpellItem(spellKey, controller, null, true);
if (itemStack != null) {
return itemStack;
}
} else if (id.startsWith("brush:")) {
String brushKey = id.replace("brush:", "");
ItemStack itemStack = Wand.createBrushItem(brushKey, controller, null, true);
if (itemStack != null) {
return itemStack;
}
} else if (id.startsWith("upgrade:")) {
String wandId = id.replace("upgrade:", "");
Wand wand = Wand.createWand(controller, wandId.trim());
if (wand != null) {
wand.makeUpgrade();
return wand.getItem();
}
} else if (id.startsWith("item:")) {
String wandId = id.replace("item:", "");
return controller.createItem(wandId);
}
return super.get(id);
}
}
|
package org.pwsafe.passwordsafeswt.dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pwsafe.passwordsafeswt.util.ShellHelpers;
import org.pwsafe.passwordsafeswt.util.VersionInfo;
import com.swtdesigner.SWTResourceManager;
/**
* StartupDialog is shown when the app starts up and is modal in front on the main window.
*
* @author Glen Smith
*/
public class StartupDialog extends Dialog {
private Combo cboFilename;
private Text txtPassword;
protected Object result;
protected Shell shell;
private String[] mruList;
private String selectedFile;
private String selectedPassword;
public static final String OPEN_FILE = "open-selected"; // open the selected file
public static final String OPEN_OTHER = "open-other"; // open file dialog for other file
public static final String NEW_FILE = "new"; // create a new safe
public static final String CANCEL = "cancel"; // exit the app
public StartupDialog(Shell parent, int style) {
super(parent, style);
}
public StartupDialog(Shell parent, String[] mru) {
this(parent, SWT.NONE);
this.mruList = mru;
}
public Object open() {
createContents();
ShellHelpers.centreShell(getParent(), shell);
shell.open();
shell.layout();
if (mruList != null) {
for (int i=0; i < mruList.length; i++) {
cboFilename.add(mruList[i]);
}
cboFilename.setText(mruList[0]);
}
Display display = getParent().getDisplay();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
return result;
}
/**
* Create dialog elements.
*/
protected void createContents() {
shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
shell.setLayout(new FormLayout());
shell.setImage(SWTResourceManager.getImage(StartupDialog.class, "/org/pwsafe/passwordsafeswt/images/clogo.gif"));
shell.setSize(550, 368);
shell.setText("Safe Combination Entry");
final Label lblTextLogo = new Label(shell, SWT.NONE);
lblTextLogo.setAlignment(SWT.CENTER);
lblTextLogo.setImage(SWTResourceManager.getImage(StartupDialog.class, "/org/pwsafe/passwordsafeswt/images/psafetxtNew.gif"));
final FormData formData_10 = new FormData();
formData_10.left = new FormAttachment(24, 0);
formData_10.top = new FormAttachment(0, 15);
lblTextLogo.setLayoutData(formData_10);
final Label lblPleaseEnter = new Label(shell, SWT.NONE);
final FormData formData = new FormData();
//formData.top = new FormAttachment(0, 55);
formData.top = new FormAttachment(lblTextLogo, 15);
formData.left = new FormAttachment(0, 55);
lblPleaseEnter.setLayoutData(formData);
lblPleaseEnter.setText("Please enter the safe combination for the password database:");
final Label lblFilename = new Label(shell, SWT.NONE);
lblFilename.setText("&Filename:");
final FormData formData_1 = new FormData();
formData_1.top = new FormAttachment(lblPleaseEnter, 15, SWT.BOTTOM);
formData_1.left = new FormAttachment(lblPleaseEnter, 15, SWT.LEFT);
lblFilename.setLayoutData(formData_1);
cboFilename = new Combo(shell, SWT.READ_ONLY);
final FormData formData_1b = new FormData();
formData_1b.top = new FormAttachment(lblFilename, 0, SWT.TOP);
formData_1b.left = new FormAttachment(lblFilename, 15, SWT.RIGHT);
formData_1b.right = new FormAttachment(100, -170);
cboFilename.setLayoutData(formData_1b);
final Label lblSafeCombination = new Label(shell, SWT.NONE);
final FormData formData_2 = new FormData();
formData_2.top = new FormAttachment(lblFilename, 20);
formData_2.right = new FormAttachment(lblFilename, 0, SWT.RIGHT);
lblSafeCombination.setLayoutData(formData_2);
lblSafeCombination.setText("&Safe Combination:");
txtPassword = new Text(shell, SWT.BORDER);
txtPassword.setEchoChar('*');
final FormData formData_3 = new FormData();
formData_3.top = new FormAttachment(lblSafeCombination, 0, SWT.TOP);
formData_3.left = new FormAttachment(cboFilename, 0, SWT.LEFT);
formData_3.right = new FormAttachment(cboFilename, 0, SWT.RIGHT);
txtPassword.setLayoutData(formData_3);
final Button btnReadOnly = new Button(shell, SWT.CHECK);
final FormData formData_4 = new FormData();
formData_4.top = new FormAttachment(txtPassword, 15);
formData_4.left = new FormAttachment(txtPassword, 0, SWT.LEFT);
btnReadOnly.setLayoutData(formData_4);
btnReadOnly.setText("&Open as read-only");
final Button btnCreate = new Button(shell, SWT.NONE);
btnCreate.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
result = StartupDialog.NEW_FILE;
shell.dispose();
}
});
final FormData formData_5 = new FormData();
formData_5.top = new FormAttachment(cboFilename, 0, SWT.TOP);
formData_5.right = new FormAttachment(100, -5);
btnCreate.setLayoutData(formData_5);
btnCreate.setText("&Create new safe... ");
final Button btnOpen = new Button(shell, SWT.NONE);
btnOpen.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
result = StartupDialog.OPEN_OTHER;
selectedFile = cboFilename.getText();
selectedPassword = txtPassword.getText();
shell.dispose();
}
});
final FormData formData_6 = new FormData();
formData_6.top = new FormAttachment(btnCreate, 10);
formData_6.left = new FormAttachment(btnCreate, 0, SWT.LEFT);
formData_6.right = new FormAttachment(btnCreate, 0, SWT.RIGHT);
btnOpen.setLayoutData(formData_6);
btnOpen.setText("&Open other safe...");
final Button btnOk = new Button(shell, SWT.NONE);
shell.setDefaultButton(btnOk);
btnOk.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
selectedFile = cboFilename.getText();
selectedPassword = txtPassword.getText();
result = StartupDialog.OPEN_FILE;
shell.dispose();
}
});
final FormData formData_7 = new FormData();
formData_7.width = 80;
formData_7.left = new FormAttachment(50, -80);
formData_7.bottom = new FormAttachment(100, -10);
btnOk.setLayoutData(formData_7);
btnOk.setText("OK");
final Button btnCancel = new Button(shell, SWT.NONE);
btnCancel.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
result = StartupDialog.CANCEL;
shell.dispose();
}
});
final FormData formData_8 = new FormData();
formData_8.width = 80;
formData_8.left = new FormAttachment(btnOk, 10);
formData_8.top = new FormAttachment(btnOk, 0, SWT.TOP);
btnCancel.setLayoutData(formData_8);
btnCancel.setText("Cancel");
final Button btnHelp = new Button(shell, SWT.NONE);
final FormData formData_9 = new FormData();
formData_9.width = 80;
formData_9.top = new FormAttachment(btnCancel, 0, SWT.TOP);
formData_9.left = new FormAttachment(btnCancel, 10);
btnHelp.setLayoutData(formData_9);
btnHelp.setText("Help");
final Label lblVersion = new Label(shell, SWT.NONE);
final FormData formData_11 = new FormData();
formData_11.top = new FormAttachment(btnReadOnly, 0, SWT.TOP);
formData_11.left = new FormAttachment(btnOpen, 0, SWT.LEFT);
lblVersion.setLayoutData(formData_11);
lblVersion.setText("Version: " + VersionInfo.getVersion());
}
/**
* Returns the filename selected in the dialog.
*
* @return the filename selected in the dialog
*/
public String getFilename() {
return selectedFile;
}
/**
* Returns the password entered in the dialog.
*
* @return the password entered in the dialog
*/
public String getPassword() {
return selectedPassword;
}
}
|
package yuku.alkitab.base.ac;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.PopupMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import yuku.afw.App;
import yuku.afw.V;
import yuku.afw.storage.Preferences;
import yuku.alkitab.base.S;
import yuku.alkitab.base.config.AppConfig;
import yuku.alkitab.base.model.ReadingPlan;
import yuku.alkitab.base.storage.Prefkey;
import yuku.alkitab.base.util.ReadingPlanManager;
import yuku.alkitab.base.util.Sqlitil;
import yuku.alkitab.debug.R;
import yuku.alkitab.model.Version;
import yuku.alkitab.util.Ari;
import yuku.alkitab.util.IntArrayList;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class ReadingPlanActivity extends ActionBarActivity {
public static final String READING_PLAN_ARI_RANGES = "reading_plan_ari_ranges";
public static final String READING_PLAN_ID = "reading_plan_id";
public static final String READING_PLAN_DAY_NUMBER = "reading_plan_day_number";
private ReadingPlan readingPlan;
private List<ReadingPlan.ReadingPlanInfo> downloadedReadingPlanInfos;
private int todayNumber;
private int dayNumber;
private IntArrayList readingCodes;
private boolean newDropDownItems;
private ImageButton bLeft;
private ImageButton bRight;
private Button bToday;
private ListView lsReadingPlan;
private ReadingPlanAdapter readingPlanAdapter;
private ActionBar actionBar;
private LinearLayout llNavigations;
private FrameLayout flNoData;
private Button bDownload;
private boolean showDetails;
public static Intent createIntent(int dayNumber) {
Intent intent = new Intent(App.context, ReadingPlanActivity.class);
intent.putExtra(READING_PLAN_DAY_NUMBER, dayNumber);
return intent;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reading_plan);
llNavigations = V.get(this, R.id.llNavigations);
flNoData = V.get(this, R.id.flNoDataContainer);
lsReadingPlan = V.get(this, R.id.lsTodayReadings);
bToday = V.get(this, R.id.bToday);
bLeft = V.get(this, R.id.bLeft);
bRight = V.get(this, R.id.bRight);
bDownload = V.get(this, R.id.bDownload);
actionBar = getSupportActionBar();
long id = Preferences.getLong(Prefkey.active_reading_plan_id, 0);
loadReadingPlan(id);
loadReadingPlanProgress();
loadDayNumber();
prepareDropDownNavigation();
prepareDisplay();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_reading_plan, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.menuReset) {
resetReadingPlan();
return true;
} else if (itemId == R.id.menuDownload) {
downloadReadingPlan();
return true;
} else if (itemId == R.id.menuDelete) {
deleteReadingPlan();
return true;
} else if (itemId == R.id.menuAbout) {
showAbout();
}
return super.onOptionsItemSelected(item);
}
private void loadReadingPlan(long id) {
downloadedReadingPlanInfos = S.getDb().listAllReadingPlanInfo();
if (downloadedReadingPlanInfos.size() == 0) {
return;
}
long startDate = 0;
if (id == 0) {
id = downloadedReadingPlanInfos.get(0).id;
startDate = downloadedReadingPlanInfos.get(0).startDate;
} else {
for (ReadingPlan.ReadingPlanInfo info : downloadedReadingPlanInfos) {
if (id == info.id) {
startDate = info.startDate;
}
}
}
byte[] binaryReadingPlan = S.getDb().getBinaryReadingPlanById(id);
InputStream inputStream = new ByteArrayInputStream(binaryReadingPlan);
ReadingPlan res = ReadingPlanManager.readVersion1(inputStream);
res.info.id = id;
res.info.startDate = startDate;
readingPlan = res;
Preferences.setLong(Prefkey.active_reading_plan_id, id);
}
private void loadReadingPlanProgress() {
if (readingPlan == null) {
return;
}
readingCodes = S.getDb().getAllReadingCodesByReadingPlanId(readingPlan.info.id);
}
public void goToIsiActivity(final int dayNumber, final int sequence) {
final int[] selectedVerses = readingPlan.dailyVerses[dayNumber];
int ari = selectedVerses[sequence * 2];
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("ari", ari);
intent.putExtra(READING_PLAN_ID, readingPlan.info.id);
intent.putExtra(READING_PLAN_DAY_NUMBER, dayNumber);
intent.putExtra(READING_PLAN_ARI_RANGES, selectedVerses);
setResult(RESULT_OK, intent);
finish();
}
private void loadDayNumber() {
if (readingPlan == null) {
return;
}
Calendar startCalendar = GregorianCalendar.getInstance();
startCalendar.setTime(new Date(readingPlan.info.startDate));
todayNumber = calculateDaysDiff(startCalendar, GregorianCalendar.getInstance());
if (todayNumber >= readingPlan.info.duration) {
todayNumber = readingPlan.info.duration - 1;
} else if (todayNumber < 0) {
todayNumber = 0;
}
dayNumber = getIntent().getIntExtra(READING_PLAN_DAY_NUMBER, -1);
if (dayNumber == -1) {
dayNumber = todayNumber;
}
}
private int calculateDaysDiff(Calendar startCalendar, Calendar endCalendar) {
startCalendar.set(Calendar.HOUR_OF_DAY, 0);
startCalendar.set(Calendar.MINUTE, 0);
startCalendar.set(Calendar.SECOND, 0);
startCalendar.set(Calendar.MILLISECOND, 0);
endCalendar.set(Calendar.HOUR_OF_DAY, 0);
endCalendar.set(Calendar.MINUTE, 0);
endCalendar.set(Calendar.SECOND, 0);
endCalendar.set(Calendar.MILLISECOND, 0);
return (int) ((endCalendar.getTime().getTime() - startCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24));
}
public boolean prepareDropDownNavigation() {
if (downloadedReadingPlanInfos.size() == 0) {
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
return true;
}
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
long id = Preferences.getLong(Prefkey.active_reading_plan_id, 0);
int itemNumber = 0;
//Drop-down navigation
List<String> titles = new ArrayList<String>();
for (int i = 0; i < downloadedReadingPlanInfos.size(); i++) {
ReadingPlan.ReadingPlanInfo info = downloadedReadingPlanInfos.get(i);
titles.add(info.title);
if (info.id == id) {
itemNumber = i;
}
}
ArrayAdapter<String> navigationAdapter = new ArrayAdapter<String>(actionBar.getThemedContext(), R.layout.support_simple_spinner_dropdown_item, titles);
newDropDownItems = false;
actionBar.setListNavigationCallbacks(navigationAdapter, new ActionBar.OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(final int i, final long l) {
if (newDropDownItems) {
loadReadingPlan(downloadedReadingPlanInfos.get(i).id);
loadReadingPlanProgress();
loadDayNumber();
prepareDisplay();
}
return true;
}
});
actionBar.setSelectedNavigationItem(itemNumber);
newDropDownItems = true;
return false;
}
public void prepareDisplay() {
if (readingPlan == null) {
llNavigations.setVisibility(View.GONE);
lsReadingPlan.setVisibility(View.GONE);
flNoData.setVisibility(View.VISIBLE);
bDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
downloadReadingPlan();
}
});
return;
}
llNavigations.setVisibility(View.VISIBLE);
lsReadingPlan.setVisibility(View.VISIBLE);
flNoData.setVisibility(View.GONE);
//Listviews
readingPlanAdapter = new ReadingPlanAdapter();
readingPlanAdapter.load();
lsReadingPlan.setAdapter(readingPlanAdapter);
lsReadingPlan.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) {
final int todayReadingsSize = readingPlan.dailyVerses[dayNumber].length / 2;
if (position < todayReadingsSize) {
goToIsiActivity(dayNumber, position);
} else if (position > todayReadingsSize) {
goToIsiActivity(position - todayReadingsSize - 1, 0);
}
}
});
//buttons
updateButtonStatus();
bToday.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
final PopupMenu popupMenu = new PopupMenu(ReadingPlanActivity.this, v);
popupMenu.getMenu().add(Menu.NONE, 1, 1, getString(R.string.rp_showCalendar));
popupMenu.getMenu().add(Menu.NONE, 2, 2, getString(R.string.rp_gotoFirstUnread));
popupMenu.getMenu().add(Menu.NONE, 3, 3, getString(R.string.rp_gotoToday));
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final MenuItem menuItem) {
popupMenu.dismiss();
int itemId = menuItem.getItemId();
if (itemId == 1) {
showCalendar();
} else if (itemId == 2) {
gotoFirstUnread();
} else if (itemId == 3) {
gotoToday();
}
return true;
}
});
popupMenu.show();
}
private void gotoToday() {
loadDayNumber();
changeDay(0);
}
private void gotoFirstUnread() {
dayNumber = findFirstUnreadDay(readingPlan.info.duration - 1);
changeDay(0);
}
private void showCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(readingPlan.info.startDate));
calendar.add(Calendar.DATE, dayNumber);
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(final DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
Calendar newCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
Calendar startCalendar = GregorianCalendar.getInstance();
startCalendar.setTime(new Date(readingPlan.info.startDate));
int newDay = calculateDaysDiff(startCalendar, newCalendar);
if (newDay < 0) {
newDay = 0;
} else if (newDay >= readingPlan.info.duration) {
newDay = readingPlan.info.duration - 1;
}
dayNumber = newDay;
changeDay(0);
}
};
DatePickerDialog datePickerDialog = new DatePickerDialog(ReadingPlanActivity.this, dateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
datePickerDialog.show();
}
});
bLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
changeDay(-1);
}
});
bRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
changeDay(+1);
}
});
}
private void resetReadingPlan() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.rp_reset))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
int lastUnreadDay = findFirstUnreadDay(dayNumber);
Calendar calendar = GregorianCalendar.getInstance();
calendar.add(Calendar.DATE, -lastUnreadDay);
S.getDb().updateStartDate(readingPlan.info.id, calendar.getTime().getTime());
loadReadingPlan(readingPlan.info.id);
loadDayNumber();
readingPlanAdapter.load();
readingPlanAdapter.notifyDataSetChanged();
updateButtonStatus();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private int findFirstUnreadDay(final int dayUntil) {
for (int i = 0; i < dayUntil; i++) {
boolean[] readMarks = new boolean[readingPlan.dailyVerses[i].length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, i);
for (boolean readMark : readMarks) {
if (!readMark) {
return i;
}
}
}
return dayUntil;
}
private void deleteReadingPlan() {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.rp_deletePlan, readingPlan.info.title))
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
S.getDb().deleteReadingPlanById(readingPlan.info.id);
readingPlan = null;
Preferences.remove(Prefkey.active_reading_plan_id);
loadReadingPlan(0);
loadReadingPlanProgress();
loadDayNumber();
prepareDropDownNavigation();
prepareDisplay();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
}
private void showAbout() {
String message = getString(R.string.rp_aboutPlanMessage, readingPlan.info.title, readingPlan.info.description, readingPlan.info.duration);
new AlertDialog.Builder(ReadingPlanActivity.this)
.setMessage(message)
.setPositiveButton(R.string.ok, null)
.show();
}
private void changeDay(int day) {
dayNumber += day;
readingPlanAdapter.load();
readingPlanAdapter.notifyDataSetChanged();
updateButtonStatus();
}
private void updateButtonStatus() { //TODO look disabled
if (dayNumber == 0) {
bLeft.setEnabled(false);
bRight.setEnabled(true);
} else if (dayNumber == readingPlan.info.duration - 1) {
bLeft.setEnabled(true);
bRight.setEnabled(false);
} else {
bLeft.setEnabled(true);
bRight.setEnabled(true);
}
bToday.setText(getReadingDateHeader(dayNumber));
}
private void downloadReadingPlan() {
AppConfig config = AppConfig.get();
final List<ReadingPlan.ReadingPlanInfo> infos = config.readingPlanInfos;
final List<String> readingPlanTitles = new ArrayList<String>();
final List<Integer> resources = new ArrayList<Integer>();
for (int i = 0; i < infos.size(); i++) {
String title = infos.get(i).title;
boolean downloaded = false;
for (ReadingPlan.ReadingPlanInfo downloadedReadingPlanInfo : downloadedReadingPlanInfos) {
if (title.equals(downloadedReadingPlanInfo.title)) {
downloaded = true;
break;
}
}
if (!downloaded) {
readingPlanTitles.add(title);
String filename = infos.get(i).filename.replace(".rpb", ""); //TODO: proper method. testing only
resources.add(getResources().getIdentifier(filename, "raw", getPackageName())); //TODO: proper method
}
}
if (readingPlanTitles.size() == 0) {
new AlertDialog.Builder(this)
.setMessage(getString(R.string.rp_noReadingPlanAvailable))
.setPositiveButton(R.string.ok, null)
.show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, readingPlanTitles), new DialogInterface.OnClickListener() {
@Override
public void onClick(final DialogInterface dialog, final int which) {
long id = ReadingPlanManager.copyReadingPlanToDb(resources.get(which));
Preferences.setLong(Prefkey.active_reading_plan_id, id);
loadDayNumber();
loadReadingPlan(id);
loadReadingPlanProgress();
prepareDropDownNavigation();
prepareDisplay();
dialog.dismiss();
}
})
.setNegativeButton("Cancel", null)
.show();
}
}
private float getActualPercentage() {
float res = 100.f * countRead() / countAllReadings();
return res;
}
private float getTargetPercentage() {
float res = 100.f * countTarget() / countAllReadings();
return res;
}
private int countRead() {
IntArrayList filteredReadingCodes = ReadingPlanManager.filterReadingCodesByDayStartEnd(readingCodes, 0, todayNumber);
return filteredReadingCodes.size();
}
private int countTarget() {
int res = 0;
for (int i = 0; i <= todayNumber; i++) {
res += readingPlan.dailyVerses[i].length / 2;
}
return res;
}
private int countAllReadings() {
int res = 0;
for (int i = 0; i < readingPlan.info.duration; i++) {
res += readingPlan.dailyVerses[i].length / 2;
}
return res;
}
public String getReadingDateHeader(final int dayNumber) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(readingPlan.info.startDate));
calendar.add(Calendar.DATE, dayNumber);
String date = getString(R.string.rp_dayHeader, (dayNumber + 1), Sqlitil.toLocaleDateMedium(calendar.getTime()));
return date;
}
public static StringBuilder getReference(final Version version, final int ari_start, final int ari_end) {
final StringBuilder sb = new StringBuilder();
sb.append(version.reference(ari_start));
int startChapter = Ari.toChapter(ari_start);
int startVerse = Ari.toVerse(ari_start);
int lastVerse = Ari.toVerse(ari_end);
int lastChapter = Ari.toChapter(ari_end);
if (startVerse == 0) {
if (lastVerse == 0) {
if (startChapter != lastChapter) {
sb.append("-").append(lastChapter);
}
} else {
sb.append("-").append(lastChapter).append(":").append(lastVerse);
}
} else {
if (startChapter == lastChapter) {
sb.append("-").append(lastVerse);
} else {
sb.append("-").append(lastChapter).append(":").append(lastVerse);
}
}
return sb;
}
class ReadingPlanAdapter extends BaseAdapter {
private int[] todayReadings;
public void load() {
todayReadings = readingPlan.dailyVerses[dayNumber];
}
@Override
public int getCount() {
if (showDetails) {
return (todayReadings.length / 2) + readingPlan.info.duration + 1;
} else {
return (todayReadings.length / 2) + 1;
}
}
@Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final int itemViewType = getItemViewType(position);
final View res;
if (itemViewType == 0) {
res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_reading_plan_one_reading, parent, false);
final CheckBox checkbox = V.get(res, R.id.checkbox);
boolean[] readMarks = new boolean[todayReadings.length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, dayNumber);
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
ReadingPlanManager.updateReadingPlanProgress(readingPlan.info.id, dayNumber, position, isChecked);
loadReadingPlanProgress();
load();
notifyDataSetChanged();
}
});
int start = position * 2;
checkbox.setText(getReference(S.activeVersion, todayReadings[start], todayReadings[start + 1]));
checkbox.setChecked(readMarks[position * 2]);
} else if (itemViewType == 1) {
res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_reading_plan_summary, parent, false);
final ProgressBar pbReadingProgress = V.get(res, R.id.pbReadingProgress);
final TextView tActual = V.get(res, R.id.tActual);
final TextView tTarget = V.get(res, R.id.tTarget);
final TextView tComment = V.get(res, R.id.tComment);
final TextView tDetail = V.get(res, R.id.tDetail);
float actualPercentage = getActualPercentage();
float targetPercentage = getTargetPercentage();
pbReadingProgress.setMax(10000);
pbReadingProgress.setProgress((int) actualPercentage * 100);
pbReadingProgress.setSecondaryProgress((int) targetPercentage * 100);
tActual.setText(getString(R.string.rp_commentActual, String.format("%.2f", actualPercentage)));
tTarget.setText(getString(R.string.rp_commentTarget, String.format("%.2f", targetPercentage)));
String comment;
if (actualPercentage == targetPercentage) {
comment = getString(R.string.rp_commentOnSchedule);
} else {
String diff = String.format("%.2f", targetPercentage - actualPercentage);
comment = getString(R.string.rp_commentBehindSchedule, diff);
}
tComment.setText(comment);
tDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
showDetails = !showDetails;
if (showDetails) {
tDetail.setText(R.string.rp_hideDetails);
} else {
tDetail.setText(R.string.rp_showDetails);
}
notifyDataSetChanged();
}
});
} else if (itemViewType == 2) {
res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_reading_plan_one_day, parent, false);
final LinearLayout layout = V.get(res, R.id.llOneDayReadingPlan);
final int currentViewTypePosition = position - todayReadings.length / 2 - 1;
//Text title
TextView tTitle = V.get(res, android.R.id.text1);
tTitle.setText(getReadingDateHeader(currentViewTypePosition));
//Text reading
while (true) {
final View reading = layout.findViewWithTag("reading");
if (reading != null) {
layout.removeView(reading);
} else {
break;
}
}
int[] aris = readingPlan.dailyVerses[currentViewTypePosition];
for (int i = 0; i < aris.length / 2; i++) {
final int ariPosition = i;
CheckBox checkBox = new CheckBox(ReadingPlanActivity.this);
checkBox.setText(getReference(S.activeVersion, aris[i * 2], aris[i * 2 + 1]));
checkBox.setTag("reading");
boolean[] readMarks = new boolean[aris.length];
ReadingPlanManager.writeReadMarksByDay(readingCodes, readMarks, currentViewTypePosition);
checkBox.setChecked(readMarks[ariPosition * 2]);
checkBox.setFocusable(false);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
checkBox.setLayoutParams(layoutParams);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
ReadingPlanManager.updateReadingPlanProgress(readingPlan.info.id, currentViewTypePosition, ariPosition, isChecked);
loadReadingPlanProgress();
load();
notifyDataSetChanged();
}
});
layout.addView(checkBox);
}
} else {
res = null;
}
return res;
}
@Override
public Object getItem(final int position) {
return null;
}
@Override
public long getItemId(final int position) {
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public int getItemViewType(final int position) {
if (position < todayReadings.length / 2) {
return 0;
} else if (position == todayReadings.length / 2) {
return 1;
} else {
return 2;
}
}
}
}
|
package ee.aktors.beantimer;
import ee.aktors.beantimer.comm.RestClient;
import org.apache.log4j.Logger;
import java.lang.instrument.Instrumentation;
/**
* Add following to VM options to target Spring application
* -DpackageToMeasure=com.corp.project -javaagent: absolute path \beantimer\target\beantimer.jar
*/
public class Agent {
final static Logger LOG = Logger.getLogger(Agent.class);
public static final int PERIOD_MS = 20_000;
public static final String ENDPOINT = "http://localhost:9999/metric/all";
public static void premain(String agentArgs, Instrumentation inst) {
String packageToMeasure = System.getProperty("packageToMeasure");
String beantimerUser = System.getProperty("beantimerUser");
if (packageToMeasure == null || packageToMeasure.isEmpty()) {
LOG.error("Please specify package to instrument as a agent argument. For example: -DpackageToMeasure=com.corp.project -javaagent:.../beantimer.jar");
return;
}
if (beantimerUser == null || beantimerUser.isEmpty()) {
LOG.error("Please specify user to find your result in collector. For example: -DbeantimerUser=yourUsername -javaagent:.../beantimer.jar");
}
LOG.info("Measuring bean initialization in [ms] in package: " + packageToMeasure);
initializeAgent(inst, packageToMeasure);
initAndStartPeriodicDataSender(PERIOD_MS, ENDPOINT);
}
private static void initAndStartPeriodicDataSender(int periodMs, String endpoint) {
RestClient restClient = new RestClient(endpoint);
PeriodicDataSender periodicDataSender = new PeriodicDataSender(periodMs, restClient);
periodicDataSender.start();
LOG.info(String.format("PeriodicDataSender started with periodMs %d ms against following endpoint %s", periodMs, endpoint));
}
private static void initializeAgent(Instrumentation inst, String packageToMeasure) {
LOG.info("Agent initializing");
ClassFilter classFilter = new ClassFilter(packageToMeasure);
inst.addTransformer(new TimerBeanTransformer(classFilter));
LOG.info("Agent initialized");
}
}
|
package com.huettermann.all;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Message extends HttpServlet {
private static Logger logger = LoggerFactory.getLogger(Message.class);
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param = request.getParameter("param");
ServletContext context = getServletContext();
if (param == null || param.equals("")) {
context.log("No message received:",
new IllegalStateException("Missing parameter"));
} else {
context.log("Here the paramater: " + param);
}
PrintWriter out = null;
if (request.getRequestedSessionId().equals("4711")) {
try {
out = response.getWriter();
String encodedName = org.owasp.encoder.Encode.forHtml(param);
out.println("Hello: " + encodedName);
out.flush();
out.close();
} catch (IOException io) {
logger.info(io.getMessage());
}
}
}
}
|
package com.sometrik.framework;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ConfigurationInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class FrameWork extends Activity implements SurfaceHolder.Callback, NativeMessageHandler {
private MyGLSurfaceView mGLView;
private RelativeLayout mainView;
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private FrameWork frameWork;
private static final int RESULT_SETTINGS = 1;
private Settings settings;
private float screenHeight;
private float screenWidth;
public Handler mainHandler;
private Intent dialogIntent;
private Bitmap picture;
private AlertDialog.Builder builder;
private AlertDialog alert;
private float windowYcoords;
public static HashMap<Integer, NativeMessageHandler> views = new HashMap<Integer, NativeMessageHandler>();
public static int currentView = 0;
private MyGLRenderer renderer;
private int appId = 0;
public native void NativeOnTouch();
public native int GetInt(float x, float y);
public native String getText();
public native void okPressed(String text);
public native void buttonClicked(int id);
public native void textChangedEvent(int id, String text);
public native void settingsCreator(Settings settings, int id);
public native void menuPressed();
public native void touchEvent(int mode, int fingerIndex, long time, float x, float y);
public native void onInit(AssetManager assetManager, float xSize, float ySize, float displayScale, Boolean hasEs3);
public native void nativeSetSurface(Surface surface, int surfaceId);
public native void nativeOnResume(int appId);
public native void nativeOnPause(int appId);
public native void nativeOnStop(int appId);
public native void nativeOnRestart(int appId);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// You can disable status bar with this
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
LinearLayout linear = new LinearLayout(this);
linear.setId(-1);
// Init for screen settings
getDisplayMetrics();
// Set up classes
settings = new Settings(this);
// Get preferences (simple key-value database)
prefs = this.getSharedPreferences("com.example.Work", Context.MODE_PRIVATE);
editor = prefs.edit();
initNative();
}
@Override
public void handleCommand(NativeCommand command) {
System.out.println("id: " + command.getInternalId() + " MessageType: " + String.valueOf(command.getCommand()));
switch (command.getCommand()) {
case SHOW_VIEW:
NativeMessageHandler formViewToShow = views.get((command.getInternalId()));
if (formViewToShow != null) {
formViewToShow.showView();
} else {
System.out.println("Message not handled");
}
break;
case CREATE_APPLICATION:
appId = command.getInternalId();
break;
case SET_CAPTION:
setTitle(command.getTextValue());
break;
case CREATE_FORMVIEW:
System.out.println("creating formView " + command.getChildInternalId());
createFormView(command.getChildInternalId());
break;
case CREATE_OPENGL_VIEW:
createOpenGLView(command.getChildInternalId());
break;
case CREATE_NATIVE_OPENGL_VIEW:
createNativeOpenGLView(command.getChildInternalId());
break;
// Create notification
case POST_NOTIFICATION:
createNotification("", "");
break;
// Open Browser
case LAUNCH_BROWSER:
launchBrowser("");
break;
default:
NativeMessageHandler handlerView = views.get((command.getInternalId()));
if (handlerView != null) {
handlerView.handleCommand(command);
} else {
System.out.println("Message not handled");
}
break;
}
}
private void initNative(){
DisplayMetrics displayMetrics = getDisplayMetrics();
System.out.println("Display scale: " + displayMetrics.scaledDensity);
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
Boolean hasEs3;
if (configurationInfo.reqGlEsVersion >= 0x30000){
hasEs3 = true;
} else if (configurationInfo.reqGlEsVersion >= 0x20000) {
System.out.println("openGLES 3 isn't supported");
hasEs3 = false;
} else {
hasEs3 = false;
System.out.println("openGLES 2 isn't supported");
}
float xSize = displayMetrics.widthPixels / displayMetrics.scaledDensity;
float ySize = displayMetrics.heightPixels / displayMetrics.scaledDensity;
onInit(getAssets(), xSize, ySize, displayMetrics.scaledDensity, hasEs3);
}
// Get screen settings
public DisplayMetrics getDisplayMetrics() {
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
screenHeight = displaymetrics.heightPixels;
screenWidth = displaymetrics.widthPixels;
return displaymetrics;
}
public static void addToViewList(int id, NativeMessageHandler view){
System.out.println(view.getElementId() + " added to view list");
views.put(id, view);
}
public MyGLSurfaceView getSurfaceView() {
return mGLView;
}
public void launchBrowser(String url) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
private void createFormView(int id){
FWLayout layout = new FWLayout(this);
layout.setId(id);
views.put(id, layout);
}
private void createOpenGLView(int id){
MyGLRenderer renderer = new MyGLRenderer(this, screenWidth, screenHeight);
MyGLSurfaceView mGLView = new MyGLSurfaceView(this, renderer, id);
mGLView.setOnTouchListener(new MyOnTouchListener(this));
mGLView.setWillNotDraw(false);
mGLView.getHolder().addCallback(this);
views.put(id, mGLView);
if (currentView == 0) {
setContentView(mGLView);
currentView = id;
}
}
private void createNativeOpenGLView(int id){
NativeSurface surfaceView = new NativeSurface(this);
surfaceView.setId(id);
surfaceView.setOnTouchListener(new MyOnTouchListener(this));
surfaceView.getHolder().addCallback(this);
views.put(id, surfaceView);
if (currentView == 0) {
setContentView(surfaceView);
currentView = id;
}
}
// Lis kuvan antaminen // Aika // ni
public void createNotification(String title, String text) {
System.out.println("Creating notification");
Intent intent = new Intent(this, FrameWork.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle(title);
builder.setContentText(text);
// builder.setSmallIcon(R.drawable.picture);
builder.setContentIntent(pIntent);
builder.setAutoCancel(true);
Notification notif = builder.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notif);
}
// Create dialog with user text input
private void createInputDialog(String title, String message) {
System.out.println("Creating input dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Negative button listener
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String inputText = String.valueOf(input.getText());
// editor.putString("username", "teksti" );
okPressed(inputText);
dialog.cancel();
}
});
// Create and show the alert
alert = builder.create();
alert.show();
}
// create Message dialog
private void showMessageDialog(String title, String message) {
System.out.println("creating message dialog");
AlertDialog.Builder builder;
builder = new AlertDialog.Builder(this);
// Building an alert
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
// Negative button listener
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Positive button listener
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Create and show the alert
alert = builder.create();
alert.show();
System.out.println("message dialog created");
}
//Code to show user preferences on screen. Might be useful later
private void showUserSettings() {
// setContentView(R.layout.activity_main);
System.out.println("showSettings called");
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
StringBuilder builder = new StringBuilder();
builder.append("\n Username: " + sharedPrefs.getString("prefUsername", "NULL"));
builder.append("\n Send report:" + sharedPrefs.getBoolean("prefSendReport", false));
builder.append("\n Sync Frequency: " + sharedPrefs.getString("prefSyncFrequency", "NULL"));
// TextView settingsTextView = (TextView) findViewById(R.id.textUserSettings);
// settingsTextView.setText(builder.toString());
}
private static PointF touchScreenStartPtArr[] = new PointF[10];
//Screen touchevent listener. Will send information to MyGLSurfaceView messagehandler
private class MyOnTouchListener implements OnTouchListener {
FrameWork frameWork;
public MyOnTouchListener(FrameWork frameWork) {
this.frameWork = frameWork;
}
public void onClick(View v) {
System.out.println("Click happened");
}
@Override
public boolean onTouch(View v, MotionEvent event) {
// On touchesBegin(), touchesEnded(), touchesMoved(), Different
// fingers (pointerId)
Message msg;
int[] intArray;
int action = event.getAction() & MotionEvent.ACTION_MASK;
int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
int fingerId = event.getPointerId(pointerIndex);
switch (action) {
//Touch event of screen touch-down for the first finger
case MotionEvent.ACTION_DOWN:
// System.out.println("Liike alkoi: " + event.getX() + " " + event.getY() + " - id: " + event.getActionIndex() + " time: " + System.currentTimeMillis());
touchEvent(1, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
break;
//Touch event of screen touch-down after the first touch
case MotionEvent.ACTION_POINTER_DOWN:
// System.out.println("Liike alkoi: " + event.getX() + " " + event.getY() + " - id: " + event.getActionIndex());
touchEvent(1, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
break;
//Touch event of finger moving
case MotionEvent.ACTION_MOVE:
int pointerCount = event.getPointerCount();
for (int i = 0; i < pointerCount; i++) {
pointerIndex = i;
int pointerId = event.getPointerId(pointerIndex);
if (pointerId == 0) {
// System.out.println("fingerOne move: " + event.getX(pointerIndex) + event.getY(pointerIndex));
touchEvent(2, 0, System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
}
if (pointerId == 1) {
// System.out.println("fingerTwo move: " + event.getX(pointerIndex) + event.getY(pointerIndex));
touchEvent(2, 1, System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
}
if (pointerId == 2) {
// System.out.println("fingerThree move: " + event.getX(pointerIndex) + event.getY(pointerIndex));
touchEvent(2, 2, System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
}
if (pointerId == 3) {
// System.out.println("fingerFour move: " + event.getX(pointerIndex) + event.getY(pointerIndex));
touchEvent(2, 3, System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
}
if (pointerId == 4) {
// System.out.println("fingerFive move: " + event.getX(pointerIndex) + event.getY(pointerIndex));
touchEvent(2, 4, System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
}
}
// System.out.println("Liikett: " + event.getX() + " " +
// event.getY() + " - id: " + event.getActionIndex());
break;
//touch event of first finger being removed from the screen
case MotionEvent.ACTION_UP:
//touch event of fingers other than the first leaving the screen
case MotionEvent.ACTION_POINTER_UP:
touchEvent(3, event.getActionIndex(), System.currentTimeMillis(), (int) event.getX(), (int) (screenHeight - event.getRawY() - windowYcoords));
break;
}
return true;
}
}
//Build in Methods of Menu Creating. Propably removable
@Override
public boolean onCreateOptionsMenu(Menu menu) {
System.out.println("onCreateOptionsMenu");
// getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch (keycode) {
case KeyEvent.KEYCODE_MENU:
System.out.println("KeyEvent");
mGLView.sHandler.sendEmptyMessage(2);
return true;
}
return super.onKeyDown(keycode, e);
}
private void createOptionsDialog(final int[] idArray, String[] names) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Options Menu");
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
System.out.println("item selected: " + item);
System.out.println("item id: " + idArray[item]);
optionSelected(idArray[item]);
}
});
AlertDialog alert = builder.create();
alert.show();
}
//Called after option was selected from ActionSheet. Currently creates settings view
private void optionSelected(int id) {
settings = new Settings(this);
// Settings tytyy tehd uusiksi tss, jotta lista ei pysy samana
settingsCreator(settings, id);
getFragmentManager().beginTransaction().replace(android.R.id.content, settings).addToBackStack("main").commit();
}
//Listener for built in menu options. Propably removable
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// case R.id.menu_settings:
// getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();
// break;
// case 1:
// startActivity(new Intent(this, Settings.class));
// break;
}
return true;
}
public float getScreenWidth(){
return screenWidth;
}
// returns database path
public String getDBPath(String dbName) {
System.out.println("getting DBPath _ db: " + dbName + " Path: " + String.valueOf(getDatabasePath(dbName)));
return String.valueOf(getDatabasePath(dbName));
}
public static void sendMessage(FrameWork frameWork, NativeCommand command) {
Message msg = Message.obtain(null, 1, command);
frameWork.mainHandler.sendMessage(msg);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
// showUserSettings();
break;
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
System.out.println("Orientation conf portrait");
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
System.out.println("Orientation conf landscape");
}
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
// savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
// savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
// mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
// mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
}
@Override
public void onResume(){
super.onResume();
nativeOnResume(appId);
}
@Override
public void onPause(){
super.onPause();
nativeOnPause(appId);
}
@Override
public void onStop(){
super.onStop();
nativeOnStop(appId);
}
@Override
public void onRestart(){
super.onRestart();
nativeOnRestart(appId);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int arg1, int arg2, int arg3) {
nativeSetSurface(holder.getSurface(), currentView);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// Empty
}
//Load JNI. Framework references to make file.
static {
System.loadLibrary("framework");
}
@Override
public void showView() {
}
@Override
public int getElementId() {
return 0;
}
}
|
package com.ezhuk.wear;
import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preview.support.v4.app.NotificationManagerCompat;
import android.preview.support.wearable.notifications.RemoteInput;
import android.preview.support.wearable.notifications.WearableNotifications;
import android.support.v4.app.NotificationCompat;
public class MainActivity extends Activity {
private static final String NOTIFICATION_GROUP = "notification_group";
private static final String ACTION_TEST = "com.ezhuk.wear.ACTION";
private static final String ACTION_EXTRA = "action";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onResume() {
super.onResume();
showTestNotification();
showTestNotificationWithPages();
showTestNotificationWithAction();
showTestNotificationWithInputForPrimaryAction();
showTestNotificationWithInputForSecondaryAction();
showGroupNotifications();
}
@Override
protected void onPause() {
super.onPause();
}
private void showTestNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.content_title))
.setContentText(getString(R.string.content_text));
NotificationManagerCompat.from(this).notify(0,
new WearableNotifications.Builder(builder).build());
}
private void showTestNotificationWithPages() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.page1_title))
.setContentText(getString(R.string.page1_text));
NotificationCompat.BigTextStyle style =
new NotificationCompat.BigTextStyle();
style.setBigContentTitle(getString(R.string.page2_title))
.bigText(getString(R.string.page2_text));
Notification second = new NotificationCompat.Builder(this)
.setStyle(style)
.build();
NotificationManagerCompat.from(this).notify(1,
new WearableNotifications.Builder(builder)
.addPage(second)
.build());
}
private void showTestNotificationWithAction() {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("");
intent.setData(uri);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.action_title))
.setContentText(getString(R.string.action_text))
.addAction(R.drawable.ic_launcher,
getString(R.string.action_button),
pendingIntent);
NotificationManagerCompat.from(this).notify(2,
new WearableNotifications.Builder(builder).build());
}
private void showTestNotificationWithInputForPrimaryAction() {
Intent intent = new Intent(ACTION_TEST);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.action_title))
.setContentText(getString(R.string.action_text))
.setContentIntent(pendingIntent);
String[] choices =
getResources().getStringArray(R.array.input_choices);
RemoteInput remoteInput = new RemoteInput.Builder(ACTION_EXTRA)
.setLabel(getString(R.string.action_label))
.setChoices(choices)
.build();
NotificationManagerCompat.from(this).notify(3,
new WearableNotifications.Builder(builder)
.addRemoteInputForContentIntent(remoteInput)
.build()
);
}
private void showTestNotificationWithInputForSecondaryAction() {
Intent intent = new Intent(ACTION_TEST);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, intent, 0);
RemoteInput remoteInput = new RemoteInput.Builder(ACTION_EXTRA)
.setLabel(getString(R.string.action_label))
.build();
WearableNotifications.Action action =
new WearableNotifications.Action.Builder(
R.drawable.ic_launcher,
"Action",
pendingIntent)
.addRemoteInput(remoteInput)
.build();
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setContentTitle(getString(R.string.action_title));
NotificationManagerCompat.from(this).notify(4,
new WearableNotifications.Builder(builder)
.addAction(action)
.build()
);
}
private void showGroupNotifications() {
Notification first = new WearableNotifications.Builder(
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.page1_title))
.setContentText(getString(R.string.page1_text)))
.setGroup(NOTIFICATION_GROUP)
.build();
Notification second = new WearableNotifications.Builder(
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.page2_title))
.setContentText(getString(R.string.page2_text)))
.setGroup(NOTIFICATION_GROUP)
.build();
Notification summary = new WearableNotifications.Builder(
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle(getString(R.string.summary_title))
.setContentText(getString(R.string.summary_text)))
.setGroup(NOTIFICATION_GROUP,
WearableNotifications.GROUP_ORDER_SUMMARY)
.build();
NotificationManagerCompat.from(this).notify(5, first);
NotificationManagerCompat.from(this).notify(6, second);
NotificationManagerCompat.from(this).notify(7, summary);
}
}
|
package com.easychat.test.webserver;
import com.easychat.Server;
import com.easychat.model.entity.User;
import com.easychat.model.error.ErrorType;
import com.easychat.repository.UserRepository;
import com.easychat.utils.CommonUtils;
import com.easychat.utils.JsonUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.*;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Server.class)
@WebIntegrationTest
public class UserControllerTest {
private static final String URL = "http://localhost:8080/v1/users";
private static final String URL_testAuthenticateApi = "http://localhost:8080/v1/users/authorization";
private RestTemplate restTemplate = new TestRestTemplate();
@Autowired
private UserRepository userRepository;
@Test
public void testAddUserApi() {
String name = "testuser";
String password = "123456";
// Request Body HttpHeaders
Map<String, String> requestBody = new HashMap<>();
requestBody.put("name", name);
requestBody.put("password", password);
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
//http
HttpEntity<String> httpEntity = new HttpEntity<>(JsonUtils.encode(requestBody),requestHeaders);
//API
// Map<String, String> apiResponse = restTemplate.postForObject(URL, httpEntity, Map.class);
ResponseEntity<String> response = restTemplate.postForEntity(URL, httpEntity, String.class);
Map<String, String> responseBody = JsonUtils.decode(response.getBody(), Map.class);
assertNotNull(response);
assertEquals(response.getStatusCode(), HttpStatus.OK);
assertEquals(name, responseBody.get("name"));
assertEquals(password, responseBody.get("password"));
User user = userRepository.findByName(name);
assertNotNull(user);
response = restTemplate.postForEntity(URL, httpEntity, String.class);
assertNotNull(response);
assertEquals(response.getStatusCode(), HttpStatus.BAD_REQUEST);
responseBody = JsonUtils.decode(response.getBody(), Map.class);
assertEquals(ErrorType.DUPLICATE_UNIQUE_PROPERTY_EXISTS, responseBody.get("error"));
userRepository.delete(user);
}
@Test
public void testAuthenticateApi(){
String name = "testuser";
String password = "123456";
User user = new User();
user.setName(name);
user.setPassword(CommonUtils.md5(password));
userRepository.save(user);
// Request Body HttpHeaders
Map<String, String> requestBody = new HashMap<>();
requestBody.put("name", name);
requestBody.put("password",CommonUtils.md5(password));
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
//http
HttpEntity<String> httpEntity = new HttpEntity<>(JsonUtils.encode(requestBody),requestHeaders);
//API
ResponseEntity<String> response = restTemplate.postForEntity(URL_testAuthenticateApi, httpEntity, String.class);
Map<String, String> responseBody = JsonUtils.decode(response.getBody(), Map.class);
assertNotNull(response);
assertEquals(response.getStatusCode(), HttpStatus.OK);
userRepository.delete(user);
}
}
|
package verification.platu.project;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import lpn.parser.LhpnFile;
import lpn.parser.Translator;
import org.antlr.runtime.ANTLRFileStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
import verification.platu.logicAnalysis.Analysis;
import verification.platu.logicAnalysis.CompositionalAnalysis;
import verification.platu.lpn.LPN;
import verification.platu.lpn.LPNTranRelation;
import verification.platu.lpn.io.Instance;
import verification.platu.lpn.io.PlatuInstLexer;
import verification.platu.lpn.io.PlatuInstParser;
import verification.platu.main.Options;
import verification.platu.markovianAnalysis.MarkovianAnalysis;
import verification.platu.markovianAnalysis.PerfromTransientMarkovAnalysisThread;
import verification.platu.markovianAnalysis.ProbGlobalStateSet;
import verification.platu.markovianAnalysis.ProbLocalStateGraph;
import verification.platu.stategraph.State;
import verification.platu.stategraph.StateGraph;
import verification.timed_state_exploration.zoneProject.ContinuousUtilities;
import verification.timed_state_exploration.zoneProject.Zone;
public class Project {
protected String label;
/* 1. Each design unit has an unique label index.
* 2. The indices of all design units are sequential starting from 0.
* */
protected List<StateGraph> designUnitSet;
/* The list for timing analysis */
// protected List<StateGraph_timed> designUnitTimedSet;
protected LPNTranRelation lpnTranRelation = null;
protected CompositionalAnalysis analysis = null;
public Project() {
this.label = "";
this.designUnitSet = new ArrayList<StateGraph>(1);
lpnTranRelation = new LPNTranRelation(this.designUnitSet);
}
public Project(LhpnFile lpn) {
this.label = "";
this.designUnitSet = new ArrayList<StateGraph>(1);
StateGraph stateGraph = new StateGraph(lpn);
designUnitSet.add(stateGraph);
}
/**
* If the OptionsFlag is false, then this constructor is identical to
* Poject(LhpnFile lpn). If the OptionsFlag is true, this constructor uses
* StateGraph_timed objects.
*
* @author Andrew N. Fisher
*
* @param lpn
* The lpn under consideration.
* @param OptionsFlag
* True for timing analysis and false otherwise. The option should match
* Options.getTimingAnalysisFlag().
*/
// public Project(LhpnFile lpn, boolean OptionsFlag)
// if(Options.getTimingAnalysisFlag())
// this.label = "";
// this.designUnitSet = new ArrayList<StateGraph>(0);
// this.designUnitTimedSet = new ArrayList<StateGraph_timed>(1);
// StateGraph_timed stategraph = new StateGraph_timed(lpn);
// designUnitTimedSet.add(stategraph);
// else
// this.label = "";
// this.designUnitSet = new ArrayList<StateGraph>(1);
// StateGraph stateGraph = new StateGraph(lpn);
// designUnitSet.add(stateGraph);
public Project(ArrayList<LhpnFile> lpns) {
this.label = "";
this.designUnitSet = new ArrayList<StateGraph>(lpns.size());
if (!Options.getMarkovianModelFlag())
for (int i=0; i<lpns.size(); i++) {
LhpnFile lpn = lpns.get(i);
StateGraph stateGraph = new StateGraph(lpn);
lpn.addStateGraph(stateGraph);
designUnitSet.add(stateGraph);
}
else
for (int i=0; i<lpns.size(); i++) {
LhpnFile lpn = lpns.get(i);
ProbLocalStateGraph stateGraph = new ProbLocalStateGraph(lpn);
lpn.addStateGraph(stateGraph);
designUnitSet.add(stateGraph);
}
lpnTranRelation = new LPNTranRelation(this.designUnitSet);
}
/**
* Find the SG for the entire project where each project state is a tuple of
* local states
*
*/
public void search() {
// TODO: temporarily set the input validation only to non-stochastic LPN models.
if (!Options.getMarkovianModelFlag())
validateInputs();
// if(Options.getSearchType().equals("compositional")){
// this.analysis = new CompositionalAnalysis();
// if(Options.getParallelFlag()){
// this.analysis.parallelCompositionalFindSG(this.designUnitSet);
// else{
// this.analysis.findReducedSG(this.designUnitSet);
// return;
long startReachability = System.currentTimeMillis();
int lpnCnt = designUnitSet.size();
/* Prepare search by placing LPNs in an array in the order of their indices.*/
StateGraph[] sgArray = new StateGraph[lpnCnt];
int idx = 0;
for (StateGraph du : designUnitSet) {
LhpnFile lpn = du.getLpn();
lpn.setLpnIndex(idx++);
sgArray[lpn.getLpnIndex()] = du;
}
// If timing, then create the sgArray with StateGraph_timed objects.
// if(Options.getTimingAnalysisFlag())
// for(StateGraph_timed du : this.designUnitTimedSet)
// LhpnFile lpn = du.getLpn();
// lpn.setIndex(idx++);
// sgArray[lpn.getIndex()] = du;
// Initialize the project state
HashMap<String, Integer> varValMap = new HashMap<String, Integer>();
State[] initStateArray = new State[lpnCnt];
for (int index = 0; index < lpnCnt; index++) {
LhpnFile curLpn = sgArray[index].getLpn();
StateGraph curSg = sgArray[index];
initStateArray[index] = curSg.genInitialState();
int[] curVariableVector = initStateArray[index].getVariableVector();
varValMap = curLpn.getAllVarsWithValuesAsInt(curVariableVector);
}
// Adjust the value of the input variables in LPN in the initial state.
// Add the initial states into their respective state graphs.
for (int index = 0; index < lpnCnt; index++) {
StateGraph curSg = sgArray[index];
// If this is a timing analysis, the boolean inequality variables
// must be updated.
if(Options.getTimingAnalysisFlag()){
// First create a zone with the continuous variables.
State[] ls = new State[1];
ls[0] = initStateArray[index];
Zone z = new Zone(ls, true);
ContinuousUtilities.updateInitialInequalities(z, ls[0]);
initStateArray[index] = curSg.genInitialState();
}
// TODO: Is it necessary to update initStateArray for un-timed case?
initStateArray[index].update(curSg, varValMap, curSg.getLpn().getVarIndexMap());
initStateArray[index] = curSg.addState(initStateArray[index]);
}
// Initialize the zones for the initStateArray, if timining is enabled.
// if(Options.getTimingAnalysisFlag())
// for(int index =0; index < lpnCnt; index++)
// if(sgArray[index] instanceof StateGraph_timed)
// if (Options.getTimingAnalysisFlag()) {
// new TimingAnalysis(sgArray);
// return;
// else if(!Options.getTimingAnalysisFlag()) {
// Analysis tmp = new Analysis(sgArray, initStateArray, lpnTranRelation, Options.getSearchType());
// // Analysis tmp = new Analysis(lpnList, curStateArray,
// // lpnTranRelation, "dfs_por");
// //Analysis tmp = new Analysis(modArray, initStateArray, lpnTranRelation, "dfs");
// //Analysis tmp = new Analysis(modArray, initStateArray, lpnTranRelation, "dfs_noDisabling");
// else {
// return;
/* Entry point for the timed analysis. */
// if(Options.getTimingAnalysisFlag())
// Analysis_Timed dfsTimedStateExploration = new Analysis_Timed(sgArray);
// dfsTimedStateExploration.search_dfs_timed(sgArray, initStateArray);
// return new StateGraph[0];
Analysis dfsStateExploration = new Analysis(sgArray);
if (!Options.getMarkovianModelFlag()) {
dfsStateExploration.search_dfs(sgArray, initStateArray);
long elapsedTimeMillis = System.currentTimeMillis() - startReachability;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println("---> total runtime for reachability analysis: " + elapsedTimeSec + " sec\n");
if (Options.getOutputLogFlag())
outputRuntimeLog(false, elapsedTimeSec);
}
else {
//Options.setBuildGlobalStateGraph();
ProbGlobalStateSet globalStateSet = (ProbGlobalStateSet) dfsStateExploration.search_dfs(sgArray, initStateArray);
long elapsedTimeMillisReachability = System.currentTimeMillis() - startReachability;
float elapsedTimeSecReachability = elapsedTimeMillisReachability/1000F;
System.out.println("---> total runtime for reachability analysis: " + elapsedTimeSecReachability + " sec");
if (Options.getOutputLogFlag())
outputRuntimeLog(false, elapsedTimeSecReachability);
// long startSteadyState = System.currentTimeMillis();
// MarkovianAnalysis markovianAnalysis = new MarkovianAnalysis(globalStateSet);
// double tolerance = 0.0000000001;
// PrjState initialSt = ((ProbGlobalStateSet) globalStateSet).getInitialState();
// markovianAnalysis.performSteadyStateMarkovianAnalysis(tolerance, null, initialSt, null);
// dfsStateExploration.drawGlobalStateGraph(sgArray, initialSt, globalStateSet, true);
// long elapsedTimeMillisSteadyState = System.currentTimeMillis() - startSteadyState;
// float elapsedTimeSecSteadyState = elapsedTimeMillisSteadyState/1000F;
System.out.println("
long startTransientAnalysis = System.currentTimeMillis();
MarkovianAnalysis markovianAnalysis = new MarkovianAnalysis(globalStateSet);
// double timeLimit = 5000.0;
// double printInterval = 100.0;
// double timeStep = 100.0;
// double absError = 1.0e-9;
// String prop = "Pr=?{PF[<=5000]((LacI>40)&(TetR<20))}";
// String prop = "Pr=?{PF[<=5000]((TetR>40)&(LacI<20))}";
double timeLimit = 2100.0;
double printInterval = 100.0;
double timeStep = 100.0;
double absError = 1.0e-9;
String prop = "Pr=?{PF[<=2100]((E>40)&(C<20))}";
// //String prop = "Pr=?{PF[<=2100]((S2>80)&(S3<20))}";
// //String prop = "Pr=?{PF[<=2100]((Z>80)&(Y<40))}";
//// JPanel progBar = new JPanel();
JProgressBar progress = new JProgressBar(0, 100);
// progress.setStringPainted(true);
// progress.setValue(0);
// progress.setIndeterminate(true);
//// progBar.add(progress);
PerfromTransientMarkovAnalysisThread performMarkovAnalysisThread = new PerfromTransientMarkovAnalysisThread(
markovianAnalysis, progress);
if (prop != null) {
String[] condition = Translator.getProbpropParts(Translator.getProbpropExpression(prop));
boolean globallyTrue = false;
if (prop.contains("PF")) {
condition[0] = "true";
}
else if (prop.contains("PG")) {
condition[0] = "true";
globallyTrue = true;
}
performMarkovAnalysisThread.start(timeLimit, timeStep, printInterval, absError, condition, globallyTrue);
}
else {
performMarkovAnalysisThread.start(timeLimit, timeStep, printInterval, absError, null, false);
}
try {
performMarkovAnalysisThread.join();
} catch (InterruptedException e) {
//JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
//dfsStateExploration.drawGlobalStateGraph(sgArray, globalStateSet.getInitialState(), globalStateSet, true);
//markovianAnalysis.printStateSetStatus(globalStateSet, "end of transient analysis");
long elapsedTimeMillisTransient = System.currentTimeMillis() - startTransientAnalysis;
float elapsedTimeSecTransient = elapsedTimeMillisTransient/1000F;
System.out.println("---> total runtime for transient analysis: " + elapsedTimeSecTransient + " sec");
}
if (Options.getOutputSgFlag())
if (sgArray != null)
for (int i=0; i<sgArray.length; i++)
sgArray[i].drawLocalStateGraph();
}
public Set<LPN> readLpn(final String src_file) {
Set<LPN> lpnSet = null;
try {
if (!src_file.endsWith(".lpn")) {
System.err.println("Invalid file extention");
System.exit(1);
}
// ANTLRFileStream input = new ANTLRFileStream(src_file);
// PlatuGrammarLexer lexer = new PlatuGrammarLexer(input);
// TokenStream tokenStream = new CommonTokenStream(lexer);
// PlatuGrammarParser parser = new PlatuGrammarParser(tokenStream);
// lpnSet = parser.lpn(this);
} catch (Exception ex) {
Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null,
ex);
}
return lpnSet;
}
/**
* Find the SG for the entire project where each project state is a tuple of
* local states. Use partial order reduction with trace-back during the dfs search.
* @param globalSGpath
* @return
*
*/
public void searchWithPOR() {
// TODO: temporarily set the input validation only to non-stochastic LPN models.
if (!Options.getMarkovianModelFlag())
validateInputs();
// if(Options.getSearchType().equals("compositional")){
// this.analysis = new CompositionalAnalysis();
// if(Options.getParallelFlag()){
// this.analysis.parallelCompositionalFindSG(this.designUnitSet);
// else{
// this.analysis.findReducedSG(this.designUnitSet);
// return;
long startReachability = System.currentTimeMillis();
int lpnCnt = designUnitSet.size();
/* Prepare search by placing LPNs in an array in the order of their indices.*/
StateGraph[] sgArray = new StateGraph[lpnCnt];
int idx = 0;
for (StateGraph sg : designUnitSet) {
LhpnFile lpn = sg.getLpn();
lpn.setLpnIndex(idx++);
sgArray[lpn.getLpnIndex()] = sg;
}
// Initialize the project state
HashMap<String, Integer> varValMap = new HashMap<String, Integer>();
State[] initStateArray = new State[lpnCnt];
for (int index = 0; index < lpnCnt; index++) {
LhpnFile curLpn = sgArray[index].getLpn();
StateGraph curSg = sgArray[index];
initStateArray[index] = curSg.genInitialState(); //curLpn.getInitState();
int[] curStateVector = initStateArray[index].getVariableVector();
varValMap = curLpn.getAllVarsWithValuesAsInt(curStateVector);
// DualHashMap<String, Integer> VarIndexMap = curLpn.getVarIndexMap();
// HashMap<String, String> outVars = curLpn.getAllOutputs();
// for(String var : outVars.keySet()) {
// varValMap.put(var, curStateVector[VarIndexMap.getValue(var)]);
}
// Adjust the value of the input variables in LPN in the initial state.
// Add the initial states into their respective LPN.
for (int index = 0; index < lpnCnt; index++) {
StateGraph curSg = sgArray[index];
initStateArray[index].update(curSg, varValMap, curSg.getLpn().getVarIndexMap());
initStateArray[index] = curSg.addState(initStateArray[index]);
}
Analysis dfsPOR = new Analysis(sgArray);
if (!Options.getMarkovianModelFlag()) {
if (Options.getPOR().toLowerCase().equals("tb"))
dfsPOR.searchPOR_taceback(sgArray, initStateArray);
else if (Options.getPOR().toLowerCase().equals("behavioral")) {
CompositionalAnalysis compAnalysis = new CompositionalAnalysis();
compAnalysis.compositionalFindSG(sgArray);
dfsPOR.searchPOR_behavioral(sgArray, initStateArray, lpnTranRelation, "state");
}
else {
System.out.println("Need to provide a POR method.");
}
long elapsedTimeMillis = System.currentTimeMillis() - startReachability;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println("---> total runtime for reachability analysis: " + elapsedTimeSec + " sec\n");
if (Options.getOutputLogFlag())
outputRuntimeLog(true, elapsedTimeSec);
if (Options.getOutputSgFlag()) {
if (sgArray != null)
for (int i=0; i<sgArray.length; i++) {
sgArray[i].drawLocalStateGraph();
}
}
}
else { // Markovian analysis
//Options.setBuildGlobalStateGraph();
ProbGlobalStateSet globalStateSet = null;
if (Options.getPOR().toLowerCase().equals("tb"))
globalStateSet = (ProbGlobalStateSet) dfsPOR.searchPOR_taceback(sgArray, initStateArray);
else if (Options.getPOR().toLowerCase().equals("behavioral")) {
CompositionalAnalysis compAnalysis = new CompositionalAnalysis();
compAnalysis.compositionalFindSG(sgArray);
dfsPOR.searchPOR_behavioral(sgArray, initStateArray, lpnTranRelation, "state");
}
else {
System.out.println("Need to provide a POR method.");
}
long elapsedTimeMillis = System.currentTimeMillis() - startReachability;
float elapsedTimeSec = elapsedTimeMillis/1000F;
System.out.println("---> total runtime for reachability analysis: " + elapsedTimeSec + " sec\n");
if (Options.getOutputLogFlag())
outputRuntimeLog(true, elapsedTimeSec);
if (Options.getOutputSgFlag()) {
if (sgArray != null)
for (int i=0; i<sgArray.length; i++) {
sgArray[i].drawLocalStateGraph();
}
}
// long startSteadyState = System.currentTimeMillis();
// MarkovianAnalysis markovianAnalysis = new MarkovianAnalysis(globalStateSet);
// double tolerance = 0.0000000001;
// PrjState initialSt = globalStateSet.getInitState();
// markovianAnalysis.performSteadyStateMarkovianAnalysis(tolerance, null, initialSt, null);
// dfsStateExploration.drawGlobalStateGraph(sgArray, globalStateSet.getInitState(), globalStateSet, true);
// long elapsedTimeMillisSteadyState = System.currentTimeMillis() - startSteadyState;
// float elapsedTimeSecSteadyState = elapsedTimeMillisSteadyState/1000F;
System.out.println("
long startTransientAnalysis = System.currentTimeMillis();
MarkovianAnalysis markovianAnalysis = new MarkovianAnalysis(globalStateSet);
// double timeLimit = 2100.0;
// double printInterval = 100.0;
// double timeStep = 100.0;
// double absError = 1.0e-9;
//String prop = "Pr=?{PF[<=5000]((LacI>40)&(TetR<20))}";
//String prop = "Pr=?{PF[<=5000]((TetR>40)&(LacI<20))}";
double timeLimit = 2100.0;
double printInterval = 100.0;
double timeStep = 100.0;
double absError = 1.0e-9;
String prop = "Pr=?{PF[<=2100]((E>40)&(C<20))}";
//// JPanel progBar = new JPanel();
JProgressBar progress = new JProgressBar(0, 100);
// progress.setStringPainted(true);
// progress.setValue(0);
// progress.setIndeterminate(true);
//// progBar.add(progress);
PerfromTransientMarkovAnalysisThread performMarkovAnalysisThread = new PerfromTransientMarkovAnalysisThread(
markovianAnalysis, progress);
if (prop != null) {
String[] condition = Translator.getProbpropParts(Translator.getProbpropExpression(prop));
boolean globallyTrue = false;
if (prop.contains("PF")) {
condition[0] = "true";
}
else if (prop.contains("PG")) {
condition[0] = "true";
globallyTrue = true;
}
performMarkovAnalysisThread.start(timeLimit, timeStep, printInterval, absError, condition, globallyTrue);
}
else {
performMarkovAnalysisThread.start(timeLimit, timeStep, printInterval, absError, null, false);
}
try {
performMarkovAnalysisThread.join();
} catch (InterruptedException e) {
//JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
//dfsStateExploration.drawGlobalStateGraph(sgArray, globalStateSet.getInitialState(), globalStateSet, true);
long elapsedTimeMillisTransient = System.currentTimeMillis() - startTransientAnalysis;
float elapsedTimeSecTransient = elapsedTimeMillisTransient/1000F;
System.out.println("---> total runtime for transient analysis: " + elapsedTimeSecTransient + " sec");
}
}
private void outputRuntimeLog(boolean isPOR, float runtime) {
try {
String fileName = null;
if (isPOR)
fileName = Options.getPrjSgPath() + Options.getLogName() + "_"
+ Options.getPOR() + "_" + Options.getCycleClosingMthd() + "_"
+ Options.getCycleClosingAmpleMethd() + "_runtime.log";
else
fileName = Options.getPrjSgPath() + Options.getLogName() + "_full_runtime.log";
BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
out.write("runtime(sec)\n");
out.write(runtime + "\n");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
public void readLpn(List<String> fileList) {
for(String srcFile : fileList){
if (!srcFile.endsWith(".lpn")) {
System.err.println("Invalid file extention");
System.exit(1);
}
ANTLRFileStream input = null;
try {
input = new ANTLRFileStream(srcFile);
}
catch (IOException e) {
System.err.println("error: error reading " + srcFile);
System.exit(1);
}
PlatuInstLexer lexer = new PlatuInstLexer(input);
TokenStream tokenStream = new CommonTokenStream(lexer);
PlatuInstParser parser = new PlatuInstParser(tokenStream);
try {
parser.parseLpnFile(this);
}
catch (RecognitionException e) {
System.err.println("error: error parsing " + srcFile);
System.exit(1);
}
}
PlatuInstParser.includeSet.removeAll(fileList);
for(String srcFile : PlatuInstParser.includeSet){
if (!srcFile.endsWith(".lpn")) {
System.err.println("Invalid file extention");
System.exit(1);
}
ANTLRFileStream input = null;
try {
input = new ANTLRFileStream(srcFile);
}
catch (IOException e) {
System.err.println("error: error reading " + srcFile);
System.exit(1);
}
PlatuInstLexer lexer = new PlatuInstLexer(input);
TokenStream tokenStream = new CommonTokenStream(lexer);
PlatuInstParser parser = new PlatuInstParser(tokenStream);
try {
parser.parseLpnFile(this);
}
catch (RecognitionException e) {
System.err.println("error: error parsing " + srcFile);
System.exit(1);
}
}
verification.platu.lpn.LPN.nextID = 1;
HashMap<String, LPN> instanceMap = new HashMap<String, LPN>();
for(Instance inst : PlatuInstParser.InstanceList){
LPN lpn = PlatuInstParser.LpnMap.get(inst.getLpnLabel());
if(lpn == null){
System.err.println("error: class " + inst.getLpnLabel() + " does not exist");
System.exit(1);
}
LPN instLpn = lpn.instantiate(inst.getName());
instanceMap.put(instLpn.getLabel(), instLpn);
this.designUnitSet.add(instLpn.getStateGraph());
}
// TODO: (irrelevant) Is this really needed???
/*
for(StateGraph sg : this.designUnitSet){
sg.getLpn().setGlobals(this.designUnitSet);
}
*/
for(Instance inst : PlatuInstParser.InstanceList){
LPN dstLpn = instanceMap.get(inst.getName());
if(dstLpn == null){
System.err.println("error: instance " + inst.getName() + " does not exist");
System.exit(1);
}
List<String> argumentList = dstLpn.getArgumentList();
List<String> varList = inst.getVariableList();
List<String> modList = inst.getModuleList();
if(argumentList.size() != varList.size()){
System.err.println("error: incompatible number of arguments for instance " + inst.getName());
System.exit(1);
}
for(int i = 0; i < argumentList.size(); i++){
LPN srcLpn = instanceMap.get(modList.get(i));
if(srcLpn == null){
System.err.println("error: instance " + modList.get(i) + " does not exist");
System.exit(1);
}
String outputVar = varList.get(i);
String inputVar = argumentList.get(i);
srcLpn.connect(outputVar, dstLpn, inputVar);
}
}
}
/**
* @return the designUnitSet
*/
public List<StateGraph> getDesignUnitSet() {
return designUnitSet;
}
/**
* Validates each lpn's input variables are driven by another lpn's output.
*/
protected void validateInputs(){ // Changed protection level. ANF
boolean error = false;
for(StateGraph sg : designUnitSet){
for(String input : sg.getLpn().getAllInputs().keySet()){
boolean connected = false;
for(StateGraph sg2 : designUnitSet){
if(sg == sg2)
continue;
if(sg2.getLpn().getAllOutputs().keySet().contains(input)){
connected = true;
break;
}
}
if(!connected){
error = true;
System.err.println("error in lpn " + sg.getLpn().getLabel() + ": input variable '" + input + "' is not dependent on an output");
}
}
}
if(error){
System.exit(1);
}
}
}
|
package org.commcare.android.util;
import org.commcare.android.logic.GlobalConstants;
import org.spongycastle.jce.provider.BouncyCastleProvider;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.X509EncodedKeySpec;
public class SigningUtil {
/**
*
* @param text the parsed out text message in the expected link/signature format
* @return the download link if the message was valid and verified, null otherwise
* @throws SignatureException if we discovered a valid-looking message but could not verifyMessageSignatureHelper it
*/
public static String parseAndVerifySMS(String text) throws SignatureException {
// parse out the app link and signature. We assume there is a space after ccapp: and
// signature: and that the end of the signature is the end of the text content
try {
byte[] signatureBytes = getSignatureBytes(text);
String decodedMessage = parseAndDecodeSMS(text);
String downloadLink = getDownloadLink(decodedMessage);
boolean success = verifySMS(downloadLink, signatureBytes);
if(success){
return downloadLink;
}
} catch(Exception e) {
e.printStackTrace();
throw new SignatureException();
}
return null;
}
/**
* Get the byte representation of the signature from the plaintext. We have to pull this out
* directly because the conversion from Base64 can have a non-1:1 correspondence with the actual
* bytes
*
* @param textMessage
* @return the binary representation of the signtature
* @throws Exception if any errors are encountered
*/
public static byte[] getSignatureBytes(String textMessage) throws Exception {
byte[] messageBytes = getBytesFromSMS(textMessage);
String decodedMessageString = parseAndDecodeSMS(textMessage);
int lastSpaceIndex = getSignatureStartIndex(messageBytes);
int signatureByteLength = messageBytes.length - lastSpaceIndex;
byte[] signatureBytes = new byte[signatureByteLength];
for(int i = 0; i< signatureByteLength; i++){
signatureBytes[i] = messageBytes[i + lastSpaceIndex];
}
return signatureBytes;
}
/**
* Iterate through the byte array until we find the third "space" character (represented
* by integer 32) and then return its index
* @param messageBytes the raw bytes of the Base64 message
* @return index of the third "space" byte, -1 if none encountered
*/
private static int getSignatureStartIndex(byte[] messageBytes) {
int index = 0;
int spaceCount = 0;
int spaceByte = 32;
for(byte b: messageBytes){
if(b == spaceByte){
if(spaceCount == 2){
return index + 1;
}
else{
spaceCount++;
}
}
index++;
}
return -1;
}
/**
* @param textMessage the plain text SMS message
* @return the parsed out profile link
*/
public static String getDownloadLink(String textMessage){
String downloadLink = textMessage.substring(textMessage.indexOf("ccapp: ") + "ccapp: ".length(),
textMessage.indexOf("signature") - 1);
return downloadLink;
}
// given a text message, parse out the cruft and return the raw Base64 bytes
public static byte[] getBytesFromSMS(String newMessage) throws Exception{
return Base64.decode(parseMessage(newMessage));
}
// given a text message, parse out the cruft and return the raw String
private static String parseAndDecodeSMS(String newMessage) throws Exception {
String parsed = parseMessage(newMessage);
return decodeEncodedSMS(parsed);
}
// given a text message, parse out the cruft and return
private static String parseMessage(String newMessage){
String parsed = newMessage.substring(newMessage.indexOf(GlobalConstants.SMS_INSTALL_KEY_STRING) +
GlobalConstants.SMS_INSTALL_KEY_STRING.length() + 1);
return parsed;
}
private static boolean verifySMS(String message, byte[] signature){
String keyString = GlobalConstants.CCHQ_PUBLIC_KEY;
return SigningUtil.verifyMessageSignatureHelper(keyString, message, signature);
}
/**
*
* @param publicKeyString the known public key of CCHQ
* @param message the message content
* @param messageSignature the signature generated by HQ with its private key and the message content
* @return whether or not the message was verified to be sent with HQ's private key
*/
public static boolean verifyMessageSignatureHelper(String publicKeyString, String message, byte[] messageSignature) {
try {
PublicKey publicKey = getPublicKey(publicKeyString);
return verifyMessageSignature(publicKey, message, messageSignature);
} catch (Exception e) {
// a bunch of exceptions can be thrown from the crypto methods. I mostly think we just
// care that we couldn't verify it
e.printStackTrace();
}
return false;
}
// convert from a key string to a PublicKey object
private static PublicKey getPublicKey(String key) throws Exception{
byte[] derPublicKey = Base64.decode(key);
X509EncodedKeySpec spec = new X509EncodedKeySpec(derPublicKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
private static boolean verifyMessageSignature(PublicKey publicKey, String messageString, byte[] signature) throws SignatureException, NoSuchAlgorithmException, Base64DecoderException, InvalidKeyException {
Signature sign = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
byte[] message = messageString.getBytes();
sign.initVerify(publicKey);
sign.update(message);
return sign.verify(signature);
}
private static String decodeEncodedSMS(String text) throws SignatureException{
String decodedMessage = null;
try {
decodedMessage = new String(Base64.decode(text), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new SignatureException();
} catch (Base64DecoderException e) {
e.printStackTrace();
throw new SignatureException();
}
return decodedMessage;
}
}
|
package processing.app.tools;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.util.Arrays;
import java.util.Random;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import processing.app.helpers.FileUtils;
public class ZipDeflaterTest {
private File destFolder;
@Before
public void makeTempFolder() {
destFolder = new File(System.getProperty("java.io.tmpdir") + File.separator + "arduino_zip_test_" + new Random().nextInt(100000));
destFolder.mkdir();
}
@Test
public void shouldDeflateZip() throws Exception {
File file = new File(ZipDeflater.class.getResource("/Test2.zip").getFile());
new ZipDeflater(file, destFolder).deflate();
String[] files = destFolder.list();
assertNotNull(files);
assertEquals(1, files.length);
assertEquals("Test2", files[0]);
File[] destFolders = destFolder.listFiles();
assertNotNull(destFolders);
assertTrue(destFolders.length > 0);
file = destFolders[0];
assertNotNull(file);
files = file.list();
assertNotNull(files);
assertEquals(5, files.length);
Arrays.sort(files);
assertEquals("Test.cpp", files[0]);
assertEquals("Test.h", files[1]);
assertEquals("examples", files[2]);
assertEquals("keywords.txt", files[3]);
assertEquals("readme.txt", files[4]);
}
@Test
public void shouldDeflateZipAndMoveContentsToParentFolder() throws Exception {
File file = new File(ZipDeflater.class.getResource("/Test.zip").getFile());
new ZipDeflater(file, destFolder).deflate();
String[] files = destFolder.list();
assertNotNull(files);
assertEquals(1, files.length);
assertEquals("Test", files[0]);
File[] destFolders = destFolder.listFiles();
assertNotNull(destFolders);
assertTrue(destFolders.length > 0);
file = destFolders[0];
assertNotNull(file);
files = file.list();
assertNotNull(files);
assertEquals(5, files.length);
Arrays.sort(files);
assertEquals("Test.cpp", files[0]);
assertEquals("Test.h", files[1]);
assertEquals("examples", files[2]);
assertEquals("keywords.txt", files[3]);
assertEquals("readme.txt", files[4]);
}
@Test
public void shouldDeflateMacZip() throws Exception {
File file = new File(ZipDeflater.class.getResource("/Keypad_mac.zip").getFile());
new ZipDeflater(file, destFolder).deflate();
String[] files = destFolder.list();
assertNotNull(files);
assertEquals(1, files.length);
assertEquals("Keypad", files[0]);
File[] destFolders = destFolder.listFiles();
assertNotNull(destFolders);
assertTrue(destFolders.length > 0);
file = destFolders[0];
assertNotNull(file);
files = file.list();
assertNotNull(files);
assertEquals(4, files.length);
Arrays.sort(files);
assertEquals("Keypad.cpp", files[0]);
assertEquals("Keypad.h", files[1]);
assertEquals("examples", files[2]);
assertEquals("keywords.txt", files[3]);
files = new File(file, "examples").list();
assertNotNull(files);
assertEquals(4, files.length);
Arrays.sort(files);
assertEquals("CustomKeypad", files[0]);
assertEquals("DynamicKeypad", files[1]);
assertEquals("EventKeypad", files[2]);
assertEquals("HelloKeypad", files[3]);
}
@Test
public void shouldDeleteHiddenFiles() throws Exception {
File file = new File(ZipDeflater.class.getResource("/Keypad_with_hidden_files.zip").getFile());
new ZipDeflater(file, destFolder).deflate();
String[] files = destFolder.list();
assertNotNull(files);
assertEquals(1, files.length);
assertEquals("Keypad_with_hidden_files", files[0]);
File[] destFolders = destFolder.listFiles();
assertNotNull(destFolders);
assertTrue(destFolders.length > 0);
file = destFolders[0];
assertNotNull(file);
files = file.list();
assertNotNull(files);
assertEquals(4, files.length);
}
@After
public void deleteTempFolder() {
FileUtils.recursiveDelete(destFolder);
}
}
|
package water.util;
import java.util.Arrays;
import water.AutoBuffer;
import water.Futures;
import water.MRTask;
import water.MemoryManager;
import water.exceptions.H2OIllegalValueException;
import water.fvec.C0DChunk;
import water.fvec.Chunk;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.exceptions.H2OIllegalArgumentException;
import water.nbhm.NonBlockingHashMapLong;
import water.parser.BufferedString;
import water.parser.Categorical;
public class VecUtils {
public static Vec toCategoricalVec(Vec src) {
switch (src.get_type()) {
case Vec.T_CAT:
return src.makeCopy(src.domain());
case Vec.T_NUM:
return numericToCategorical(src);
case Vec.T_STR: // PUBDEV-2204
throw new H2OIllegalArgumentException("Changing string columns to a categorical"
+ " column has not been implemented yet.");
//return stringToCategorical(src);
case Vec.T_TIME: // PUBDEV-2205
throw new H2OIllegalArgumentException("Changing time/date columns to a categorical"
+ " column has not been implemented yet.");
case Vec.T_UUID:
throw new H2OIllegalArgumentException("Changing UUID columns to a categorical"
+ " column has not been implemented yet.");
default:
throw new H2OIllegalArgumentException("Unrecognized column type " + src.get_type_str()
+ " given to toCategoricalVec()");
}
}
/**
* Create a new vector of categorical values from string vector.
*
* To be finished, PUBDEV-2204
*
* @param src a string vector
* @return a categorical vector
*/
public static Vec stringToCategorical(Vec src) {
Vec res = null;
return res;
}
/**
* Create a new vector of categorical values from a numeric vector.
*
* This currently only ingests a vector of integers.
*
* Handling reals is PUBDEV-2207
*
* @param src a numeric vector
* @return a categorical vector
*/
public static Vec numericToCategorical(Vec src) {
if (src.isInt()) {
int min = (int) src.min(), max = (int) src.max();
// try to do the fast domain collection
long dom[] = (min >= 0 && max < Integer.MAX_VALUE - 4) ? new CollectDomainFast(max).doAll(src).domain() : new CollectDomain().doAll(src).domain();
if (dom.length > Categorical.MAX_CATEGORICAL_COUNT)
throw new H2OIllegalArgumentException("Column domain is too large to be represented as an categorical: " + dom.length + " > " + Categorical.MAX_CATEGORICAL_COUNT);
return copyOver(src, Vec.T_CAT, dom);
} else throw new H2OIllegalArgumentException("Categorical conversion can only currently be applied to integer columns.");
}
public static Vec toNumericVec(Vec src) {
switch (src.get_type()) {
case Vec.T_CAT:
return categoricalToInt(src);
case Vec.T_STR:
return stringToNumeric(src);
case Vec.T_NUM:
case Vec.T_TIME:
case Vec.T_UUID:
return src.makeCopy(null, Vec.T_NUM);
default:
throw new H2OIllegalArgumentException("Unrecognized column type " + src.get_type_str()
+ " given to toNumericVec()");
}
}
/**
* Create a new vector of numeric values from a string vector. Any rows that cannot be
* converted to a number are set to NA.
*
* Currently only does basic numeric formats. No exponents, or hex values. Doesn't
* even like commas or spaces. :( Needs love. Handling more numeric
* representations is PUBDEV-2209
*
* @param src a string vector
* @return a numeric vector
*/
public static Vec stringToNumeric(Vec src) {
if(!src.isString()) throw new H2OIllegalArgumentException("stringToNumeric conversion only works on string columns");
Vec res = new MRTask() {
@Override public void map(Chunk chk, NewChunk newChk){
if (chk instanceof C0DChunk) { // all NAs
for (int i=0; i < chk._len; i++)
newChk.addNA();
} else {
BufferedString tmpStr = new BufferedString();
for (int i=0; i < chk._len; i++) {
if (!chk.isNA(i)) {
tmpStr = chk.atStr(tmpStr, i);
switch (tmpStr.getNumericType()) {
case BufferedString.NA:
newChk.addNA(); break;
case BufferedString.INT:
newChk.addNum(Long.parseLong(tmpStr.toString()),0); break;
case BufferedString.REAL:
newChk.addNum(Double.parseDouble(tmpStr.toString())); break;
default:
throw new H2OIllegalValueException("Received unexpected type when parsing a string to a number.", this);
}
} else newChk.addNA();
}
}
}
}.doAll(Vec.T_NUM, src).outputFrame().anyVec();
assert res != null;
return res;
}
public static Vec categoricalToInt(final Vec src) {
if( src.isInt() && src.domain()==null ) return copyOver(src, Vec.T_NUM, null);
if( !src.isCategorical() ) throw new IllegalArgumentException("categoricalToInt conversion only works on categorical columns.");
// check if the 1st lvl of the domain can be parsed as int
boolean useDomain=false;
Vec newVec = copyOver(src, Vec.T_NUM, null);
try {
Integer.parseInt(src.domain()[0]);
useDomain=true;
} catch (NumberFormatException e) {
// makeCopy and return...
}
if( useDomain ) {
new MRTask() {
@Override public void map(Chunk c) {
for (int i=0;i<c._len;++i)
if( !c.isNA(i) )
c.set(i, Integer.parseInt(src.domain()[(int)c.at8(i)]));
}
}.doAll(newVec);
}
return newVec;
}
/**
* Create a new vector of string values from an existing vector.
*
* This method accepts all vector types as input. The original Vec is not mutated.
*
* If src is a string vector, a copy of the vector is made.
*
* If src is a categorical vector, levels are dropped, and the vector only records the string.
*
* For all numeric vectors, the number is converted to a string.
*
* For all UUID vectors, the hex representation is stored as a string.
*
* @param src A vector whose values will be used as the basis for a new string Vec
* @return the resulting string Vec
*/
public static Vec toStringVec(Vec src) {
switch (src.get_type()) {
case Vec.T_STR:
return src.makeCopy();
case Vec.T_CAT:
return categoricalToStringVec(src);
case Vec.T_UUID:
return UUIDToStringVec(src);
case Vec.T_TIME:
case Vec.T_NUM:
return numericToStringVec(src);
default:
throw new H2OIllegalArgumentException("Unrecognized column type " + src.get_type_str()
+ " given to toStringVec().");
}
}
/**
* Create a new vector of string values from a categorical vector.
*
* Transformation is done by a {@link Categorical2StrChkTask} which provides a mapping
* between values - without copying the underlying data.
*
* @param src a categorical vector
* @return a string vector
*/
public static Vec categoricalToStringVec(Vec src) {
if( !src.isCategorical() )
throw new H2OIllegalValueException("Can not convert a non-categorical column"
+ " using categoricalToStringVec().",src);
return new Categorical2StrChkTask(src.domain()).doAll(Vec.T_STR,src).outputFrame().anyVec();
}
private static class Categorical2StrChkTask extends MRTask<Categorical2StrChkTask> {
final String[] _domain;
Categorical2StrChkTask(String[] domain) { _domain=domain; }
@Override public void map(Chunk c, NewChunk nc) {
for(int i=0;i<c._len;++i)
if (!c.isNA(i))
nc.addStr(_domain == null ? "" + c.at8(i) : _domain[(int) c.at8(i)]);
else
nc.addNA();
}
}
/**
* Create a new vector of string values from a numeric vector.
*
* Currently only uses a default pretty printer. Would be better if
* it accepted a format string PUBDEV-2211
*
* @param src a numeric vector
* @return a string vector
*/
public static Vec numericToStringVec(Vec src) {
if (src.isCategorical() || src.isUUID())
throw new H2OIllegalValueException("Cannot convert a non-numeric column"
+ " using numericToStringVec() ",src);
Vec res = new MRTask() {
@Override
public void map(Chunk chk, NewChunk newChk) {
if (chk instanceof C0DChunk) { // all NAs
for (int i=0; i < chk._len; i++)
newChk.addNA();
} else {
for (int i=0; i < chk._len; i++) {
if (!chk.isNA(i))
newChk.addStr(PrettyPrint.number(chk, chk.atd(i), 4));
else
newChk.addNA();
}
}
}
}.doAll(Vec.T_STR, src).outputFrame().anyVec();
assert res != null;
return res;
}
/**
* Create a new vector of string values from a UUID vector.
*
* String vector is the standard hexadecimal representations of a UUID.
*
* @param src a UUID vector
* @return a string vector
*/
public static Vec UUIDToStringVec(Vec src) {
if( !src.isUUID() ) throw new H2OIllegalArgumentException("UUIDToStringVec() conversion only works on UUID columns");
Vec res = new MRTask() {
@Override public void map(Chunk chk, NewChunk newChk) {
if (chk instanceof C0DChunk) { // all NAs
for (int i=0; i < chk._len; i++)
newChk.addNA();
} else {
for (int i=0; i < chk._len; i++) {
if (!chk.isNA(i))
newChk.addStr(PrettyPrint.UUID(chk.at16l(i), chk.at16h(i)));
else
newChk.addNA();
}
}
}
}.doAll(Vec.T_STR,src).outputFrame().anyVec();
assert res != null;
return res;
}
/**
* Create a new vector of numeric values from a categorical vector.
*
* Numeric values are generated explicitly from the domain values, and not the
* enumeration levels. If a domain value cannot be translated as a number, that
* domain and all values for that domain will be NA.
*
* @param src a categorical vector
* @return a numeric vector
*/
public static Vec categoricalDomainsToNumeric(final Vec src) {
if( !src.isCategorical() ) throw new H2OIllegalArgumentException("categoricalToNumeric() conversion only works on categorical columns");
// check if the 1st lvl of the domain can be parsed as int
return new MRTask() {
@Override public void map(Chunk c) {
for (int i=0;i<c._len;++i)
if( !c.isNA(i) )
c.set(i, Integer.parseInt(src.domain()[(int)c.at8(i)]));
}
}.doAll(Vec.T_NUM, src).outputFrame().anyVec();
}
/** Collect numeric domain of given vector
* A map-reduce task to collect up the unique values of an integer vector
* and returned as the domain for the vector.
* */
public static class CollectDomain extends MRTask<CollectDomain> {
transient NonBlockingHashMapLong<String> _uniques;
@Override protected void setupLocal() { _uniques = new NonBlockingHashMapLong<>(); }
@Override public void map(Chunk ys) {
for( int row=0; row< ys._len; row++ )
if( !ys.isNA(row) )
_uniques.put(ys.at8(row), "");
}
@Override public void reduce(CollectDomain mrt) {
if( _uniques != mrt._uniques ) _uniques.putAll(mrt._uniques);
}
@Override public AutoBuffer write_impl( AutoBuffer ab ) {
return ab.putA8(_uniques==null ? null : _uniques.keySetLong());
}
@Override public CollectDomain read_impl( AutoBuffer ab ) {
assert _uniques == null || _uniques.size()==0;
long ls[] = ab.getA8();
_uniques = new NonBlockingHashMapLong<>();
if( ls != null ) for( long l : ls ) _uniques.put(l, "");
return this;
}
@Override public void copyOver(CollectDomain that) {
_uniques = that._uniques;
}
/** Returns exact numeric domain of given vector computed by this task.
* The domain is always sorted. Hence:
* domain()[0] - minimal domain value
* domain()[domain().length-1] - maximal domain value
*/
public long[] domain() {
long[] dom = _uniques.keySetLong();
Arrays.sort(dom);
return dom;
}
}
// >11x faster than CollectDomain
/** (Optimized for positive ints) Collect numeric domain of given vector
* A map-reduce task to collect up the unique values of an integer vector
* and returned as the domain for the vector.
* */
public static class CollectDomainFast extends MRTask<CollectDomainFast> {
private final int _s;
private boolean[] _u;
private long[] _d;
public CollectDomainFast(int s) { _s=s; }
@Override protected void setupLocal() { _u= MemoryManager.mallocZ(_s + 1); }
@Override public void map(Chunk ys) {
for( int row=0; row< ys._len; row++ )
if( !ys.isNA(row) )
_u[(int)ys.at8(row)]=true;
}
@Override public void reduce(CollectDomainFast mrt) { if( _u != mrt._u ) ArrayUtils.or(_u, mrt._u);}
@Override protected void postGlobal() {
int c=0;
for (boolean b : _u) if(b) c++;
_d=MemoryManager.malloc8(c);
int id=0;
for (int i = 0; i < _u.length;++i)
if (_u[i])
_d[id++]=i;
Arrays.sort(_d);
}
/** Returns exact numeric domain of given vector computed by this task.
* The domain is always sorted. Hence:
* domain()[0] - minimal domain value
* domain()[domain().length-1] - maximal domain value
*/
public long[] domain() { return _d; }
}
public static void deleteVecs(Vec[] vs, int cnt) {
Futures f = new Futures();
for (int i =0; i < cnt; i++) vs[cnt].remove(f);
f.blockForPending();
}
private static Vec copyOver(Vec src, byte type, long[] domain) {
String[][] dom = new String[1][];
dom[0]=domain==null?null:ArrayUtils.toString(domain);
return new CPTask(domain).doAll(type, src).outputFrame(null,dom).anyVec();
}
private static class CPTask extends MRTask<CPTask> {
private final long[] _domain;
CPTask(long[] domain) { _domain = domain;}
@Override public void map(Chunk c, NewChunk nc) {
for(int i=0;i<c._len;++i) {
if( c.isNA(i) ) { nc.addNA(); continue; }
if( _domain == null )
nc.addNum(c.at8(i));
else {
long num = Arrays.binarySearch(_domain,c.at8(i)); // ~24 hits in worst case for 10M levels
if( num < 0 )
throw new IllegalArgumentException("Could not find the categorical value!");
nc.addNum(num);
}
}
}
}
}
|
package com.nativelibs4java.opencl;
import static com.nativelibs4java.opencl.CLException.error;
import com.nativelibs4java.opencl.CLPlatform.DeviceFeature;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.*;
import com.nativelibs4java.opencl.library.OpenCLLibrary;
import com.nativelibs4java.opencl.library.OpenCLLibrary.cl_platform_id;
import org.bridj.*;
import org.bridj.ann.Ptr;
import org.bridj.util.ProcessUtils;
import org.bridj.util.StringUtils;
import static org.bridj.Pointer.*;
/**
* Entry point class for the OpenCL4Java Object-oriented wrappers around the OpenCL API.<br/>
* @author Olivier Chafik
*/
public class JavaCL {
static final boolean debug = "true".equals(System.getProperty("javacl.debug")) || "1".equals(System.getenv("JAVACL_DEBUG"));
static final boolean verbose = debug || "true".equals(System.getProperty("javacl.verbose")) || "1".equals(System.getenv("JAVACL_VERBOSE"));
static final int minLogLevel = Level.WARNING.intValue();
static final String JAVACL_DEBUG_COMPILER_FLAGS_PROP = "JAVACL_DEBUG_COMPILER_FLAGS";
static List<String> DEBUG_COMPILER_FLAGS;
static boolean shouldLog(Level level) {
return verbose || level.intValue() >= minLogLevel;
}
static boolean log(Level level, String message, Throwable ex) {
if (!shouldLog(level))
return true;
Logger.getLogger(JavaCL.class.getSimpleName()).log(level, message, ex);
return true;
}
static boolean log(Level level, String message) {
log(level, message, null);
return true;
}
private static int getPlatformIDs(int count, Pointer<cl_platform_id> out, Pointer<Integer> pCount) {
try {
return CL.clIcdGetPlatformIDsKHR(count, out, pCount);
} catch (Throwable th) {
return CL.clGetPlatformIDs(count, out, pCount);
}
}
@org.bridj.ann.Library("OpenCLProbe")
@org.bridj.ann.Convention(org.bridj.ann.Convention.Style.StdCall)
public static class OpenCLProbeLibrary {
static {
BridJ.setNativeLibraryActualName("OpenCLProbe", "OpenCL");
BridJ.register();
}
@org.bridj.ann.Optional
public native static synchronized int clGetPlatformIDs(int cl_uint1, Pointer<cl_platform_id > cl_platform_idPtr1, Pointer<Integer > cl_uintPtr1);
@org.bridj.ann.Optional
public native static synchronized int clIcdGetPlatformIDsKHR(int cl_uint1, Pointer<cl_platform_id > cl_platform_idPtr1, Pointer<Integer > cl_uintPtr1);
@org.bridj.ann.Optional
public native static int clGetPlatformInfo(cl_platform_id cl_platform_id1, int cl_platform_info1, @Ptr long size_t1, Pointer<? > voidPtr1, Pointer<SizeT > size_tPtr1);
private static CLInfoGetter<cl_platform_id> infos = new CLInfoGetter<cl_platform_id>() {
@Override
protected int getInfo(cl_platform_id entity, int infoTypeEnum, long size, Pointer out, Pointer<SizeT> sizeOut) {
return clGetPlatformInfo(entity, infoTypeEnum, size, out, sizeOut);
}
};
private static int getPlatformIDs(int count, Pointer<cl_platform_id> out, Pointer<Integer> pCount) {
try {
return clIcdGetPlatformIDsKHR(count, out, pCount);
} catch (Throwable th) {
return clGetPlatformIDs(count, out, pCount);
}
}
private static Pointer<cl_platform_id> getPlatformIDs() {
Pointer<Integer> pCount = allocateInt();
error(getPlatformIDs(0, null, pCount));
int nPlats = pCount.getInt();
if (nPlats == 0)
return null;
Pointer<cl_platform_id> ids = allocateTypedPointers(cl_platform_id.class, nPlats);
error(getPlatformIDs(nPlats, ids, null));
return ids;
}
public static boolean hasOpenCL1_0() {
Pointer<cl_platform_id> ids = getPlatformIDs();
if (ids == null)
return false;
for (cl_platform_id id : ids)
if (isOpenCL1_0(id))
return true;
return false;
}
public static boolean isOpenCL1_0(cl_platform_id platform) {
String version = infos.getString(platform, OpenCLLibrary.CL_PLATFORM_VERSION);
return version.matches("OpenCL 1\\.0.*");
}
public static boolean isValid() {
try {
Pointer<cl_platform_id> ids = getPlatformIDs();
return ids != null;
} catch (Throwable th) {
return false;
}
}
}
static final OpenCLLibrary CL;
static {
boolean needsAdditionalSynchronization = false;
{
OpenCLProbeLibrary probe = new OpenCLProbeLibrary();
try {
if (!probe.isValid()) {
BridJ.unregister(OpenCLProbeLibrary.class);
String alt;
if (Platform.is64Bits() && BridJ.getNativeLibraryFile(alt = "atiocl64") != null ||
BridJ.getNativeLibraryFile(alt = "atiocl32") != null ||
BridJ.getNativeLibraryFile(alt = "atiocl") != null)
{
log(Level.INFO, "Hacking around ATI's weird driver bugs (using atiocl library instead of OpenCL)", null);
BridJ.setNativeLibraryActualName("OpenCL", alt);
}
BridJ.register(OpenCLProbeLibrary.class);
}
if (probe.hasOpenCL1_0()) {
needsAdditionalSynchronization = true;
log(Level.INFO, "At least one OpenCL platform uses OpenCL 1.0, which is not thread-safe: will use synchronized low-level bindings.");
}
} finally {
probe = null;
BridJ.unregister(OpenCLProbeLibrary.class);
}
}
if (debug) {
String debugArgs = System.getenv(JAVACL_DEBUG_COMPILER_FLAGS_PROP);
if (debugArgs != null)
DEBUG_COMPILER_FLAGS = Arrays.asList(debugArgs.split(" "));
else if (Platform.isMacOSX())
DEBUG_COMPILER_FLAGS = Arrays.asList("-g");
else
DEBUG_COMPILER_FLAGS = Arrays.asList("-O0", "-g");
int pid = ProcessUtils.getCurrentProcessId();
log(Level.INFO, "Debug mode enabled with compiler flags \"" + StringUtils.implode(DEBUG_COMPILER_FLAGS, " ") + "\" (can be overridden with env. var. JAVACL_DEBUG_COMPILER_FLAGS_PROP)");
log(Level.INFO, "You can debug your kernels with GDB using one of the following commands :\n"
+ "\tsudo gdb --tui --pid=" + pid + "\n"
+ "\tsudo ddd --debugger \"gdb --pid=" + pid + "\"\n"
+ "More info here :\n"
+ "\thttp://code.google.com/p/javacl/wiki/DebuggingKernels");
}
Class<? extends OpenCLLibrary> libraryClass = OpenCLLibrary.class;
if (needsAdditionalSynchronization) {
try {
libraryClass = BridJ.subclassWithSynchronizedNativeMethods(libraryClass);
} catch (Throwable ex) {
throw new RuntimeException("Failed to create a synchronized version of the OpenCL API bindings: " + ex, ex);
}
}
BridJ.register(libraryClass);
try {
CL = libraryClass.newInstance();
} catch (Throwable ex) {
throw new RuntimeException("Failed to instantiate library " + libraryClass.getName() + ": " + ex, ex);
}
}
/**
* List the OpenCL implementations that contain at least one GPU device.
*/
public static CLPlatform[] listGPUPoweredPlatforms() {
CLPlatform[] platforms = listPlatforms();
List<CLPlatform> out = new ArrayList<CLPlatform>(platforms.length);
for (CLPlatform platform : platforms) {
if (platform.listGPUDevices(true).length > 0)
out.add(platform);
}
return out.toArray(new CLPlatform[out.size()]);
}
/**
* Lists all available OpenCL implementations.
*/
public static CLPlatform[] listPlatforms() {
Pointer<Integer> pCount = allocateInt();
error(getPlatformIDs(0, null, pCount));
int nPlats = pCount.getInt();
if (nPlats == 0)
return new CLPlatform[0];
Pointer<cl_platform_id> ids = allocateTypedPointers(cl_platform_id.class, nPlats);
error(getPlatformIDs(nPlats, ids, null));
CLPlatform[] platforms = new CLPlatform[nPlats];
for (int i = 0; i < nPlats; i++) {
platforms[i] = new CLPlatform(ids.get(i));
}
return platforms;
}
/**
* Creates an OpenCL context formed of the provided devices.<br/>
* It is generally not a good idea to create a context with more than one device,
* because much data is shared between all the devices in the same context.
* @param devices devices that are to form the new context
* @return new OpenCL context
*/
public static CLContext createContext(Map<CLPlatform.ContextProperties, Object> contextProperties, CLDevice... devices) {
return devices[0].getPlatform().createContext(contextProperties, devices);
}
/**
* Allows the implementation to release the resources allocated by the OpenCL compiler. <br/>
* This is a hint from the application and does not guarantee that the compiler will not be used in the future or that the compiler will actually be unloaded by the implementation. <br/>
* Calls to Program.build() after unloadCompiler() will reload the compiler, if necessary, to build the appropriate program executable.
*/
public static void unloadCompiler() {
error(CL.clUnloadCompiler());
}
/**
* Returns the "best" OpenCL device (currently, the one that has the largest amount of compute units).<br>
* For more control on what is to be considered a better device, please use the {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature[]) } variant.<br>
* This is currently equivalent to <code>getBestDevice(MaxComputeUnits)</code>
*/
public static CLDevice getBestDevice() {
return getBestDevice(CLPlatform.DeviceFeature.MaxComputeUnits);
}
/**
* Returns the "best" OpenCL device based on the comparison of the provided prioritized device feature.<br>
* The returned device does not necessarily exhibit the features listed in preferredFeatures, but it has the best ordered composition of them.<br>
* For instance on a system with a GPU and a CPU device, <code>JavaCL.getBestDevice(CPU, MaxComputeUnits)</code> will return the CPU device, but on another system with two GPUs and no CPU device it will return the GPU that has the most compute units.
*/
public static CLDevice getBestDevice(CLPlatform.DeviceFeature... preferredFeatures) {
List<CLDevice> devices = new ArrayList<CLDevice>();
for (CLPlatform platform : listPlatforms())
devices.addAll(Arrays.asList(platform.listAllDevices(true)));
return CLPlatform.getBestDevice(Arrays.asList(preferredFeatures), devices);
}
/**
* Creates an OpenCL context with the "best" device (see {@link JavaCL#getBestDevice() })
*/
public static CLContext createBestContext() {
return createBestContext(DeviceFeature.MaxComputeUnits);
}
/**
* Creates an OpenCL context with the "best" device based on the comparison of the provided
* prioritized device feature (see {@link JavaCL#getBestDevice(CLPlatform.DeviceFeature...) })
*/
public static CLContext createBestContext(CLPlatform.DeviceFeature... preferredFeatures) {
CLDevice device = getBestDevice(preferredFeatures);
return device.getPlatform().createContext(null, device);
}
/**
* Creates an OpenCL context able to share entities with the current OpenGL context.
* @throws RuntimeException if JavaCL is unable to create an OpenGL-shared OpenCL context.
*/
public static CLContext createContextFromCurrentGL() {
RuntimeException first = null;
for (CLPlatform platform : listPlatforms()) {
try {
CLContext ctx = platform.createContextFromCurrentGL();
if (ctx != null)
return ctx;
} catch (RuntimeException ex) {
if (first == null)
first = ex;
}
}
throw new RuntimeException("Failed to create an OpenCL context based on the current OpenGL context", first);
}
static File userJavaCLDir = new File(new File(System.getProperty("user.home")), ".javacl");
static File userCacheDir = new File(userJavaCLDir, "cache");
static synchronized File createTempFile(String prefix, String suffix, String category) {
File dir = new File(userJavaCLDir, category);
dir.mkdirs();
try {
return File.createTempFile(prefix, suffix, dir);
} catch (IOException ex) {
throw new RuntimeException("Failed to create a temporary directory for category '" + category + "' in " + userJavaCLDir + ": " + ex.getMessage(), ex);
}
}
static synchronized File createTempDirectory(String prefix, String suffix, String category) {
File file = createTempFile(prefix, suffix, category);
file.delete();
file.mkdir();
return file;
}
}
|
package org.jboss.dmr.client;
import java.io.IOException;
public class DataInput {
private int pos = 0;
private byte[] bytes;
public DataInput(byte[] bytes) {
this.bytes = bytes;
}
public int read() throws IOException {
return bytes[pos++];
}
public boolean readBoolean() throws IOException {
return readByte() != 0;
}
public byte readByte() throws IOException {
int i = read();
/*if (i == -1) {
throw new RuntimeException("EOF");
} */
return (byte) i;
}
public char readChar() throws IOException {
int a = readByte();
int b = readUnsignedByte();
return (char) ((a << 8) | b);
}
public double readDouble() throws IOException {
throw new RuntimeException("readDouble");
}
public float readFloat() throws IOException {
throw new RuntimeException("readFloat");
}
public int readInt() throws IOException {
int a = readByte();
int b = readByte();
int c = readByte();
int d = readUnsignedByte();
return (a << 24) | (b << 16) | (c << 8) | d;
}
public String readLine() throws IOException {
throw new RuntimeException("readline NYI");
}
public long readLong() throws IOException {
long a = readInt();
long b = readInt() & 0x0ffffffff;
return (a << 32) | b;
}
public short readShort() throws IOException {
int a = readByte();
int b = readUnsignedByte();
return (short) ((a << 8) | b);
}
public String readUTF() throws IOException {
int bytes = readUnsignedShort();
StringBuilder sb = new StringBuilder();
while (bytes > 0) {
bytes -= readUtfChar(sb);
}
return sb.toString();
}
private int readUtfChar(StringBuilder sb) throws IOException {
int a = readUnsignedByte();
if ((a & 0x80) == 0) {
sb.append((char) a);
return 1;
}
if ((a & 0xe0) == 0xb0) {
int b = readUnsignedByte();
sb.append((char)(((a& 0x1F) << 6) | (b & 0x3F)));
return 2;
}
if ((a & 0xf0) == 0xe0) {
int b = readByte();
int c = readUnsignedByte();
sb.append((char)(((a & 0x0F) << 12) | ((b & 0x3F) << 6) | (c & 0x3F)));
return 3;
}
throw new IllegalArgumentException("Illegal byte "+a);
}
/*public int readUnsignedByte() throws IOException {
int i = read();
if (i == -1) {
throw new RuntimeException("EOF");
}
return i;
} */
public int readUnsignedByte() throws IOException {
return readByte() & 0xFF;
}
public int readUnsignedShort() throws IOException {
int a = readByte();
int b = readUnsignedByte();
return ((a << 8) | b);
}
public int skipBytes(int n) throws IOException {
// note: This is actually a valid implementation of this method, rendering it quite useless...
return 0;
}
public void readFully(byte[] b) {
for (int i = 0; i < b.length; i++) {
b[i] = bytes[pos++];
}
}
}
|
package verification.platu.stategraph;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.IndexObjMap;
import verification.platu.logicAnalysis.Constraint;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LpnTranList;
import verification.platu.main.Main;
import verification.platu.main.Options;
import verification.platu.project.PrjState;
import verification.timed_state_exploration.zoneProject.ContinuousUtilities;
import verification.timed_state_exploration.zoneProject.EventSet;
import verification.timed_state_exploration.zoneProject.InequalityVariable;
import verification.timed_state_exploration.zoneProject.Event;
import verification.timed_state_exploration.zoneProject.LPNTransitionPair;
import verification.timed_state_exploration.zoneProject.TimedPrjState;
import verification.timed_state_exploration.zoneProject.Zone;
public class StateGraph {
protected State init = null;
protected IndexObjMap<State> stateCache;
protected IndexObjMap<State> localStateCache;
protected HashMap<State, State> state2LocalMap;
protected HashMap<State, LpnTranList> enabledSetTbl;
protected HashMap<State, HashMap<Transition, State>> nextStateMap;
protected List<State> stateSet = new LinkedList<State>();
protected List<State> frontierStateSet = new LinkedList<State>();
protected List<State> entryStateSet = new LinkedList<State>();
protected List<Constraint> oldConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> newConstraintSet = new LinkedList<Constraint>();
protected List<Constraint> frontierConstraintSet = new LinkedList<Constraint>();
protected Set<Constraint> constraintSet = new HashSet<Constraint>();
protected LhpnFile lpn;
public StateGraph(LhpnFile lpn) {
this.lpn = lpn;
this.stateCache = new IndexObjMap<State>();
this.localStateCache = new IndexObjMap<State>();
this.state2LocalMap = new HashMap<State, State>();
this.enabledSetTbl = new HashMap<State, LpnTranList>();
this.nextStateMap = new HashMap<State, HashMap<Transition, State>>();
}
public LhpnFile getLpn(){
return this.lpn;
}
public void printStates(){
System.out.println(String.format("%-8s %5s", this.lpn.getLabel(), "|States| = " + stateCache.size()));
}
public Set<Transition> getTranList(State currentState){
return this.nextStateMap.get(currentState).keySet();
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* @param baseState - State to start from
* @return Number of new transitions.
*/
public int constrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State newState = constrFire(firedTran,currentState);
State nextState = addState(newState);
newStateFlag = false;
if(nextState == newState){
addFrontierState(nextState);
newStateFlag = true;
}
// StateTran stTran = new StateTran(currentState, firedTran, state);
if(nextState != currentState){
// this.addStateTran(currentState, nextState, firedTran);
this.addStateTran(currentState, firedTran, nextState);
newTransitions++;
// TODO: (original) check that a variable was changed before creating a constraint
if(!firedTran.isLocal()){
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraint.
}
}
}
if(!newStateFlag) continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions.isEmpty()) continue;
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// System.out.println("Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
// currentState.setFailure();
// return -1;
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
/**
* Finds reachable states from the given state.
* Also generates new constraints from the state transitions.
* Synchronized version of constrFindSG(). Method is not synchronized, but uses synchronized methods
* @param baseState State to start from
* @return Number of new transitions.
*/
public int synchronizedConstrFindSG(final State baseState){
boolean newStateFlag = false;
int ptr = 1;
int newTransitions = 0;
Stack<State> stStack = new Stack<State>();
Stack<LpnTranList> tranStack = new Stack<LpnTranList>();
LpnTranList currentEnabledTransitions = getEnabled(baseState);
stStack.push(baseState);
tranStack.push((LpnTranList) currentEnabledTransitions);
while (true){
ptr
State currentState = stStack.pop();
currentEnabledTransitions = tranStack.pop();
for (Transition firedTran : currentEnabledTransitions) {
State st = constrFire(firedTran,currentState);
State nextState = addState(st);
newStateFlag = false;
if(nextState == st){
newStateFlag = true;
addFrontierState(nextState);
}
if(nextState != currentState){
newTransitions++;
if(!firedTran.isLocal()){
// TODO: (original) check that a variable was changed before creating a constraint
for(LhpnFile lpn : firedTran.getDstLpnList()){
// TODO: (temp) Hack here.
Constraint c = null; //new Constraint(currentState, nextState, firedTran, lpn);
// TODO: (temp) Ignore constraints.
}
}
}
if(!newStateFlag)
continue;
LpnTranList nextEnabledTransitions = getEnabled(nextState);
if (nextEnabledTransitions == null || nextEnabledTransitions.isEmpty()) {
continue;
}
// currentEnabledTransitions = getEnabled(nexState);
// Transition disabledTran = firedTran.disablingError(currentEnabledTransitions, nextEnabledTransitions);
// if(disabledTran != null) {
// prDbg(10, "Verification failed: " +disabledTran.getFullLabel() + " is disabled by " +
// firedTran.getFullLabel());
// currentState.setFailure();
// return -1;
stStack.push(nextState);
tranStack.push(nextEnabledTransitions);
ptr++;
}
if (ptr == 0) {
break;
}
}
return newTransitions;
}
public List<State> getFrontierStateSet(){
return this.frontierStateSet;
}
public List<State> getStateSet(){
return this.stateSet;
}
public void addFrontierState(State st){
this.entryStateSet.add(st);
}
public List<Constraint> getOldConstraintSet(){
return this.oldConstraintSet;
}
/**
* Adds constraint to the constraintSet.
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public boolean addConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
/**
* Adds constraint to the constraintSet. Synchronized version of addConstraint().
* @param c - Constraint to be added.
* @return True if added, otherwise false.
*/
public synchronized boolean synchronizedAddConstraint(Constraint c){
if(this.constraintSet.add(c)){
this.frontierConstraintSet.add(c);
return true;
}
return false;
}
public List<Constraint> getNewConstraintSet(){
return this.newConstraintSet;
}
public void genConstraints(){
oldConstraintSet.addAll(newConstraintSet);
newConstraintSet.clear();
newConstraintSet.addAll(frontierConstraintSet);
frontierConstraintSet.clear();
}
public void genFrontier(){
this.stateSet.addAll(this.frontierStateSet);
this.frontierStateSet.clear();
this.frontierStateSet.addAll(this.entryStateSet);
this.entryStateSet.clear();
}
public void setInitialState(State init){
this.init = init;
}
public State getInitialState(){
return this.init;
}
public void draw(){
String dotFile = Options.getDotPath();
if(!dotFile.endsWith("/") && !dotFile.endsWith("\\")){
String dirSlash = "/";
if(Main.isWindows) dirSlash = "\\";
dotFile = dotFile += dirSlash;
}
dotFile += this.lpn.getLabel() + ".dot";
PrintStream graph = null;
try {
graph = new PrintStream(new FileOutputStream(dotFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
graph.println("digraph SG{");
//graph.println(" fixedsize=true");
int size = this.lpn.getAllOutputs().size() + this.lpn.getAllInputs().size() + this.lpn.getAllInternals().size();
String[] variables = new String[size];
DualHashMap<String, Integer> varIndexMap = this.lpn.getVarIndexMap();
int i;
for(i = 0; i < size; i++){
variables[i] = varIndexMap.getKey(i);
}
//for(State state : this.reachableSet.keySet()){
for(int stateIdx = 0; stateIdx < this.reachSize(); stateIdx++) {
State state = this.getState(stateIdx);
String dotLabel = state.getIndex() + ": ";
int[] vector = state.getVector();
for(i = 0; i < size; i++){
dotLabel += variables[i];
if(vector[i] == 0) dotLabel += "'";
if(i < size-1) dotLabel += " ";
}
int[] mark = state.getMarking();
dotLabel += "\\n";
for(i = 0; i < mark.length; i++){
if(i == 0) dotLabel += "[";
dotLabel += mark[i];
if(i < mark.length - 1)
dotLabel += ", ";
else
dotLabel += "]";
}
String attributes = "";
if(state == this.init) attributes += " peripheries=2";
if(state.failure()) attributes += " style=filled fillcolor=\"red\"";
graph.println(" " + state.getIndex() + "[shape=ellipse width=.3 height=.3 " +
"label=\"" + dotLabel + "\"" + attributes + "]");
for(Entry<Transition, State> stateTran : this.nextStateMap.get(state).entrySet()){
State tailState = state;
State headState = stateTran.getValue();
Transition lpnTran = stateTran.getKey();
String edgeLabel = lpnTran.getName() + ": ";
int[] headVector = headState.getVector();
int[] tailVector = tailState.getVector();
for(i = 0; i < size; i++){
if(headVector[i] != tailVector[i]){
if(headVector[i] == 0){
edgeLabel += variables[i];
edgeLabel += "-";
}
else{
edgeLabel += variables[i];
edgeLabel += "+";
}
}
}
graph.println(" " + tailState.getIndex() + " -> " + headState.getIndex() + "[label=\"" + edgeLabel + "\"]");
}
}
graph.println("}");
graph.close();
}
/**
* Return the enabled transitions in the state with index 'stateIdx'.
* @param stateIdx
* @return
*/
public LpnTranList getEnabled(int stateIdx) {
State curState = this.getState(stateIdx);
return this.getEnabled(curState);
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
return curEnabled;
}
/**
* Return the set of all LPN transitions that are enabled in 'state'.
* @param curState
* @return
*/
public LpnTranList getEnabled(State curState, boolean init) {
if (curState == null) {
throw new NullPointerException();
}
if(enabledSetTbl.containsKey(curState) == true){
if (Options.getDebugMode()) {
System.out.println("~~~~~~~ existing state in enabledSetTbl for LPN" + curState.getLpn().getLabel() + ": S" + curState.getIndex() + "~~~~~~~~");
printTransitionSet((LpnTranList)enabledSetTbl.get(curState), "enabled trans at this state ");
}
return (LpnTranList)enabledSetTbl.get(curState).clone();
}
LpnTranList curEnabled = new LpnTranList();
if (init) {
for (Transition tran : this.lpn.getAllTransitions()) {
if (isEnabled(tran,curState)) {
if (Options.getDebugMode())
System.out.println("Transition " + tran.getLpn().getLabel() + "(" + tran.getName() + ") is enabled");
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
}
else {
for (int i=0; i < this.lpn.getAllTransitions().length; i++) {
Transition tran = this.lpn.getAllTransitions()[i];
if (curState.getTranVector()[i])
if(tran.isLocal()==true)
curEnabled.addLast(tran);
else
curEnabled.addFirst(tran);
}
}
this.enabledSetTbl.put(curState, curEnabled);
if (Options.getDebugMode()) {
System.out.println("~~~~~~~~ State S" + curState.getIndex() + " does not exist in enabledSetTbl for LPN " + curState.getLpn().getLabel() + ". Add to enabledSetTbl.");
printEnabledSetTbl();
}
return curEnabled;
}
private void printEnabledSetTbl() {
System.out.println("******* enabledSetTbl**********");
for (State s : enabledSetTbl.keySet()) {
System.out.print("S" + s.getIndex() + " -> ");
printTransitionSet(enabledSetTbl.get(s), "");
}
}
public boolean isEnabled(Transition tran, State curState) {
int[] varValuesVector = curState.getVector();
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode())
System.out.println("Checking " + tran);
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0
&& !(tran.isPersistent() && curState.getTranVector()[tranIndex])) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Enabling condition is false");
return false;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(varValuesVector)) == 0.0) {
if (Options.getDebugMode())
System.out.println("Rate is zero");
return false;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
int[] curMarking = curState.getMarking();
for (int place : this.lpn.getPresetIndex(tranName)) {
if (curMarking[place]==0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Missing a preset token");
return false;
}
}
// if a transition is enabled and it is not recorded in the enabled transition vector
curState.getTranVector()[tranIndex] = true;
}
return true;
}
public int reachSize() {
if(this.stateCache == null){
return this.stateSet.size();
}
return this.stateCache.size();
}
public boolean stateOnStack(State curState, HashSet<PrjState> stateStack) {
boolean isStateOnStack = false;
for (PrjState prjState : stateStack) {
State[] stateArray = prjState.toStateArray();
for (State s : stateArray) {
if (s == curState) {
isStateOnStack = true;
break;
}
}
if (isStateOnStack)
break;
}
return isStateOnStack;
}
/*
* Add the module state mState into the local cache, and also add its local portion into
* the local portion cache, and build the mapping between the mState and lState for fast lookup
* in the future.
*/
public State addState(State mState) {
State cachedState = this.stateCache.add(mState);
State lState = this.state2LocalMap.get(cachedState);
if(lState == null) {
lState = cachedState.getLocalState();
lState = this.localStateCache.add(lState);
this.state2LocalMap.put(cachedState, lState);
}
return cachedState;
}
/*
* Get the local portion of mState from the cache..
*/
public State getLocalState(State mState) {
return this.state2LocalMap.get(mState);
}
public State getState(int stateIdx) {
return this.stateCache.get(stateIdx);
}
public void addStateTran(State curSt, Transition firedTran, State nextSt) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null) {
nextMap = new HashMap<Transition,State>();
nextMap.put(firedTran, nextSt);
this.nextStateMap.put(curSt, nextMap);
}
else
nextMap.put(firedTran, nextSt);
}
public State getNextState(State curSt, Transition firedTran) {
HashMap<Transition, State> nextMap = this.nextStateMap.get(curSt);
if(nextMap == null)
return null;
return nextMap.get(firedTran);
}
private static Set<Entry<Transition, State>> emptySet = new HashSet<Entry<Transition, State>>(0);
public Set<Entry<Transition, State>> getOutgoingTrans(State currentState){
HashMap<Transition, State> tranMap = this.nextStateMap.get(currentState);
if(tranMap == null){
return emptySet;
}
return tranMap.entrySet();
}
public int numConstraints(){
if(this.constraintSet == null){
return this.oldConstraintSet.size();
}
return this.constraintSet.size();
}
public void clear(){
this.constraintSet.clear();
this.frontierConstraintSet.clear();
this.newConstraintSet.clear();
this.frontierStateSet.clear();
this.entryStateSet.clear();
this.constraintSet = null;
this.frontierConstraintSet = null;
this.newConstraintSet = null;
this.frontierStateSet = null;
this.entryStateSet = null;
this.stateCache = null;
}
public State getInitState() {
// create initial vector
int size = this.lpn.getVarIndexMap().size();
int[] initialVector = new int[size];
for(int i = 0; i < size; i++) {
String var = this.lpn.getVarIndexMap().getKey(i);
int val = this.lpn.getInitVector(var);// this.initVector.get(var);
initialVector[i] = val;
}
return new State(this.lpn, this.lpn.getInitialMarkingsArray(), initialVector, this.lpn.getInitEnabledTranArray(initialVector));
}
/**
* Fire a transition on a state array, find new local states, and return the new state array formed by the new local states.
* @param firedTran
* @param curLpnArray
* @param curStateArray
* @param curLpnIndex
* @return
*/
public State[] fire(final StateGraph[] curSgArray, final int[] curStateIdxArray, Transition firedTran) {
State[] stateArray = new State[curSgArray.length];
for(int i = 0; i < curSgArray.length; i++)
stateArray[i] = curSgArray[i].getState(curStateIdxArray[i]);
return this.fire(curSgArray, stateArray, firedTran);
}
// This method is called by search_dfs(StateGraph[], State[]).
public State[] fire(final StateGraph[] curSgArray, final State[] curStateArray, Transition firedTran) {
int thisLpnIndex = this.getLpn().getLpnIndex();
State[] nextStateArray = curStateArray.clone();
State curState = curStateArray[thisLpnIndex];
State nextState = this.fire(curSgArray[thisLpnIndex], curState, firedTran);
//int[] nextVector = nextState.getVector();
//int[] curVector = curState.getVector();
// TODO: (future) assertions in our LPN?
/*
for(Expression e : assertions){
if(e.evaluate(nextVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
nextStateArray[thisLpnIndex] = nextState;
if(firedTran.isLocal()==true) {
// nextStateArray[thisLpnIndex] = curSgArray[thisLpnIndex].addState(nextState);
return nextStateArray;
}
HashMap<String, Integer> vvSet = new HashMap<String, Integer>();
vvSet = this.lpn.getAllVarsWithValuesAsInt(nextState.getVector());
// for (String key : this.lpn.getAllVarsWithValuesAsString(curState.getVector()).keySet()) {
// if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// // TODO: (temp) type cast continuous variable to int.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
// if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curState.getVector()));
// vvSet.put(key, newValue);
/*
for (VarExpr s : this.getAssignments()) {
int newValue = nextVector[s.getVar().getIndex(curVector)];
vvSet.put(s.getVar().getName(), newValue);
}
*/
// Update other local states with the new values generated for the shared variables.
//nextStateArray[this.lpn.getIndex()] = nextState;
// if (!firedTran.getDstLpnList().contains(this.lpn))
// firedTran.getDstLpnList().add(this.lpn);
for(LhpnFile curLPN : firedTran.getDstLpnList()) {
int curIdx = curLPN.getLpnIndex();
// System.out.println("Checking " + curLPN.getLabel() + " " + curIdx);
State newState = curSgArray[curIdx].getNextState(curStateArray[curIdx], firedTran);
if(newState != null) {
nextStateArray[curIdx] = newState;
}
else {
State newOther = curStateArray[curIdx].update(curSgArray[curIdx], vvSet, curSgArray[curIdx].getLpn().getVarIndexMap());
if (newOther == null)
nextStateArray[curIdx] = curStateArray[curIdx];
else {
State cachedOther = curSgArray[curIdx].addState(newOther);
//nextStateArray[curIdx] = newOther;
nextStateArray[curIdx] = cachedOther;
// System.out.println("ADDING TO " + curIdx + ":\n" + curStateArray[curIdx].getIndex() + ":\n" +
// curStateArray[curIdx].print() + firedTran.getName() + "\n" +
// cachedOther.getIndex() + ":\n" + cachedOther.print());
curSgArray[curIdx].addStateTran(curStateArray[curIdx], firedTran, cachedOther);
}
}
}
return nextStateArray;
}
// TODO: (original) add transition that fires to parameters
public State fire(final StateGraph thisSg, final State curState, Transition firedTran) {
// Search for and return cached next state first.
// if(this.nextStateMap.containsKey(curState) == true)
// return (State)this.nextStateMap.get(curState);
State nextState = thisSg.getNextState(curState, firedTran);
if(nextState != null)
return nextState;
// If no cached next state exists, do regular firing.
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0)
curNewMarking = curOldMarking;
else {
curNewMarking = new int[curOldMarking.length];
curNewMarking = curOldMarking.clone();
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
curNewMarking[prep]=0;
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[postp]=1;
}
}
// State vector update
int[] newVectorArray = curState.getVector().clone();
int[] curVector = curState.getVector();
for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
// TODO: (temp) type cast continuous variable to int.
// Continuous variables will be handled by the
// fire(StateGraph,PrjState,Transition) method in the timing.
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
/*
for (VarExpr s : firedTran.getAssignments()) {
int newValue = (int) s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranVector = updateEnabledTranVector(curState.getTranVector(), curNewMarking, newVectorArray, firedTran);
State newState = thisSg.addState(new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranVector));
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
thisSg.addStateTran(curState, firedTran, newState);
return newState;
}
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode())
System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode())
System.out.println("Checking " + tranName);
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Enabling condition is false");
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println("Rate is zero");
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Missing a preset token");
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode())
System.out.println(tran.getName() + " is Enabled.");
}
}
return enabledTranAfterFiring;
}
/**
* Updates the transition vector.
* @param enabledTranBeforeFiring
* The enabling before the transition firing.
* @param newMarking
* The new marking to check for transitions with.
* @param newVectorArray
* The new values of the boolean variables.
* @param firedTran
* The transition that fire.
* @param newlyEnabled
* A list to capture the newly enabled transitions.
* @return
* The newly enabled transitions.
*/
public boolean[] updateEnabledTranVector(boolean[] enabledTranBeforeFiring,
int[] newMarking, int[] newVectorArray, Transition firedTran, HashSet<LPNTransitionPair> newlyEnabled) {
boolean[] enabledTranAfterFiring = enabledTranBeforeFiring.clone();
// Disable fired transition
if (firedTran != null) {
enabledTranAfterFiring[firedTran.getIndex()] = false;
for (Integer curConflictingTranIndex : firedTran.getConflictSetTransIndices()) {
enabledTranAfterFiring[curConflictingTranIndex] = false;
}
}
// find newly enabled transition(s) based on the updated markings and variables
if (Options.getDebugMode())
System.out.println("Finding newly enabled transitions at updateEnabledTranVector.");
for (Transition tran : this.lpn.getAllTransitions()) {
boolean needToUpdate = true;
String tranName = tran.getName();
int tranIndex = tran.getIndex();
if (Options.getDebugMode())
System.out.println("Checking " + tranName);
if (this.lpn.getEnablingTree(tranName) != null
&& this.lpn.getEnablingTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Enabling condition is false");
if (enabledTranAfterFiring[tranIndex] && !tran.isPersistent())
enabledTranAfterFiring[tranIndex] = false;
continue;
}
if (this.lpn.getTransitionRateTree(tranName) != null
&& this.lpn.getTransitionRateTree(tranName).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(newVectorArray)) == 0.0) {
if (Options.getDebugMode())
System.out.println("Rate is zero");
continue;
}
if (this.lpn.getPreset(tranName) != null && this.lpn.getPreset(tranName).length != 0) {
for (int place : this.lpn.getPresetIndex(tranName)) {
if (newMarking[place]==0) {
if (Options.getDebugMode())
System.out.println(tran.getName() + " " + "Missing a preset token");
needToUpdate = false;
break;
}
}
}
if (needToUpdate) {
// if a transition is enabled and it is not recorded in the enabled transition vector
enabledTranAfterFiring[tranIndex] = true;
if (Options.getDebugMode())
System.out.println(tran.getName() + " is Enabled.");
}
if(newlyEnabled != null && enabledTranAfterFiring[tranIndex] && !enabledTranBeforeFiring[tranIndex]){
newlyEnabled.add(new LPNTransitionPair(tran.getLpn().getLpnIndex(), tranIndex));
}
}
return enabledTranAfterFiring;
}
public State constrFire(Transition firedTran, final State curState) {
// Marking update
int[] curOldMarking = curState.getMarking();
int[] curNewMarking = null;
if(firedTran.getPreset().length==0 && firedTran.getPostset().length==0){
curNewMarking = curOldMarking;
}
else {
curNewMarking = new int[curOldMarking.length - firedTran.getPreset().length + firedTran.getPostset().length];
int index = 0;
for (int i : curOldMarking) {
boolean existed = false;
for (int prep : this.lpn.getPresetIndex(firedTran.getName())) {
if (i == prep) {
existed = true;
break;
}
// TODO: (??) prep > i
else if(prep > i){
break;
}
}
if (existed == false) {
curNewMarking[index] = i;
index++;
}
}
for (int postp : this.lpn.getPostsetIndex(firedTran.getName())) {
curNewMarking[index] = postp;
index++;
}
}
// State vector update
int[] oldVector = curState.getVector();
int size = oldVector.length;
int[] newVectorArray = new int[size];
System.arraycopy(oldVector, 0, newVectorArray, 0, size);
int[] curVector = curState.getVector();
for (String key : this.lpn.getAllVarsWithValuesAsString(curVector).keySet()) {
if (this.lpn.getBoolAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getBoolAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
// TODO: (temp) type cast continuous variable to int.
if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
if (this.lpn.getIntAssignTree(firedTran.getName(), key) != null) {
int newValue = (int)this.lpn.getIntAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
}
}
// TODO: (check) Is the update is equivalent to the one below?
/*
for (VarExpr s : getAssignments()) {
int newValue = s.getExpr().evaluate(curVector);
newVectorArray[s.getVar().getIndex(curVector)] = newValue;
}
*/
// Enabled transition vector update
boolean[] newEnabledTranArray = curState.getTranVector();
newEnabledTranArray[firedTran.getIndex()] = false;
State newState = new State(this.lpn, curNewMarking, newVectorArray, newEnabledTranArray);
// TODO: (future) assertions in our LPN?
/*
int[] newVector = newState.getVector();
for(Expression e : assertions){
if(e.evaluate(newVector) == 0){
System.err.println("Assertion " + e.toString() + " failed in LPN transition " + this.lpn.getLabel() + ":" + this.label);
System.exit(1);
}
}
*/
return newState;
}
public void outputLocalStateGraph(String file) {
try {
int size = this.lpn.getVarIndexMap().size();
String varNames = "";
for(int i = 0; i < size; i++) {
varNames = varNames + ", " + this.lpn.getVarIndexMap().getKey(i);
}
varNames = varNames.replaceFirst(", ", "");
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write("digraph G {\n");
out.write("Inits [shape=plaintext, label=\"<" + varNames + ">\"]\n");
for (State curState : nextStateMap.keySet()) {
String markings = intArrayToString("markings", curState);
String vars = intArrayToString("vars", curState);
String enabledTrans = boolArrayToString("enabledTrans", curState);
String curStateName = "S" + curState.getIndex();
out.write(curStateName + "[shape=\"ellipse\",label=\"" + curStateName + "\\n<"+vars+">" + "\\n<"+enabledTrans+">" + "\\n<"+markings+">" + "\"]\n");
}
for (State curState : nextStateMap.keySet()) {
HashMap<Transition, State> stateTransitionPair = nextStateMap.get(curState);
for (Transition curTran : stateTransitionPair.keySet()) {
String curStateName = "S" + curState.getIndex();
String nextStateName = "S" + stateTransitionPair.get(curTran).getIndex();
String curTranName = curTran.getName();
if (curTran.isFail() && !curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=red]\n");
else if (!curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=blue]\n");
else if (curTran.isFail() && curTran.isPersistent())
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\", fontcolor=purple]\n");
else
out.write(curStateName + " -> " + nextStateName + " [label=\"" + curTranName + "\"]\n");
}
}
out.write("}");
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println("Error producing local state graph as dot file.");
}
}
private String intArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("markings")) {
for (int i=0; i< curState.getMarking().length; i++) {
if (curState.getMarking()[i] == 1) {
arrayStr = arrayStr + curState.getLpn().getPlaceList()[i] + ",";
}
// String tranName = curState.getLpn().getAllTransitions()[i].getName();
// if (curState.getTranVector()[i])
// System.out.println(tranName + " " + "Enabled");
// else
// System.out.println(tranName + " " + "Not Enabled");
}
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
else if (type.equals("vars")) {
for (int i=0; i< curState.getVector().length; i++) {
arrayStr = arrayStr + curState.getVector()[i] + ",";
}
if (arrayStr.contains(","))
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private String boolArrayToString(String type, State curState) {
String arrayStr = "";
if (type.equals("enabledTrans")) {
for (int i=0; i< curState.getTranVector().length; i++) {
if (curState.getTranVector()[i]) {
arrayStr = arrayStr + curState.getLpn().getAllTransitions()[i].getName() + ",";
}
}
if (arrayStr != "")
arrayStr = arrayStr.substring(0, arrayStr.lastIndexOf(","));
}
return arrayStr;
}
private void printTransitionSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
private static void printAmpleSet(LpnTranList transitionSet, String setName) {
if (!setName.isEmpty())
System.out.print(setName + " ");
if (transitionSet.isEmpty()) {
System.out.println("empty");
}
else {
for (Iterator<Transition> curTranIter = transitionSet.iterator(); curTranIter.hasNext();) {
Transition tranInDisable = curTranIter.next();
System.out.print(tranInDisable.getName() + " ");
}
System.out.print("\n");
}
}
public HashMap<State,LpnTranList> copyEnabledSetTbl() {
HashMap<State,LpnTranList> copyEnabledSetTbl = new HashMap<State,LpnTranList>();
for (State s : enabledSetTbl.keySet()) {
LpnTranList tranList = enabledSetTbl.get(s).clone();
copyEnabledSetTbl.put(s.clone(), tranList);
}
return copyEnabledSetTbl;
}
public void setEnabledSetTbl(HashMap<State, LpnTranList> enabledSetTbl) {
this.enabledSetTbl = enabledSetTbl;
}
public HashMap<State, LpnTranList> getEnabledSetTbl() {
return this.enabledSetTbl;
}
public HashMap<State, HashMap<Transition, State>> getNextStateMap() {
return this.nextStateMap;
}
/**
* Fires a transition.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param firedTran
* The transition to fire.
* @return
* The new states.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, Transition firedTran){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Extract relevant information from the current project state.
State[] curStateArray = currentTimedPrjState.toStateArray();
Zone[] currentZones = currentTimedPrjState.toZoneArray();
// Zone[] newZones = new Zone[curStateArray.length];
Zone[] newZones = new Zone[1];
// Get the new un-timed local states.
State[] newStates = fire(curSgArray, curStateArray, firedTran);
LpnTranList enabledTransitions = new LpnTranList();
for(int i=0; i<newStates.length; i++)
{
// enabledTransitions = getEnabled(newStates[i]);
// The stategraph has to be used to call getEnabled
// since it is being passed implicitly.
LpnTranList localEnabledTransitions = curSgArray[i].getEnabled(newStates[i]);
for(int j=0; j<localEnabledTransitions.size(); j++){
enabledTransitions.add(localEnabledTransitions.get(j));
}
// newZones[i] = currentZones[i].fire(firedTran,
// enabledTransitions, newStates);
// Update any continuous variable assignments.
// for (this.lpn.get) {
// if (this.lpn.getContAssignTree(firedTran.getName(), key) != null) {
//// int newValue = (int)this.lpn.getContAssignTree(firedTran.getName(), key).evaluateExpr(this.lpn.getAllVarsWithValuesAsString(curVector));
//// newVectorArray[this.lpn.getVarIndexMap().get(key)] = newValue;
// for(String contVar : this.lpn.getContVars()){
// // Get the new range.
// InveralRange range =
// this.lpn.getContAssignTree(firedTran.getName(), contVar)
// .evaluateExprBound(this.lpn.getAllVarsWithValuesAsString(curVector), z)
}
newZones[0] = currentZones[0].fire(firedTran,
enabledTransitions, newStates);
ContinuousUtilities.updateInequalities(newZones[0],
newStates[firedTran.getLpn().getLpnIndex()]);
return new TimedPrjState(newStates, newZones);
}
/**
* Fires a list of events. This list can either contain a single transition
* or a set of inequalities.
* @param curSgArray
* The current information on the all local states.
* @param currentPrjState
* The current state.
* @param eventSets
* The set of events to fire.
* @return
* The new state.
*/
public TimedPrjState fire(final StateGraph[] curSgArray,
final PrjState currentPrjState, EventSet eventSet){
TimedPrjState currentTimedPrjState;
// Check that this is a timed state.
if(currentPrjState instanceof TimedPrjState){
currentTimedPrjState = (TimedPrjState) currentPrjState;
}
else{
throw new IllegalArgumentException("Attempted to use the " +
"fire(StateGraph[],PrjState,Transition)" +
"without a TimedPrjState stored in the PrjState " +
"variable. This method is meant for TimedPrjStates.");
}
// Determine if the list of events represents a list of inequalities.
if(eventSet.isInequalities()){
// Create a copy of the current states.
State[] oldStates = currentTimedPrjState.getStateArray();
State[] states = new State[oldStates.length];
for(int i=0; i<oldStates.length; i++){
states[i] = oldStates[i].clone();
}
// Get the variable index map for getting the indecies
// of the variables.
DualHashMap<String, Integer> map = lpn.getVarIndexMap();
for(Event e : eventSet){
// Extract inequality variable.
InequalityVariable iv = e.getInequalityVariable();
// Get the index to change the value.
int variableIndex = map.getValue(iv.getName());
// Flip the value of the inequality.
int[] vector = states[this.lpn.getLpnIndex()].getVector();
vector[variableIndex] =
vector[variableIndex] == 0 ? 1 : 0;
}
HashSet<LPNTransitionPair> newlyEnabled = new HashSet<LPNTransitionPair>();
// Update the enabled transitions according to inequalities that have changed.
for(int i=0; i<states.length; i++){
boolean[] newEnabledTranVector = updateEnabledTranVector(states[i].getTranVector(),
states[i].marking, states[i].vector, null, newlyEnabled);
State newState = curSgArray[i].addState(new State(this.lpn, states[i].marking, states[i].vector, newEnabledTranVector));
states[i] = newState;
}
// Get a new zone that has been restricted according to the inequalities firing.
Zone z = currentTimedPrjState.get_zones()[0].getContinuousRestrictedZone(eventSet);
// Add any new transitions.
z = z.addTransition(newlyEnabled, states);
// return new TimedPrjState(states, currentTimedPrjState.get_zones());
return new TimedPrjState(states, new Zone[]{z});
}
return fire(curSgArray, currentPrjState, eventSet.getTransition());
}
}
|
package water.util;
import hex.CreateFrame;
import hex.Model;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.DKV;
import water.Key;
import water.Scope;
import water.TestUtil;
import water.fvec.Frame;
import water.fvec.FrameTestUtil;
import water.fvec.TestFrameBuilder;
import water.fvec.Vec;
import java.util.ArrayList;
import java.util.Random;
import static org.junit.Assert.*;
import static org.junit.Assert.assertTrue;
/**
* Test FrameUtils interface.
*/
public class FrameUtilsTest extends TestUtil {
@BeforeClass
static public void setup() { stall_till_cloudsize(1); }
@Test
public void testCategoricalColumnsBinaryEncoding() {
int numNoncatColumns = 10;
int[] catSizes = {2, 3, 4, 5, 7, 8, 9, 15, 16, 30, 31, 127, 255, 256};
int[] expBinarySizes = {2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 7, 8, 9};
String[] catNames = {"duo", "Trinity", "Quart", "Star rating", "Dwarves", "Octopus legs", "Planets",
"Game of Fifteen", "Halfbyte", "Days30", "Days31", "Periodic Table", "AlmostByte", "Byte"};
Assert.assertEquals(catSizes.length, expBinarySizes.length);
Assert.assertEquals(catSizes.length, catNames.length);
int totalExpectedColumns = numNoncatColumns;
for (int s : expBinarySizes) totalExpectedColumns += s;
Key<Frame> frameKey = Key.make();
CreateFrame cf = new CreateFrame(frameKey);
cf.rows = 100;
cf.cols = numNoncatColumns;
cf.categorical_fraction = 0.0;
cf.integer_fraction = 0.3;
cf.binary_fraction = 0.1;
cf.time_fraction = 0.2;
cf.string_fraction = 0.1;
Frame mainFrame = cf.execImpl().get();
assert mainFrame != null : "Unable to create a frame";
Frame[] auxFrames = new Frame[catSizes.length];
Frame transformedFrame = null;
try {
for (int i = 0; i < catSizes.length; ++i) {
CreateFrame ccf = new CreateFrame();
ccf.rows = 100;
ccf.cols = 1;
ccf.categorical_fraction = 1;
ccf.integer_fraction = 0;
ccf.binary_fraction = 0;
ccf.time_fraction = 0;
ccf.string_fraction = 0;
ccf.factors = catSizes[i];
auxFrames[i] = ccf.execImpl().get();
auxFrames[i]._names[0] = catNames[i];
mainFrame.add(auxFrames[i]);
}
FrameUtils.CategoricalBinaryEncoder cbed = new FrameUtils.CategoricalBinaryEncoder(mainFrame, null);
transformedFrame = cbed.exec().get();
assert transformedFrame != null : "Unable to transform a frame";
Assert.assertEquals("Wrong number of columns after converting to binary encoding",
totalExpectedColumns, transformedFrame.numCols());
for (int i = 0; i < numNoncatColumns; ++i) {
Assert.assertEquals(mainFrame.name(i), transformedFrame.name(i));
Assert.assertEquals(mainFrame.types()[i], transformedFrame.types()[i]);
}
for (int i = 0, colOffset = numNoncatColumns; i < catSizes.length; colOffset += expBinarySizes[i++]) {
for (int j = 0; j < expBinarySizes[i]; ++j) {
int jj = colOffset + j;
Assert.assertTrue("A categorical column should be transformed into several binary ones (col "+jj+")",
transformedFrame.vec(jj).isBinary());
Assert.assertThat("Transformed categorical column should carry the name of the original column",
transformedFrame.name(jj), CoreMatchers.startsWith(mainFrame.name(numNoncatColumns+i) + ":"));
}
}
} catch (Throwable e) {
e.printStackTrace();
throw e;
} finally {
mainFrame.delete();
if (transformedFrame != null) transformedFrame.delete();
for (Frame f : auxFrames)
if (f != null)
f.delete();
}
}
@Test
public void testOneHotExplicitEncoder() {
Scope.enter();
try {
Frame f = new TestFrameBuilder()
.withName("testFrame")
.withColNames("NumCol", "CatCol1", "CatCol2")
.withVecTypes(Vec.T_NUM, Vec.T_CAT, Vec.T_CAT)
.withDataForCol(0, ard(Double.NaN, 1, 2, 3, 4, 5.6, 7))
.withDataForCol(1, ar("A", "B", "C", "E", "F", "I", "J"))
.withDataForCol(2, ar("A", "B", "A", "C", null, "B", "A"))
.withChunkLayout(2, 2, 2, 1)
.build();
Frame result = FrameUtils.categoricalEncoder(f, new String[]{"CatCol1"},
Model.Parameters.CategoricalEncodingScheme.OneHotExplicit, null, -1);
Scope.track(result);
assertArrayEquals(
new String[]{"NumCol", "CatCol2.A", "CatCol2.B", "CatCol2.C", "CatCol2.missing(NA)", "CatCol1"},
result.names());
// check that original columns are the same
assertVecEquals(f.vec("NumCol"), result.vec("NumCol"), 1e-6);
assertCatVecEquals(f.vec("CatCol1"), result.vec("CatCol1"));
// validate 1-hot encoding
Vec catVec = f.vec("CatCol2");
for (long i = 0; i < catVec.length(); i++) {
String hotCol = "CatCol2." + (catVec.isNA(i) ? "missing(NA)" : catVec.domain()[(int) catVec.at8(i)]);
for (String col : result.names())
if (col.startsWith("CatCol2.")) {
long expectedVal = hotCol.equals(col) ? 1 : 0;
assertEquals("Value of column " + col + " in row = " + i + " matches", expectedVal, result.vec(col).at8(i));
}
}
} finally {
Scope.exit();
}
}
// This test is used to test some utilities that I have written to make sure they function as planned.
@Test
public void testIDColumnOperationEncoder() {
Scope.enter();
Random _rand = new Random();
int numRows = 1000;
int rowsToTest = _rand.nextInt(numRows);
try {
FrameTestUtil.Create1IDColumn tempO = new FrameTestUtil.Create1IDColumn(numRows);
Frame f = tempO.doAll(tempO.returnFrame()).returnFrame();
Scope.track(f);
ArrayList<Integer> badRows = new FrameTestUtil.CountAllRowsPresented(0, f).doAll(f).findMissingRows();
assertEquals("All rows should be present but not!", badRows.size(), 0);
long countAppear = new FrameTestUtil.CountIntValueRows(rowsToTest, 0,
0, f).doAll(f).getNumberAppear();
assertEquals("All values should appear only once.", countAppear, 1);
// delete a row to make sure it is not found again.
f.remove(rowsToTest); // row containing value rowsToTest is no longer there.
countAppear = new FrameTestUtil.CountIntValueRows(2000, 0, 0,
f).doAll(f).getNumberAppear();
assertEquals("Value of interest should not been found....", countAppear, 0);
} finally {
Scope.exit();
}
}
@Test
public void getColumnIndexByName() {
Scope.enter();
try {
Frame fr = new TestFrameBuilder()
.withName("testFrame")
.withColNames("ColA", "ColB")
.withVecTypes(Vec.T_CAT, Vec.T_NUM)
.withDataForCol(0, ar("a", "b"))
.withDataForCol(1, ard(1, 1))
.build();
Scope.track(fr);
assertEquals(0, fr.find("ColA"));
assertEquals(1, fr.find("ColB"));
} finally {
Scope.exit();
}
}
@Test
public void testEnumLimitedEncoding() {
Scope.enter();
try {
Frame fr = parse_test_file("./smalldata/prostate/prostate.csv");
Scope.track(fr);
fr.toCategoricalCol("AGE");
Frame enc = FrameUtils.categoricalEncoder(
fr, new String[]{}, Model.Parameters.CategoricalEncodingScheme.EnumLimited, null, 5);
Scope.track(enc);
assertArrayEquals(new String[] {"70", "68", "65", "71", "66", "other"}, enc.vec("AGE.top_5_levels").domain());
} finally {
Scope.exit();
}
}
// I want to test and make sure the CalculateWeightMeanSTD will calculate the correct weighted mean and STD
// for a column of a dataset using another column as the weight column. Note that the weighted
@Test
public void testCalculateWeightMeanSTD() {
Scope.enter();
try {
Frame trainData = parse_test_file("smalldata/prostate/prostate.csv");
Scope.track(trainData);
Vec orig = trainData.remove(trainData.numCols() - 1);
Vec[] weights = new Vec[2];
weights[0] = orig.makeCon(2.0); // constant weight, should give same answer as normal
weights[1] = orig.makeCon(1.0); // increasing weights
for (int rindex = 0; rindex < orig.length(); rindex++) {
weights[1].set(rindex, rindex + 1);
}
Scope.track(orig);
Scope.track(weights[0]);
Scope.track(weights[1]);
Frame test = new Frame(new String[]{"weight0", "weight1"},weights);
test._key = Key.make();
Scope.track(test);
FrameUtils.CalculateWeightMeanSTD calMeansSTDW1 = new FrameUtils.CalculateWeightMeanSTD();
calMeansSTDW1.doAll(trainData.vec(0), test.vec(0)); // calculate statistic with constant weight
// compare with results with no weights, should be the same
assert Math.abs(trainData.vec(0).mean()-calMeansSTDW1.getWeightedMean())<1e-10:"Error, weighted mean "+
calMeansSTDW1.getWeightedMean()+ " and expected mean "+trainData.vec(0).mean()+" should equal but not.";
assert Math.abs(trainData.vec(0).sigma()-calMeansSTDW1.getWeightedSigma())<1e-10:"Error, weighted sigma "+
calMeansSTDW1.getWeightedSigma()+ " and expected sigma "+trainData.vec(0).sigma()+" should equal but not.";
FrameUtils.CalculateWeightMeanSTD calMeansSTDW2 = new FrameUtils.CalculateWeightMeanSTD();
calMeansSTDW2.doAll(trainData.vec(0), test.vec(1)); // calculate statistic with increasing weight
double[] meanSigma = calWeightedMeanSigma(trainData, test,0, 1);
assert Math.abs(meanSigma[0]-calMeansSTDW2.getWeightedMean())<1e-10:"Error, weighted mean "+
calMeansSTDW1.getWeightedMean()+ " and expected mean "+meanSigma[0]+" should equal but not.";
assert Math.abs(meanSigma[1]-calMeansSTDW2.getWeightedSigma())<1e-10:"Error, weighted sigma "+
calMeansSTDW1.getWeightedSigma()+ " and expected sigma "+meanSigma[1]+" should equal but not.";
} finally {
Scope.exit();
}
}
/*
calculate weighted mean and sigma from theory.
*/
public double[] calWeightedMeanSigma(Frame dataFrame,Frame weightF, int targetIndex, int WeightIndex) {
double[] meanSigma = new double[2];
int zeroWeightCount = 0;
double weightSum = 0.0;
double weightEleSum = 0.0;
double weightedEleSqSum = 0.0;
for (int rindex=0; rindex < dataFrame.numRows(); rindex++) {
double tempWeight = weightF.vec(WeightIndex).at(rindex);
if (Math.abs(tempWeight) > 0) {
double tempVal = dataFrame.vec(targetIndex).at(rindex);
double weightedtempVal = tempVal*tempWeight;
weightSum += tempWeight;
weightEleSum += weightedtempVal;
weightedEleSqSum += weightedtempVal*tempVal;
} else {
zeroWeightCount++;
}
}
meanSigma[0] = weightEleSum/weightSum;
double scale = (dataFrame.numRows()-zeroWeightCount)/(dataFrame.numRows()-zeroWeightCount-1.0);
meanSigma[1] = Math.sqrt(scale*(weightedEleSqSum/weightSum-meanSigma[0]*meanSigma[0]));
return meanSigma;
}
}
|
/**
* You are given two linked lists representing two non-negative numbers. The
* digits are stored in reverse order and each of their nodes contain a single
* digit. Add the two numbers and return it as a linked list.
*
* Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
* Output: 7 -> 0 -> 8
*
* Tags: Linkedlist, Math
*/
class AddTwoNum {
public static void main(String[] args) {
}
/**
* Create a dummy head pointer
* Build list node one by one
* Use sum to track the current sum of nodes, or node
* Reset sum using sum /= 10
* Note whether there is carry for last digit
*/
public ListNdoe addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode dummy = new ListNode(0); // set dummy head
ListNode d = dummy; //digit
int sum = 0; // the sum of two nodes
while (c1 != null || c2 != null) { // traverse longer list
if (c1 != null) { // add one list
sum += c1.val;
c1 = c1.next; // move on
}
if (c2 != null) { // add another list
sum += c2.val;
c2 = c2.next; // move on
}
// build next node
d.next = new ListNode(sum % 10); // digit for current node
sum /= 10; // carry
d = d.next;
}
if (sum == 1) d.next = new ListNode(1); // note that can have carry at the last digit
return dummy.next;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}
|
package com.dgrid.util.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.channels.FileChannel;
public class OutputStreamUtils {
public static final int DEFAULT_BUFFER_SIZE = 1024;
public static void writeStringToFile(String content, File dest)
throws IOException {
FileOutputStream fos = new FileOutputStream(dest);
PrintStream ps = new PrintStream(fos);
ps.print(content);
ps.close();
fos.close();
}
public static void writeStreamToStream(InputStream in, OutputStream out)
throws IOException {
writeStreamToStream(in, out, DEFAULT_BUFFER_SIZE);
}
public static void writeStreamToStream(InputStream in, OutputStream out,
int bufferSize) throws IOException {
int read = 0;
byte[] buffer = new byte[bufferSize];
while ((read = in.read(buffer)) > 0) {
out.write(buffer, 0, read);
}
}
public static void writeStreamToFile(InputStream in, File dest)
throws IOException {
FileOutputStream fos = new FileOutputStream(dest);
writeStreamToStream(in, fos);
fos.close();
}
public static void copyFile(File source, File dest) throws IOException {
FileChannel ic = new FileInputStream(source).getChannel();
FileChannel oc = new FileOutputStream(dest).getChannel();
ic.transferTo(0, ic.size(), oc);
ic.close();
oc.close();
}
}
|
package javaslang.collection;
import javaslang.*;
import javaslang.control.Option;
import java.util.*;
import java.util.function.*;
/**
* An immutable {@code Map} interface.
*
* @param <K> Key type
* @param <V> Value type
* @author Daniel Dietrich, Ruslan Sennov
* @since 2.0.0
*/
public interface Map<K, V> extends Traversable<Tuple2<K, V>>, Function1<K, V> {
long serialVersionUID = 1L;
/**
* Narrows a widened {@code Map<? extends K, ? extends V>} to {@code Map<K, V>}
* by performing a type safe-cast. This is eligible because immutable/read-only
* collections are covariant.
*
* @param map A {@code Map}.
* @param <K> Key type
* @param <V> Value type
* @return the given {@code map} instance as narrowed type {@code Map<K, V>}.
*/
@SuppressWarnings("unchecked")
static <K, V> Map<K, V> narrow(Map<? extends K, ? extends V> map) {
return (Map<K, V>) map;
}
/**
* Convenience factory method to create a key/value pair.
* <p>
* If imported statically, this method allows to create a {@link Map} with arbitrary entries in a readable and
* type-safe way, e.g.:
* <pre>
* {@code
*
* HashMap.ofEntries(
* entry(k1, v1),
* entry(k2, v2),
* entry(k3, v3)
* );
*
* }
* </pre>
*
* @param key the entry's key
* @param value the entry's value
* @param <K> Key type
* @param <V> Value type
* @return a key/value pair
*/
static <K, V> Tuple2<K, V> entry(K key, V value) {
return Tuple.of(key, value);
}
@Override
default V apply(K key) {
return get(key).getOrElseThrow(NoSuchElementException::new);
}
/**
* Maps this {@code Map} to a new {@code Map} with different component type by applying a function to its elements.
*
* @param <K2> key's component type of the map result
* @param <V2> value's component type of the map result
* @param keyMapper a {@code Function} that maps the keys of type {@code K} to keys of type {@code K2}
* @param valueMapper a {@code Function} that the values of type {@code V} to values of type {@code V2}
* @return a new {@code Map}
* @throws NullPointerException if {@code keyMapper} or {@code valueMapper} is null
*/
<K2, V2> Map<K2, V2> bimap(Function<? super K, ? extends K2> keyMapper, Function<? super V, ? extends V2> valueMapper);
/**
* Returns <code>true</code> if this map contains a mapping for the specified key.
*
* @param key key whose presence in this map is to be tested
* @return <code>true</code> if this map contains a mapping for the specified key
*/
boolean containsKey(K key);
/**
* Returns <code>true</code> if this map maps one or more keys to the
* specified value. This operation will require time linear in the map size.
*
* @param value value whose presence in this map is to be tested
* @return <code>true</code> if this map maps one or more keys to the
* specified value
*/
default boolean containsValue(V value) {
return iterator().map(Tuple2::_2).contains(value);
}
/**
* FlatMaps this {@code Map} to a new {@code Map} with different component type.
*
* @param mapper A mapper
* @param <K2> key's component type of the mapped {@code Map}
* @param <V2> value's component type of the mapped {@code Map}
* @return A new {@code Map}.
* @throws NullPointerException if {@code mapper} is null
*/
<K2, V2> Map<K2, V2> flatMap(BiFunction<? super K, ? super V, ? extends Iterable<Tuple2<K2, V2>>> mapper);
/**
* Returns the {@code Some} of value to which the specified key
* is mapped, or {@code None} if this map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the {@code Some} of value to which the specified key
* is mapped, or {@code None} if this map contains no mapping
* for the key
*/
Option<V> get(K key);
/**
* Returns the keys contained in this map.
*
* @return {@code Set} of the keys contained in this map.
*/
Set<K> keySet();
/**
* Maps the entries of this {@code Map} to form a new {@code Map}.
*
* @param <K2> key's component type of the map result
* @param <V2> value's component type of the map result
* @param mapper a {@code Function} that maps entries of type {@code (K, V)} to entries of type {@code (K2, V2)}
* @return a new {@code Map}
* @throws NullPointerException if {@code mapper} is null
*/
<K2, V2> Map<K2, V2> map(BiFunction<? super K, ? super V, Tuple2<K2, V2>> mapper);
/**
* Maps the keys of this {@code Map} while preserving the corresponding values.
* If {@code keyMapper} will return not unique values for keys, result map will lost some values which will be mapped to same key.
*
* @param <K2> the new key type
* @param keyMapper a {@code Function} that maps keys of type {@code V} to keys of type {@code V2}
* @return a new {@code Map}
* @throws NullPointerException if {@code keyMapper} is null
*/
<K2> Map<K2, V> mapKeys(Function<? super K, ? extends K2> keyMapper);
/**
* Maps the keys of this {@code Map} while preserving the corresponding values.
* <p>
* The size of the result map may be smaller if {@code keyMapper} maps two or more distinct keys to the same new key.
* In this case the associated values will be combined using {@code valueMerge}.
*
* @param <K2> the new key type
* @param keyMapper a {@code Function} that maps keys of type {@code V} to keys of type {@code V2}
* @return a new {@code Map}
* @throws NullPointerException if {@code keyMapper} is null
*/
<K2> Map<K2, V> mapKeys(Function<? super K, ? extends K2> keyMapper, Function2<V, V, V> valueMerge);
/**
* Maps the values of this {@code Map} while preserving the corresponding keys.
*
* @param <V2> the new value type
* @param valueMapper a {@code Function} that maps values of type {@code V} to values of type {@code V2}
* @return a new {@code Map}
* @throws NullPointerException if {@code valueMapper} is null
*/
<V2> Map<K, V2> mapValues(Function<? super V, ? extends V2> valueMapper);
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is
* replaced by the specified value.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return A new Map containing these elements and that entry.
*/
Map<K, V> put(K key, V value);
/**
* Convenience method for {@code put(entry._1, entry._2)}.
*
* @param entry A Tuple2 containing the key and value
* @return A new Map containing these elements and that entry.
*/
Map<K, V> put(Tuple2<? extends K, ? extends V> entry);
/**
* Removes the mapping for a key from this map if it is present.
*
* @param key key whose mapping is to be removed from the map
* @return A new Map containing these elements without the entry
* specified by that key.
*/
Map<K, V> remove(K key);
/**
* Removes the mapping for a key from this map if it is present.
*
* @param keys keys are to be removed from the map
* @return A new Map containing these elements without the entries
* specified by that keys.
*/
Map<K, V> removeAll(Iterable<? extends K> keys);
@Override
int size();
/**
* Converts this Javaslang {@code Map} to a {@code java.util.Map} while preserving characteristics
* like insertion order ({@code LinkedHashMap}) and sort order ({@code SortedMap}).
*
* @return a new {@code java.util.Map} instance
*/
java.util.Map<K, V> toJavaMap();
/**
* Transforms this {@code Map}.
*
* @param f A transformation
* @param <U> Type of transformation result
* @return An instance of type {@code U}
* @throws NullPointerException if {@code f} is null
*/
default <U> U transform(Function<? super Map<K, V>, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return f.apply(this);
}
default <U> Seq<U> traverse(BiFunction<K, V, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
return foldLeft(List.empty(), (acc, entry) -> acc.append(mapper.apply(entry._1, entry._2)));
}
default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(BiFunction<? super K, ? super V, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return unzip(entry -> unzipper.apply(entry._1, entry._2));
}
default <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3(BiFunction<? super K, ? super V, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return unzip3(entry -> unzipper.apply(entry._1, entry._2));
}
Seq<V> values();
// -- Adjusted return types of Traversable methods
@Override
default boolean contains(Tuple2<K, V> element) {
return get(element._1).map(v -> Objects.equals(v, element._2)).getOrElse(false);
}
@Override
Map<K, V> distinct();
@Override
Map<K, V> distinctBy(Comparator<? super Tuple2<K, V>> comparator);
@Override
<U> Map<K, V> distinctBy(Function<? super Tuple2<K, V>, ? extends U> keyExtractor);
@Override
Map<K, V> drop(long n);
@Override
Map<K, V> dropRight(long n);
@Override
Map<K, V> dropUntil(Predicate<? super Tuple2<K, V>> predicate);
@Override
Map<K, V> dropWhile(Predicate<? super Tuple2<K, V>> predicate);
@Override
Map<K, V> filter(Predicate<? super Tuple2<K, V>> predicate);
/**
* Flat-maps this entries to a sequence of values.
* <p>
* Please use {@link #flatMap(BiFunction)} if the result should be a {@code Map}
*
* @param mapper A mapper
* @param <U> Component type
* @return A sequence of flat-mapped values.
*/
@SuppressWarnings("unchecked")
@Override
default <U> Seq<U> flatMap(Function<? super Tuple2<K, V>, ? extends Iterable<? extends U>> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
// don't remove cast, doesn't compile in Eclipse without it
return (Seq<U>) iterator().flatMap(mapper).toStream();
}
@Override
default <U> U foldRight(U zero, BiFunction<? super Tuple2<K, V>, ? super U, ? extends U> f) {
Objects.requireNonNull(f, "f is null");
return iterator().foldRight(zero, f);
}
@Override
<C> Map<C, ? extends Map<K, V>> groupBy(Function<? super Tuple2<K, V>, ? extends C> classifier);
@Override
Iterator<? extends Map<K, V>> grouped(long size);
@Override
default boolean hasDefiniteSize() {
return true;
}
@Override
Map<K, V> init();
@Override
Option<? extends Map<K, V>> initOption();
@Override
default boolean isTraversableAgain() {
return true;
}
@Override
Iterator<Tuple2<K, V>> iterator();
@Override
default int length() {
return size();
}
/**
* Turns this map into a plain function returning an Option result.
*
* @return a function that takes a key k and returns its value in a Some if found, otherwise a None.
*/
default Function1<K, Option<V>> lift() {
return this::get;
}
/**
* Maps the {@code Map} entries to a sequence of values.
* <p>
* Please use {@link #map(BiFunction)} if the result has to be of type {@code Map}.
*
* @param mapper A mapper
* @param <U> Component type
* @return A sequence of mapped values.
*/
@SuppressWarnings("unchecked")
@Override
default <U> Seq<U> map(Function<? super Tuple2<K, V>, ? extends U> mapper) {
Objects.requireNonNull(mapper, "mapper is null");
// don't remove cast, doesn't compile in Eclipse without it
return (Seq<U>) iterator().map(mapper).toStream();
}
/**
* Creates a new map which by merging the entries of {@code this} map and {@code that} map.
* <p>
* If collisions occur, the value of {@code this} map is taken.
*
* @param that the other map
* @return A merged map
* @throws NullPointerException if that map is null
*/
Map<K, V> merge(Map<? extends K, ? extends V> that);
/**
* Creates a new map which by merging the entries of {@code this} map and {@code that} map.
* <p>
* Uses the specified collision resolution function if two keys are the same.
* The collision resolution function will always take the first argument from <code>this</code> map
* and the second from <code>that</code> map.
*
* @param <U> value type of that Map
* @param that the other map
* @param collisionResolution the collision resolution function
* @return A merged map
* @throws NullPointerException if that map or the given collision resolution function is null
*/
<U extends V> Map<K, V> merge(Map<? extends K, U> that, BiFunction<? super V, ? super U, ? extends V> collisionResolution);
@Override
Tuple2<? extends Map<K, V>, ? extends Map<K, V>> partition(Predicate<? super Tuple2<K, V>> predicate);
@Override
Map<K, V> peek(Consumer<? super Tuple2<K, V>> action);
@Override
Map<K, V> replace(Tuple2<K, V> currentElement, Tuple2<K, V> newElement);
@Override
Map<K, V> replaceAll(Tuple2<K, V> currentElement, Tuple2<K, V> newElement);
@Override
Map<K, V> retainAll(Iterable<? extends Tuple2<K, V>> elements);
@Override
Map<K, V> scan(Tuple2<K, V> zero,
BiFunction<? super Tuple2<K, V>, ? super Tuple2<K, V>, ? extends Tuple2<K, V>> operation);
@Override
default <U> Seq<U> scanLeft(U zero, BiFunction<? super U, ? super Tuple2<K, V>, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanLeft(this, zero, operation, List.empty(), List::prepend, List::reverse);
}
@Override
default <U> Seq<U> scanRight(U zero, BiFunction<? super Tuple2<K, V>, ? super U, ? extends U> operation) {
Objects.requireNonNull(operation, "operation is null");
return Collections.scanRight(this, zero, operation, List.empty(), List::prepend, Function.identity());
}
@Override
Iterator<? extends Map<K, V>> sliding(long size);
@Override
Iterator<? extends Map<K, V>> sliding(long size, long step);
@Override
Tuple2<? extends Map<K, V>, ? extends Map<K, V>> span(Predicate<? super Tuple2<K, V>> predicate);
@Override
default Spliterator<Tuple2<K, V>> spliterator() {
return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE);
}
@Override
Map<K, V> tail();
@Override
Option<? extends Map<K, V>> tailOption();
@Override
Map<K, V> take(long n);
@Override
Map<K, V> takeRight(long n);
@Override
Map<K, V> takeUntil(Predicate<? super Tuple2<K, V>> predicate);
@Override
Map<K, V> takeWhile(Predicate<? super Tuple2<K, V>> predicate);
@Override
default <T1, T2> Tuple2<Seq<T1>, Seq<T2>> unzip(Function<? super Tuple2<K, V>, Tuple2<? extends T1, ? extends T2>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return iterator().unzip(unzipper).map(Stream::ofAll, Stream::ofAll);
}
@Override
default <T1, T2, T3> Tuple3<Seq<T1>, Seq<T2>, Seq<T3>> unzip3(
Function<? super Tuple2<K, V>, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) {
Objects.requireNonNull(unzipper, "unzipper is null");
return iterator().unzip3(unzipper).map(Stream::ofAll, Stream::ofAll, Stream::ofAll);
}
@Override
default <U> Seq<Tuple2<Tuple2<K, V>, U>> zip(Iterable<? extends U> that) {
Objects.requireNonNull(that, "that is null");
return Stream.ofAll(iterator().zip(that));
}
@Override
default <U> Seq<Tuple2<Tuple2<K, V>, U>> zipAll(Iterable<? extends U> that, Tuple2<K, V> thisElem, U thatElem) {
Objects.requireNonNull(that, "that is null");
return Stream.ofAll(iterator().zipAll(that, thisElem, thatElem));
}
@Override
default Seq<Tuple2<Tuple2<K, V>, Long>> zipWithIndex() {
return Stream.ofAll(iterator().zipWithIndex());
}
/**
* Performs an action on key, value pair.
*
* @param action A {@code BiConsumer}
* @throws NullPointerException if {@code action} is null
*/
default void forEach(BiConsumer<K, V> action) {
Objects.requireNonNull(action, "action is null");
for (Tuple2<K, V> t : this) {
action.accept(t._1, t._2);
}
}
/**
* Turns this map from a partial function into a total function that
* returns defaultValue for all keys absent from the map.
*
* @param defaultValue default value to return for all keys not present in the map
* @return a total function from K to T
*/
default Function1<K, V> withDefaultValue(V defaultValue) {
return k -> get(k).getOrElse(defaultValue);
}
/**
* Turns this map from a partial function into a total function that
* returns a value computed by defaultFunction for all keys
* absent from the map.
*
* @param defaultFunction function to evaluate for all keys not present in the map
* @return a total function from K to T
*/
default Function1<K, V> withDefault(Function<? super K, ? extends V> defaultFunction) {
return k -> get(k).getOrElse(() -> defaultFunction.apply(k));
}
}
|
package javaslang;
import org.junit.Test;
import java.math.BigDecimal;
import java.util.function.Predicate;
import static javaslang.Predicates.*;
import static org.assertj.core.api.Assertions.assertThat;
public class PredicatesTest {
static final Predicate<? super Throwable> IS_RUNTIME_EXCEPTION = instanceOf(RuntimeException.class);
// -- instanceOf
@Test
public void shouldTestInstanceOf_PositiveCase() {
assertThat(instanceOf(Number.class).test(1)).isTrue();
assertThat(instanceOf(Number.class).test(new BigDecimal("1"))).isTrue();
assertThat(IS_RUNTIME_EXCEPTION.test(new NullPointerException())).isTrue();
}
@Test
public void shouldTestInstanceOf_NegativeCase() {
assertThat(IS_RUNTIME_EXCEPTION.test(new Exception())).isFalse();
assertThat(IS_RUNTIME_EXCEPTION.test(new Error("error"))).isFalse();
}
@Test
public void shouldTestIs_PositiveCase() {
assertThat(is(1).test(1)).isTrue();
assertThat(is((CharSequence) "1").test("1")).isTrue();
}
@Test
public void shouldTestIs_NegativeCase() {
assertThat(is(1).test(2)).isFalse();
assertThat(is((CharSequence) "1").test(new StringBuilder("1"))).isFalse();
}
// -- isIn
@Test
public void shouldTestIsIn_PositiveCase() {
assertThat(isIn(1, 2, 3).test(2)).isTrue();
assertThat(isIn((CharSequence) "1", "2", "3").test("2")).isTrue();
}
@Test
public void shouldTestIsIn_NegativeCase() {
assertThat(isIn(1, 2, 3).test(4)).isFalse();
assertThat(isIn((CharSequence) "1", "2", "3").test("4")).isFalse();
}
// Predicate Combinators
// -- allOf
static final Predicate<Integer> P1 = i -> i > 1;
static final Predicate<? super Integer> P2 = i -> i > 2;
@Test
public void shouldTestAllOf_PositiveCase() {
assertThat(allOf().test(1)).isTrue();
assertThat(allOf(P1, P2).test(3)).isTrue();
}
@Test
public void shouldTestAllOf_NegativeCase() {
assertThat(allOf(P1, P2).test(2)).isFalse();
}
// -- anyOf
@Test
public void shouldTestAnyOf_PositiveCase() {
assertThat(anyOf(P1, P2).test(3)).isTrue();
assertThat(anyOf(P1, P2).test(2)).isTrue();
}
@Test
public void shouldTestAnyOf_NegativeCase() {
assertThat(anyOf().test(1)).isFalse();
assertThat(anyOf(P1, P2).test(1)).isFalse();
}
// -- noneOf
@Test
public void shouldTestNoneOf_PositiveCase() {
assertThat(noneOf().test(1)).isTrue();
assertThat(noneOf(P1, P2).test(1)).isTrue();
}
@Test
public void shouldTestNoneOf_NegativeCase() {
assertThat(noneOf(P1).test(2)).isFalse();
assertThat(noneOf(P1, P2).test(2)).isFalse();
}
}
|
package org.ccnx.ccn.utils.explorer;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
import org.ccnx.ccn.io.content.Link;
import org.ccnx.ccn.profiles.security.access.group.ACL;
import org.ccnx.ccn.profiles.security.access.group.ACL.ACLOperation;
import org.ccnx.ccn.protocol.ContentName;
public class ACLTable extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"Principals", "Read", "Write", "Manage"};
private int ACL_LENGTH = 3;
private ContentName[] principals;
private Object[][] aclTable;
private ACL initialACL;
public ACLTable(String type, ContentName[] principals, ACL initialACL) {
columnNames[0] = type;
this.principals = principals;
this.initialACL = initialACL;
initializeACLTable();
}
private void initializeACLTable() {
aclTable = new Object[principals.length][ACL_LENGTH];
for (int c=0; c<ACL_LENGTH; c++) {
for (int r=0; r<principals.length; r++) {
aclTable[r][c] = new Boolean(false);
}
}
for (int i=0; i<initialACL.size(); i++) {
Link lk = (Link) initialACL.get(i);
ContentName principal = lk.targetName();
String role = lk.targetLabel();
this.setRole(principal, role);
}
}
public int getColumnCount() {
return columnNames.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getRowCount() {
return principals.length;
}
public Class getColumnClass(int col) {
return getValueAt(0, col).getClass();
}
public Object getValueAt(int row, int col) {
if (col == 0) {
String friendlyName = ContentName.componentPrintNative(principals[row].lastComponent());
return friendlyName;
}
else if (col < 4) return aclTable[row][col-1];
else return null;
}
public void setValueAt(Object value, int row, int col) {
Boolean v = (Boolean) value;
if (v.equals(Boolean.TRUE)) {
for (int c=0; c<col; c++) {
aclTable[row][c] = v;
fireTableCellUpdated(row, c+1);
}
}
else {
for (int c=col-1; c < ACL_LENGTH; c++) {
aclTable[row][c] = v;
fireTableCellUpdated(row, c+1);
}
}
}
public boolean isCellEditable(int row, int col) {
if (col == 0 ) return false;
else return true;
}
public void cancelChanges() {
initializeACLTable();
fireTableDataChanged();
}
public int getIndexOfPrincipal(ContentName principal) {
int pos = -1;
for (int i=0; i<principals.length; i++) {
if (principal.compareTo(principals[i]) == 0) {
pos = i;
break;
}
}
return pos;
}
public void setRole(ContentName principal, String role) {
int pos = getIndexOfPrincipal(principal);
if (pos > -1) {
if (role.equals(ACL.LABEL_READER)) {
aclTable[pos][0] = new Boolean(true);
aclTable[pos][1] = new Boolean(false);
aclTable[pos][2] = new Boolean(false);
}
if (role.equals(ACL.LABEL_WRITER)) {
aclTable[pos][0] = new Boolean (true);
aclTable[pos][1] = new Boolean(true);
aclTable[pos][2] = new Boolean(false);
}
if (role.equals(ACL.LABEL_MANAGER)) {
aclTable[pos][0] = new Boolean (true);
aclTable[pos][1] = new Boolean(true);
aclTable[pos][2] = new Boolean(true);
}
}
else {
String friendlyName = ContentName.componentPrintNative(principal.lastComponent());
System.out.println("WARNING: principal name " + friendlyName + " in ACL not a known principal in this table");
}
}
public String getRole(ContentName principal) {
String role = null;
int pos = getIndexOfPrincipal(principal);
if (pos > -1) {
if ((Boolean) aclTable[pos][2]) role = ACL.LABEL_MANAGER;
else if ((Boolean) aclTable[pos][1]) role = ACL.LABEL_WRITER;
else if ((Boolean) aclTable[pos][0]) role = ACL.LABEL_READER;
}
return role;
}
public ArrayList<ACLOperation> computeACLUpdates() {
ArrayList<ACLOperation> ACLUpdates = new ArrayList<ACLOperation>();
for (int i=0; i<principals.length; i++) {
ContentName principal = principals[i];
Link plk = new Link(principal);
// get initial role
String initialRole = null;
for (int j=0; j<initialACL.size(); j++) {
Link lk = (Link) initialACL.get(j);
if (principal.compareTo(lk.targetName()) == 0) {
initialRole = lk.targetLabel();
}
}
// get final role
String finalRole = getRole(principal);
// compare initial and final role
if (initialRole == null) {
if (finalRole == null) continue;
if (finalRole.equals(ACL.LABEL_READER)) ACLUpdates.add(ACLOperation.addReaderOperation(plk));
else if (finalRole.equals(ACL.LABEL_WRITER)) ACLUpdates.add(ACLOperation.addWriterOperation(plk));
else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
}
else if (initialRole.equals(ACL.LABEL_READER)) {
if (finalRole == null) ACLUpdates.add(ACLOperation.removeReaderOperation(plk));
else if (finalRole.equals(ACL.LABEL_WRITER)) ACLUpdates.add(ACLOperation.addWriterOperation(plk));
else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
}
else if (initialRole.equals(ACL.LABEL_WRITER)) {
if (finalRole == null) ACLUpdates.add(ACLOperation.removeWriterOperation(plk));
else if (finalRole.equals(ACL.LABEL_READER)) {
ACLUpdates.add(ACLOperation.removeWriterOperation(plk));
ACLUpdates.add(ACLOperation.addReaderOperation(plk));
}
else if (finalRole.equals(ACL.LABEL_MANAGER)) ACLUpdates.add(ACLOperation.addManagerOperation(plk));
}
else if (initialRole.equals(ACL.LABEL_MANAGER)) {
if (finalRole == null) ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
else if (finalRole.equals(ACL.LABEL_READER)) {
ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
ACLUpdates.add(ACLOperation.addReaderOperation(plk));
}
else if (finalRole.equals(ACL.LABEL_WRITER)) {
ACLUpdates.add(ACLOperation.removeManagerOperation(plk));
ACLUpdates.add(ACLOperation.addWriterOperation(plk));
}
}
}
return ACLUpdates;
}
}
|
package org.javers.core;
import org.javers.common.collections.Optional;
import org.javers.core.changelog.ChangeProcessor;
import org.javers.core.commit.Commit;
import org.javers.core.commit.CommitMetadata;
import org.javers.core.diff.Change;
import org.javers.core.diff.Diff;
import org.javers.core.diff.changetype.NewObject;
import org.javers.core.diff.changetype.ReferenceChange;
import org.javers.core.diff.changetype.ValueChange;
import org.javers.core.diff.changetype.container.ListChange;
import org.javers.core.json.JsonConverter;
import org.javers.core.metamodel.object.CdoSnapshot;
import org.javers.core.metamodel.object.GlobalId;
import org.javers.repository.jql.GlobalIdDTO;
import org.javers.repository.jql.JqlQuery;
import java.util.List;
public interface Javers {
Commit commit(String author, Object currentVersion);
/**
* Marks given object as deleted.
* <br/><br/>
*
* Unlike {@link Javers#commit(String, Object)}, this method is shallow
* and affects only given object.
* <br/><br/>
*
* This method doesn't delete anything from JaVers repository.
* It just persists 'terminal snapshot' of given object.
*
* @param deleted object to be marked as deleted
*/
Commit commitShallowDelete(String author, Object deleted);
/**
* The same like {@link #commitShallowDelete(String,Object)}
* but deleted object is selected using globalId
*/
Commit commitShallowDeleteById(String author, GlobalIdDTO globalId);
Diff compare(Object oldVersion, Object currentVersion);
/**
* Initial diff is a kind of snapshot of given domain object graph.
* Use it alongside with {@link #compare(Object, Object)}
*/
Diff initial(Object newDomainObject);
List<Change> findChanges(JqlQuery query);
List<CdoSnapshot> findSnapshots(JqlQuery query);
/**
* Latest snapshot of given entity instance
* or Optional#EMPTY if instance is not versioned.
* <br/><br/>
*
* For example, to get last snapshot of "bob" Person, call:
* <pre>
* javers.getLatestSnapshot("bob", Person.class));
* </pre>
*/
Optional<CdoSnapshot> getLatestSnapshot(Object localId, Class entityClass);
/**
* If you are serializing JaVers objects like
* {@link Commit}, {@link Change}, {@link Diff} or {@link CdoSnapshot} to JSON, use this JsonConverter.
* For example:
*
* <pre>
* javers.getJsonConverter().toJson(changes);
* </pre>
*/
JsonConverter getJsonConverter();
/**
* Generic purpose method for processing a changes list.
* After iterating over given list, returns data computed by
* {@link org.javers.core.changelog.ChangeProcessor#result()}.
* <br/>
* It's more convenient than iterating over changes on your own.
* ChangeProcessor frees you from <tt>if + inctanceof</tt> boilerplate.
*
* <br/><br/>
* Additional features: <br/>
* - when several changes in a row refers to the same Commit, {@link ChangeProcessor#onCommit(CommitMetadata)}
* is called only for first occurrence <br/>
* - similarly, when several changes in a row affects the same object, {@link ChangeProcessor#onAffectedObject(GlobalId)}
* is called only for first occurrence
*
* <br/><br/>
* For example, to get pretty change log, call:
* <pre>
* List<Change> changes = javers.calculateDiffs(...);
* String changeLog = javers.processChangeList(changes, new SimpleTextChangeLog());
* System.out.println( changeLog );
* </pre>
*
* @see org.javers.core.changelog.SimpleTextChangeLog
*/
<T> T processChangeList(List<Change> changes, ChangeProcessor<T> changeProcessor);
/**
* use: <pre>
* javers.getJsonConverter().toJson(diff);
* </pre>
*/
@Deprecated
String toJson(Diff diff);
/**
* use {@link #findSnapshots(JqlQuery)}
*/
@Deprecated
List<CdoSnapshot> getStateHistory(GlobalIdDTO globalId, int limit);
/**
* use {@link #findChanges(JqlQuery)}
*/
@Deprecated
List<Change> getChangeHistory(GlobalIdDTO globalId, int limit);
/**
* use {@link #getLatestSnapshot(Object, Class)}
*/
@Deprecated
Optional<CdoSnapshot> getLatestSnapshot(GlobalIdDTO globalId);
IdBuilder idBuilder();
}
|
package com.jenjinstudios.jgsf;
import com.jenjinstudios.message.MessageRegistry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The base Server class for implementation of the JGSA. It contains extensible execution functionality designed to be
* used by Executable Messages from ClientHandlers.
* @author Caleb Brinkman
*/
@SuppressWarnings("SameParameterValue")
public class Server<T extends ClientHandler> extends Thread
{
/** The default number of max clients. */
public static final int DEFAULT_MAX_CLIENTS = 100;
/** The logger used by this class. */
static final Logger LOGGER = Logger.getLogger(Server.class.getName());
/** The updates per second. */
public final int UPS;
/** The period of the update in milliseconds. */
public final int PERIOD;
/** The list of {@code ClientListener}s working for this server. */
private final ClientListener<T> clientListener;
/** The list of {@code ClientHandler}s working for this server. */
private final ArrayList<T> clientHandlers;
/** The map of clients stored by username. */
private final TreeMap<String, T> clientsByUsername;
/** Indicates whether this server is initialized. */
private volatile boolean initialized;
/** The current number of connected clients. */
private int numClients;
/**
* Construct a new Server without a SQLHandler.
* @param ups The cycles per second at which this server will run.
* @param port The port number on which this server will listen.
* @param handlerClass The class of ClientHandler used by this Server.
* @throws java.io.IOException If there is an IO Error initializing the server.
*/
public Server(int ups, int port, Class<? extends T> handlerClass) throws IOException {
this(ups, port, handlerClass, DEFAULT_MAX_CLIENTS);
}
/**
* Construct a new Server without a SQLHandler.
* @param ups The cycles per second at which this server will run.
* @param port The port number on which this server will listen.
* @param handlerClass The class of ClientHandler used by this Server.
* @param maxClients The maximum number of clients.
* @throws java.io.IOException If there is an IO Error initializing the server.
*/
public Server(int ups, int port, Class<? extends T> handlerClass, int maxClients) throws IOException {
super("Server");
LOGGER.log(Level.FINE, "Initializing Server.");
UPS = ups;
PERIOD = 1000 / ups;
clientsByUsername = new TreeMap<>();
clientListener = (ClientListener<T>) new ClientListener<>(this, port, handlerClass);
clientHandlers = new ArrayList<>();
for (int i = 0; i < maxClients; i++)
clientHandlers.add(null);
numClients = 0;
MessageRegistry.registerXmlMessages();
}
/**
* Schedule a client to be removed during the next update.
* @param handler The client handler to be removed.
*/
void removeClient(ClientHandler handler) {
synchronized (clientHandlers)
{
String username = handler.getUsername();
if (username != null) { clientsByUsername.remove(username); }
clientHandlers.set(handler.getHandlerId(), null);
numClients
}
}
/**
* Add new clients that have connected to the client listeners.
* @return true if new clients were added.
*/
public boolean getNewClients() {
boolean clientsAdded;
LinkedList<T> nc = clientListener.getNewClients();
clientsAdded = !nc.isEmpty();
for (T h : nc)
{
int nullIndex = clientHandlers.indexOf(null);
clientHandlers.set(nullIndex, h);
h.setID(nullIndex);
h.start();
numClients++;
}
return clientsAdded;
}
/** Broadcast all outgoing messages to clients. */
public void broadcast() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.sendAllMessages(); }
}
}
}
/** Update all clients before they sendAllMessages. */
public void update() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.update(); }
}
}
}
/** Refresh all clients after they sendAllMessages. */
public void refresh() {
synchronized (clientHandlers)
{
for (ClientHandler current : clientHandlers)
{
if (current != null) { current.refresh(); }
}
}
}
/** Run the server. */
@Override
public void run() {
clientListener.listen();
initialized = true;
}
/** Start the server, and do not return until it is fully initialized. */
public final void blockingStart() {
start();
// TODO Add timeout here.
while (!initialized) try
{
Thread.sleep(1);
} catch (InterruptedException e)
{
LOGGER.log(Level.WARNING, "Issue with server blockingStart", e);
}
}
/**
* Shutdown the server, forcing all client links to close.
* @throws IOException if there is an error shutting down a client.
*/
public void shutdown() throws IOException {
synchronized (clientHandlers)
{
for (ClientHandler h : clientHandlers)
{
if (h != null) { h.shutdown(); }
}
}
clientListener.stopListening();
}
/**
* Return whether this server is initialized.
* @return true if the server has been initialized.
*/
public boolean isInitialized() { return initialized; }
/**
* Get the ClientHandler with the given username.
* @param username The username of the client to look up.
* @return The client with the username specified; null if there is no client with this username.
*/
public T getClientHandlerByUsername(String username) { return clientsByUsername.get(username); }
/**
* Called by ClientHandler when the client sets a username.
* @param username The username assigned to the ClientHandler.
* @param handler The ClientHandler that has had a username set.
*/
@SuppressWarnings("unchecked")
void clientUsernameSet(String username, ClientHandler handler) { clientsByUsername.put(username, (T) handler); }
/**
* Get the current number of connected clients.
* @return The current number of connected clients.
*/
public int getNumClients() {
return numClients;
}
}
|
package ads;
/**
*
* A simple implementation of a binary search tree.
*
* @author Andrzej Ruszczewski
*
*/
public class BinaryTree {
TreeNode root;
/**
*
* Basic insertion method which inserts into root if null, or calls the
* recursive method otherwise. This is the method that should be called to
* insert a value into the tree.
*
* @param value
* the data to insert
*
*/
public void insert(int value) {
if (root == null) {
root = new TreeNode();
root.data = value;
} else {
insertNode(value, root);
}
}
/**
*
* Recursive insertion method for inserting deeper than the root.
*
* @param value
* @param current
*
*/
private void insertNode(int value, TreeNode current) {
if (value < current.data) {
if (current.left == null) {
current.left = new TreeNode();
current.left.data = value;
} else {
insertNode(value, current.left);
}
} else {
if (current.right == null) {
current.right = new TreeNode();
current.right.data = value;
} else {
insertNode(value, current.right);
}
}
}
/**
* Checks if a given value is contained in the tree.
*
* @param value
* the value to search for in the tree
* @return True if the value is contained in the tree, false otherwise.
*/
public boolean contains(int value) {
if (findNode(value) != null) {
return true;
} else {
return false;
}
}
/**
* Main recursive search method. Deprecated. ;) Used to be used by contains
* method.
*
* @param value
* @param current
* @return
*/
private boolean containsRecursion(int value, TreeNode current) {
if (current == null) {
return false;
} else if (current.data == value) {
return true;
} else {
if (value > current.data) {
return containsRecursion(value, current.right);
} else {
return containsRecursion(value, current.left);
}
}
}
/**
* Recursively finds a reference to the node containing the given value.
*
* @param value
* Data of the node to find.
* @return A reference to the node containing the given value, null if the
* value does not exist in the tree.
*/
public TreeNode findNode(int value) {
return findNodeRecursion(value, root);
}
/**
* Main recursive logic of the findNode method.
*
* @param value
* @param current
* @return
*/
private TreeNode findNodeRecursion(int value, TreeNode current) {
if (current == null) {
return null;
} else if (current.data == value) {
return current;
} else {
if (value > current.data) {
return findNodeRecursion(value, current.right);
} else {
return findNodeRecursion(value, current.left);
}
}
}
/**
* Finds the parent node of the node containing the given value.
*
* @param value
* Parent of the node containing this value will be returned.
* @return Reference to the parent node, null if the value doesn't exist in
* the tree, or it is contained in the root node.
*/
public TreeNode findParent(int value) {
return findParentRecursion(value, root);
}
/**
* Main recursive logic for the findParent method.
*
* @param value
* @param current
* @return Reference to the parent node, null if the value doesn't exist in
* the tree, or it is contained in the root node.
*/
private TreeNode findParentRecursion(int value, TreeNode current) {
if (root.data == value) {
return null;
}
if (value < current.data) {
if (current.left == null) {
return null;
} else if (current.left.data == value) {
return current;
} else {
return findParentRecursion(value, current.left);
}
} else {
if (current.right == null) {
return null;
} else if (current.right.data == value) {
return current;
} else {
return findParentRecursion(value, current.right);
}
}
}
/**
* Removes node with the given value from the tree.
*
* @param value
* Data of the node to remove.
* @return True if the value existed and was removed, false if the value did
* not exist in the tree.
*/
public boolean remove(int value) {
TreeNode nodeToRemove = findNode(value);
if (nodeToRemove == null) {
return false;
}
TreeNode parent = findParent(value);
if (root.left == null && root.right == null) {
root = null;
} else if (nodeToRemove.left == null && nodeToRemove.right == null) {
if (value < parent.data) {
parent.left = null;
} else {
parent.right = null;
}
} else if (nodeToRemove.left == null) {
if (value < parent.data) {
parent.left = nodeToRemove.right;
} else {
parent.right = nodeToRemove.right;
}
} else if (nodeToRemove.right == null) {
if (value < parent.data) {
parent.left = nodeToRemove.left;
} else {
parent.right = nodeToRemove.left;
}
} else {
TreeNode largestValue = nodeToRemove.left;
boolean right = false;
while (largestValue.right != null) {
largestValue = largestValue.right;
right = true;
}
// bug bug bug !!!
if (right) {
findParent(largestValue.data).right = null;
} else {
findParent(largestValue.data).left = null;
}
nodeToRemove.data = largestValue.data;
}
return true;
}
/**
* findMin and findMax could potentially return the value instead of the
* node, but then it creates a problem when the tree is empty - throwing an
* exception can be a solution to this problem.
*/
/**
* Finds the node with the minimum value.
*
* @return Node with minimum value.
*/
public TreeNode findMin() {
if (root == null) {
return null;
}
return findMinRecursion(root);
}
/**
* Recursive logic for findMin method.
*
* @param current
* @return
*/
private TreeNode findMinRecursion(TreeNode current) {
if (current.left == null) {
return current;
} else {
return findMinRecursion(current.left);
}
}
/**
* Finds the node with the maximum value.
*
* @return Node with maximum value.
*/
public TreeNode findMax() {
if (root == null) {
return null;
}
return findMaxRecursion(root);
}
/**
* Recursive logic for findMax method.
*
* @param current
* @return
*/
private TreeNode findMaxRecursion(TreeNode current) {
if (current.right == null) {
return current;
} else {
return findMaxRecursion(current.right);
}
}
/**
* Test method
*/
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.insert(42);
bt.insert(13);
bt.insert(666);
bt.insert(10);
bt.insert(11);
bt.insert(7);
bt.insert(9);
bt.insert(4);
System.out.println("1: " + bt.contains(1));
System.out.println("10: " + bt.contains(10));
System.out.println("42: " + bt.contains(42));
System.out.println("13: " + bt.contains(13));
System.out.println("11: " + bt.contains(11));
System.out.println("7: " + bt.contains(7));
System.out.println("9: " + bt.contains(9));
System.out.println("4: " + bt.contains(4));
System.out.println("666: " + bt.contains(666));
System.out.println("123456: " + bt.contains(123456));
System.out.println();
System.out.println(bt.findParent(42));
System.out.println(bt.findParent(13).data);
System.out.println(bt.findParent(10).data);
System.out.println(bt.findParent(123456));
System.out.println();
System.out.println(bt.findNode(1));
System.out.println(bt.findNode(42));
System.out.println(bt.findNode(666));
System.out.println();
// remove test
// int vToRemove = 42;
// System.out.println(vToRemove + ": " + bt.contains(vToRemove));
// System.out.println("Removing " + vToRemove);
// bt.remove(vToRemove);
System.out.println("42: " + bt.contains(42));
System.out.println("10: " + bt.contains(10));
System.out.println("13: " + bt.contains(13));
System.out.println("11: " + bt.contains(11));
System.out.println("7: " + bt.contains(7));
System.out.println("9: " + bt.contains(9));
System.out.println("4: " + bt.contains(4));
System.out.println("666: " + bt.contains(666));
System.out.println();
System.out.println("Min: " + bt.findMin().data);
System.out.println("Max: " + bt.findMax().data);
}
}
class TreeNode {
int data;
TreeNode left;
TreeNode right;
}
|
package mockit;
import org.junit.*;
import static org.junit.Assert.*;
import mockit.internal.*;
public final class ExpectationsForConstructorsTest
{
public static class BaseCollaborator
{
protected int value;
protected BaseCollaborator() { value = -1; }
protected BaseCollaborator(int value) { this.value = value; }
protected boolean add(Integer i) { return i != null; }
}
static class Collaborator extends BaseCollaborator
{
Collaborator() {}
Collaborator(int value) { super(value); }
}
@SuppressWarnings("UnusedDeclaration")
public abstract static class AbstractCollaborator extends BaseCollaborator
{
protected AbstractCollaborator(int value) { super(value); }
protected AbstractCollaborator(boolean b, int value) { super(value); }
protected abstract void doSomething();
}
@Test
public void mockAllConstructors()
{
new Expectations() {
@Mocked final Collaborator unused = null;
{
new Collaborator();
new Collaborator(123);
}
};
assertEquals(0, new Collaborator().value);
assertEquals(0, new Collaborator(123).value);
}
@Test
public void mockOnlyOneConstructor()
{
new Expectations() {
@Mocked("(int)")
final Collaborator unused = null;
{
new Collaborator(123);
}
};
assertEquals(-1, new Collaborator().value);
assertEquals(-1, new Collaborator(123).value);
}
@Test
public void mockOnlyNoArgsConstructor()
{
new Expectations() {
@Mocked("()")
final Collaborator unused = null;
{
new Collaborator();
}
};
assertEquals(0, new Collaborator().value);
assertEquals(123, new Collaborator(123).value);
}
@Test
public void partiallyMockAbstractClass(final AbstractCollaborator mock)
{
new Expectations() {{ mock.doSomething(); }};
mock.doSomething();
}
@Test
public void partiallyMockSubclass()
{
new Expectations() {
@Mocked("add") Collaborator mock;
{
mock.add(5); result = false;
}
};
assertEquals(12, new Collaborator(12).value);
assertFalse(new Collaborator().add(5));
}
static class A
{
@SuppressWarnings("UnusedDeclaration") private A() {}
A(String s) { assertNotNull("A(String) executed with null", s); }
}
static class B extends A { B(String s) { super(s); } }
@Test
public void mockClassHierarchyWhereFirstConstructorInBaseClassIsPrivate(@Mocked B mock)
{
new B("Test1");
}
@SuppressWarnings({"UnnecessaryFullyQualifiedName", "UnusedParameters"})
static class D extends integrationTests.C { D(String s) {} }
@Test
public void mockClassHierarchyWhereFirstConstructorInBaseClassOnAnotherPackageIsPackagePrivate(D mock)
{
assertNotNull(mock);
new D("Test1");
}
static class Base {}
static class Derived extends Base {}
@Test
public void recordAndReplayBaseConstructorInvocation(@Mocked Base mocked)
{
new Expectations() {{ new Base(); }};
new Base();
}
@Test(expected = MissingInvocation.class)
public void recordStrictExpectationOnBaseConstructorAndReplayWithCallToSuper(@Mocked Base mocked)
{
new Expectations() {{ new Base(); }};
new Derived();
}
@Test(expected = MissingInvocation.class)
public void recordNonStrictExpectationOnBaseConstructorAndReplayWithCallToSuper(@NonStrict Base mocked)
{
new Expectations() {{ new Base(); times = 1; }};
new Derived();
}
@Test(expected = MissingInvocation.class)
public void verifyExpectationOnBaseConstructorReplayedWithCallToSuper(@Mocked Base mocked)
{
new Derived();
new Verifications() {{ new Base(); }};
}
}
|
package com.flytxt.tp.marker;
public class Marker {
public int index;
public int length;
private FindMarker fm = new FindMarker();
private CurrentObject currentObject;
private byte[] localData;
Marker(byte[] data, int index, int length) {
localData = data;
this.index = index;
this.length = length;
}
public Marker(CurrentObject currentObject) {
this.currentObject = currentObject;
}
public void setLineAttribute(int index, int length) {
this.index = index;
this.length = length;
localData = null;
}
public void setData(byte[] data, int index, int length) {
localData = data;
this.index = index;
this.length = length;
}
public void splitAndGetMarkers(final byte[] token, final Router r, final MarkerFactory mf, Marker... markers) {
if (localData == null) {
byte[] data = currentObject.getLine();
find(false, data, token, r, mf, markers);
} else {
find(true, localData, token, r, mf, markers);
}
}
private void resetMarkerLength(Marker... markers) {
for (Marker aMarker : markers) {
aMarker.length = 0;
}
}
protected void find(boolean assignData, byte[] data, byte[] token, final Router router, MarkerFactory mf, Marker... markers) {
resetMarkerLength(markers);
if (token.length == 1)
fromByteArray(assignData, token[0], data, router, markers);
else
fromByteArray(assignData, token, data, router, markers);
// System.out.println("\n");
}
private void fromByteArray(boolean assignData, byte token, byte[] data, Router router, Marker... markers) {
int eol = this.index + length;
int from = this.index;
int stx = this.index;
int markers2Mine = router.maxMarkers2Mine();
int counter = 0;
for (int i = 0; i <= markers2Mine; i++) {
from = fm.findPreMarker(token, from + 1, eol, data);
if (from == -1) {// there is no marker hence consider the whole ",NoCommaAfterThis."
from = eol;
}
int len = from - stx;
if (len < 0) {
stx = 0;
len = 0;
}
// System.out.println("{M:"+i +" from:"+from +" str: "+new String(data, stx, len) +" } ");
int nextPos = router.geNthtMarkerlocation(counter);
if (i == nextPos) {
int ptr = router.getMarkerPosition(counter);
Marker m = markers[ptr];
m.setLineAttribute(stx, len);
if (assignData)
m.setData(data, stx, len);
counter++;
}
stx = from + 1;
}
}
private void fromByteArray(boolean assignData, byte[] token, byte[] data, Router router, Marker... markers) {
int eol = this.index + length;
int from = this.index;
int stx = this.index;
int markers2Mine = router.maxMarkers2Mine();
int counter = 0;
for (int i = 0; i <= markers2Mine; i++) {
from = fm.findPreMarker(token, from + 1, eol, data);
int len = from - stx - token.length;
// System.out.println("{M:"+i +" from:"+from +" str: "+new String(data, stx, len) +" } ");
int nextPos = router.geNthtMarkerlocation(counter);
if (i == nextPos) {
int ptr = router.getMarkerPosition(counter);
Marker m = markers[ptr];
m.setLineAttribute(stx, len);
if (assignData)
m.setData(data, stx, len);
counter++;
}
stx = from;
}
}
public byte[] getData() {
return (localData == null) ? currentObject.getLine() : localData;
}
@Override
public String toString() {
return new String((localData == null) ? currentObject.getLine() : localData, index, length);
}
public int asInt() {
return (int)asLong();
}
public long asLong() {
if (length == 0) {
return 0;
}
long value = 0;
byte[] data = getData();
int power = length;
for (int i = index; i < index + length; i++) {
power = power - 1;
value += Math.pow(10, power) * Character.getNumericValue(data[i]);
}
return value;
}
public double asDouble() {
if (length == 0) {
return 0;
}
return Double.parseDouble(toString());
}
}
|
package org.osmdroid.samplefragments.location;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import org.osmdroid.R;
import org.osmdroid.samplefragments.BaseSampleFragment;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.compass.IOrientationConsumer;
import org.osmdroid.views.overlay.compass.IOrientationProvider;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
public class SampleHeadingCompassUp extends BaseSampleFragment implements LocationListener, IOrientationConsumer {
int deviceOrientation = 0;
MyLocationNewOverlay overlay = null;
IOrientationProvider compass = null;
float gpsspeed;
float gpsbearing;
TextView textViewCurrentLocation = null;
float lat = 0;
float lon = 0;
float alt = 0;
long timeOfFix = 0;
String screen_orientation = "";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.map_with_locationbox, container, false);
mMapView = (MapView) root.findViewById(R.id.mapview);
textViewCurrentLocation = (TextView) root.findViewById(R.id.textViewCurrentLocation);
return root;
}
@Override
public String getSampleTitle() {
return "Heading/Compass Up";
}
@Override
public void addOverlays() {
overlay = new MyLocationNewOverlay(mMapView);
overlay.setEnableAutoStop(false);
overlay.enableFollowLocation();
overlay.enableMyLocation();
this.mMapView.getOverlayManager().add(overlay);
}
@Override
public void onResume() {
super.onResume();
//hack for x86
if (!"Android-x86".equalsIgnoreCase(Build.BRAND)) {
//lock the device in current screen orientation
int orientation;
int rotation = ((WindowManager) getActivity().getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
this.deviceOrientation = 0;
screen_orientation = "ROTATION_0 SCREEN_ORIENTATION_PORTRAIT";
break;
case Surface.ROTATION_90:
this.deviceOrientation = 90;
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
screen_orientation = "ROTATION_90 SCREEN_ORIENTATION_LANDSCAPE";
break;
case Surface.ROTATION_180:
this.deviceOrientation = 180;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
screen_orientation = "ROTATION_180 SCREEN_ORIENTATION_REVERSE_PORTRAIT";
break;
default:
this.deviceOrientation = 270;
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
screen_orientation = "ROTATION_270 SCREEN_ORIENTATION_REVERSE_LANDSCAPE";
break;
}
getActivity().setRequestedOrientation(orientation);
}
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
try {
//on API15 AVDs,network provider fails. no idea why
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, (LocationListener) this);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, (LocationListener) this);
} catch (Exception ex) {
}
compass = new InternalCompassOrientationProvider(getActivity());
compass.startOrientationProvider(this);
mMapView.getController().zoomTo(18);
}
@Override
public void onPause() {
super.onPause();
compass.stopOrientationProvider();
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
try {
lm.removeUpdates(this);
} catch (Exception ex) {
}
//unlock the orientation
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
@Override
public void onDestroyView() {
super.onDestroyView();
compass.destroy();
overlay.disableMyLocation();
overlay.disableFollowLocation();
overlay.onDetach(mMapView);
if (mMapView != null)
mMapView.onDetach();
mMapView = null;
overlay = null;
compass = null;
textViewCurrentLocation = null;
}
@Override
public void onLocationChanged(Location location) {
if (mMapView == null)
return;
gpsbearing = location.getBearing();
gpsspeed = location.getSpeed();
lat = (float) location.getLatitude();
lon = (float) location.getLongitude();
alt = (float) location.getAltitude(); //meters
timeOfFix = location.getTime();
//use gps bearing instead of the compass
float t = (360 - gpsbearing - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
//help smooth everything out
t = (int) t;
t = t / 10;
t = (int) t;
t = t * 10;
mMapView.setMapOrientation(t);
updateDisplay(location.getBearing());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
Float trueNorth = 0f;
@Override
public void onOrientationChanged(final float orientationToMagneticNorth, IOrientationProvider source) {
//note, on devices without a compass this never fires...
//only use the compass bit if we aren't moving, since gps is more accurate
if (gpsspeed > 0.01) {
GeomagneticField gf = new GeomagneticField(lat, lon, alt, timeOfFix);
trueNorth = orientationToMagneticNorth + gf.getDeclination();
gf = null;
synchronized (trueNorth) {
if (trueNorth > 360.0f) {
trueNorth = trueNorth - 360.0f;
}
float actualHeading = 0f;
//this part adjusts the desired map rotation based on device orientation and compass heading
float t = (360 - trueNorth - this.deviceOrientation);
if (t < 0) {
t += 360;
}
if (t > 360) {
t -= 360;
}
actualHeading = t;
//help smooth everything out
t = (int) t;
t = t / 10;
t = (int) t;
t = t * 10;
mMapView.setMapOrientation(t);
updateDisplay(actualHeading);
}
}
}
private void updateDisplay(final float bearing) {
try {
Activity act = getActivity();
if (act != null)
act.runOnUiThread(new Runnable() {
@Override
public void run() {
if (getActivity() != null && textViewCurrentLocation != null) {
textViewCurrentLocation.setText("GPS Speed: " + gpsspeed + "m/s GPS Bearing: " + gpsbearing +
"\nDevice Orientation: " + (int) deviceOrientation + " Compass heading: " + (int) bearing + "\n" +
"True north: " + trueNorth.intValue() + " Map Orientation: " + (int) mMapView.getMapOrientation() + "\n" +
screen_orientation);
}
}
});
} catch (Exception ex) {
}
}
private void updateMap() {
}
}
|
package com.hubspot.singularity.mesos;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.mesos.Protos;
import org.apache.mesos.Protos.ContainerInfo.DockerInfo.PortMapping;
import org.apache.mesos.Protos.ContainerInfo.Type;
import org.apache.mesos.Protos.Environment.Variable;
import org.apache.mesos.Protos.FrameworkID;
import org.apache.mesos.Protos.Offer;
import org.apache.mesos.Protos.OfferID;
import org.apache.mesos.Protos.Parameter;
import org.apache.mesos.Protos.SlaveID;
import org.apache.mesos.Protos.Volume.Mode;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableMap;
import com.hubspot.mesos.MesosUtils;
import com.hubspot.mesos.Resources;
import com.hubspot.mesos.SingularityContainerInfo;
import com.hubspot.mesos.SingularityContainerType;
import com.hubspot.mesos.SingularityDockerInfo;
import com.hubspot.mesos.SingularityDockerNetworkType;
import com.hubspot.mesos.SingularityDockerPortMapping;
import com.hubspot.mesos.SingularityDockerVolumeMode;
import com.hubspot.mesos.SingularityPortMappingType;
import com.hubspot.mesos.SingularityVolume;
import com.hubspot.singularity.RequestType;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityDeployBuilder;
import com.hubspot.singularity.SingularityPendingRequest.PendingType;
import com.hubspot.singularity.SingularityPendingTask;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestBuilder;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskRequest;
import com.hubspot.singularity.config.NetworkConfiguration;
import com.hubspot.singularity.config.SingularityConfiguration;
import com.hubspot.singularity.data.ExecutorIdGenerator;
public class SingularityMesosTaskBuilderTest {
private final SingularityConfiguration configuration = new SingularityConfiguration();
private SingularityMesosTaskBuilder builder;
private Resources taskResources;
private Resources executorResources;
private Offer offer;
private SingularityPendingTask pendingTask;
private final String user = "testUser";
@Before
public void createMocks() {
pendingTask = new SingularityPendingTask(new SingularityPendingTaskId("test", "1", 0, 1, PendingType.IMMEDIATE, 0), Optional.<List<String>> absent(),
Optional.of(user), Optional.<String> absent(), Optional.<Boolean> absent(), Optional.<String> absent(), Optional.<Resources>absent(), Optional.<String>absent());
final SingularitySlaveAndRackHelper slaveAndRackHelper = mock(SingularitySlaveAndRackHelper.class);
final ExecutorIdGenerator idGenerator = mock(ExecutorIdGenerator.class);
when(idGenerator.getNextExecutorId()).then(new CreateFakeId());
builder = new SingularityMesosTaskBuilder(new ObjectMapper(), slaveAndRackHelper, idGenerator, configuration);
taskResources = new Resources(1, 1, 0, 0);
executorResources = new Resources(0.1, 1, 0, 0);
offer = Offer.newBuilder()
.setSlaveId(SlaveID.newBuilder().setValue("1"))
.setId(OfferID.newBuilder().setValue("1"))
.setFrameworkId(FrameworkID.newBuilder().setValue("1"))
.setHostname("test")
.build();
when(slaveAndRackHelper.getRackId(offer)).thenReturn(Optional.<String> absent());
when(slaveAndRackHelper.getMaybeTruncatedHost(offer)).thenReturn("host");
when(slaveAndRackHelper.getRackIdOrDefault(offer)).thenReturn("DEFAULT");
}
@Test
public void testShellCommand() {
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER).build();
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setCommand(Optional.of("/bin/echo hi"))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, null, taskRequest, taskResources, executorResources);
assertEquals("/bin/echo hi", task.getMesosTask().getCommand().getValue());
assertEquals(0, task.getMesosTask().getCommand().getArgumentsCount());
assertTrue(task.getMesosTask().getCommand().getShell());
}
@Test
public void testJobUserPassedAsEnvironmentVariable() {
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER)
.build();
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setCommand(Optional.of("/bin/echo hi"))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, null, taskRequest, taskResources, executorResources);
List<Variable> environmentVariables = task.getMesosTask()
.getCommand()
.getEnvironment()
.getVariablesList();
boolean success = false;
for (Variable environmentVariable : environmentVariables) {
success = success || (environmentVariable.getName().equals("JOB_USER") && environmentVariable.getValue().equals(user));
}
assertTrue("Expected env variable JOB_USER to be set to " + user, success);
}
@Test
public void testArgumentCommand() {
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER).build();
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setCommand(Optional.of("/bin/echo"))
.setArguments(Optional.of(Collections.singletonList("wat")))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, null, taskRequest, taskResources, executorResources);
assertEquals("/bin/echo", task.getMesosTask().getCommand().getValue());
assertEquals(1, task.getMesosTask().getCommand().getArgumentsCount());
assertEquals("wat", task.getMesosTask().getCommand().getArguments(0));
assertFalse(task.getMesosTask().getCommand().getShell());
}
@Test
public void testDockerTask() {
taskResources = new Resources(1, 1, 1, 0);
final Protos.Resource portsResource = Protos.Resource.newBuilder()
.setName("ports")
.setType(Protos.Value.Type.RANGES)
.setRanges(Protos.Value.Ranges.newBuilder()
.addRange(Protos.Value.Range.newBuilder()
.setBegin(31000)
.setEnd(31000).build()).build()).build();
final SingularityDockerPortMapping literalMapping = new SingularityDockerPortMapping(Optional.<SingularityPortMappingType>absent(), 80, Optional.of(SingularityPortMappingType.LITERAL), 8080, Optional.<String>absent());
final SingularityDockerPortMapping offerMapping = new SingularityDockerPortMapping(Optional.<SingularityPortMappingType>absent(), 81, Optional.of(SingularityPortMappingType.FROM_OFFER), 0, Optional.of("udp"));
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER).build();
final SingularityContainerInfo containerInfo = new SingularityContainerInfo(
SingularityContainerType.DOCKER,
Optional.of(Arrays.asList(
new SingularityVolume("/container", Optional.of("/host"), SingularityDockerVolumeMode.RW),
new SingularityVolume("/container/${TASK_REQUEST_ID}/${TASK_DEPLOY_ID}", Optional.of("/host/${TASK_ID}"), SingularityDockerVolumeMode.RO))),
Optional.of(new SingularityDockerInfo("docker-image", true, SingularityDockerNetworkType.BRIDGE, Optional.of(Arrays.asList(literalMapping, offerMapping)), Optional.of(false), Optional.<Map<String, String>>of(
ImmutableMap.of("env", "var=value")))));
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setContainerInfo(Optional.of(containerInfo))
.setCommand(Optional.of("/bin/echo"))
.setArguments(Optional.of(Collections.singletonList("wat")))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, Collections.singletonList(portsResource), taskRequest, taskResources, executorResources);
assertEquals("/bin/echo", task.getMesosTask().getCommand().getValue());
assertEquals(1, task.getMesosTask().getCommand().getArgumentsCount());
assertEquals("wat", task.getMesosTask().getCommand().getArguments(0));
assertFalse(task.getMesosTask().getCommand().getShell());
assertEquals(Type.DOCKER, task.getMesosTask().getContainer().getType());
assertEquals("docker-image", task.getMesosTask().getContainer().getDocker().getImage());
assertTrue(task.getMesosTask().getContainer().getDocker().getPrivileged());
assertEquals("/container", task.getMesosTask().getContainer().getVolumes(0).getContainerPath());
assertEquals("/host", task.getMesosTask().getContainer().getVolumes(0).getHostPath());
assertEquals(Mode.RW, task.getMesosTask().getContainer().getVolumes(0).getMode());
Parameter envParameter = Parameter.newBuilder().setKey("env").setValue("var=value").build();
assertTrue(task.getMesosTask().getContainer().getDocker().getParametersList().contains(envParameter));
assertEquals(String.format("/container/%s/%s", task.getTaskRequest().getDeploy().getRequestId(), task.getTaskRequest().getDeploy().getId()), task.getMesosTask().getContainer().getVolumes(1).getContainerPath());
assertEquals(String.format("/host/%s", task.getMesosTask().getTaskId().getValue()), task.getMesosTask().getContainer().getVolumes(1).getHostPath());
assertEquals(Mode.RO, task.getMesosTask().getContainer().getVolumes(1).getMode());
assertEquals(80, task.getMesosTask().getContainer().getDocker().getPortMappings(0).getContainerPort());
assertEquals(8080, task.getMesosTask().getContainer().getDocker().getPortMappings(0).getHostPort());
assertEquals("tcp", task.getMesosTask().getContainer().getDocker().getPortMappings(0).getProtocol());
assertTrue(MesosUtils.getAllPorts(task.getMesosTask().getResourcesList()).contains(8080L));
assertEquals(81, task.getMesosTask().getContainer().getDocker().getPortMappings(1).getContainerPort());
assertEquals(31000, task.getMesosTask().getContainer().getDocker().getPortMappings(1).getHostPort());
assertEquals("udp", task.getMesosTask().getContainer().getDocker().getPortMappings(1).getProtocol());
assertEquals(Protos.ContainerInfo.DockerInfo.Network.BRIDGE, task.getMesosTask().getContainer().getDocker().getNetwork());
}
@Test
public void testDockerMinimalNetworking() {
taskResources = new Resources(1, 1, 0, 0);
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER).build();
final SingularityContainerInfo containerInfo = new SingularityContainerInfo(
SingularityContainerType.DOCKER,
Optional.<List<SingularityVolume>>absent(),
Optional.of(new SingularityDockerInfo("docker-image", true, SingularityDockerNetworkType.NONE,
Optional.<List<SingularityDockerPortMapping>>absent(),
Optional.<Boolean>absent(),
Optional.<Map<String, String>>absent())));
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setContainerInfo(Optional.of(containerInfo))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, Collections.<Protos.Resource>emptyList(), taskRequest, taskResources, executorResources);
assertEquals(Type.DOCKER, task.getMesosTask().getContainer().getType());
assertEquals(Protos.ContainerInfo.DockerInfo.Network.NONE, task.getMesosTask().getContainer().getDocker().getNetwork());
}
@Test
public void testAutomaticPortMapping() {
NetworkConfiguration netConf = new NetworkConfiguration();
netConf.setDefaultPortMapping(true);
configuration.setNetworkConfiguration(netConf);
taskResources = new Resources(1, 1, 2);
final SingularityRequest request = new SingularityRequestBuilder("test", RequestType.WORKER).build();
final SingularityContainerInfo containerInfo = new SingularityContainerInfo(
SingularityContainerType.DOCKER,
Optional.<List<SingularityVolume>>absent(),
Optional.of(new SingularityDockerInfo("docker-image", false, SingularityDockerNetworkType.BRIDGE,
Optional.<List<SingularityDockerPortMapping>>absent(),
Optional.<Boolean>absent(),
Optional.<Map<String, String>>absent())));
final SingularityDeploy deploy = new SingularityDeployBuilder("test", "1")
.setContainerInfo(Optional.of(containerInfo))
.build();
final SingularityTaskRequest taskRequest = new SingularityTaskRequest(request, deploy, pendingTask);
final SingularityTask task = builder.buildTask(offer, Collections.singletonList(MesosUtils.getPortRangeResource(31010, 31011)), taskRequest, taskResources, executorResources);
assertEquals(Type.DOCKER, task.getMesosTask().getContainer().getType());
assertEquals(Protos.ContainerInfo.DockerInfo.Network.BRIDGE, task.getMesosTask().getContainer().getDocker().getNetwork());
List<PortMapping> portMappings = task.getMesosTask().getContainer().getDocker().getPortMappingsList();
assertEquals(2, portMappings.size());
assertEquals(31010, portMappings.get(0).getHostPort());
assertEquals(31010, portMappings.get(0).getContainerPort());
assertEquals(31011, portMappings.get(1).getHostPort());
assertEquals(31011, portMappings.get(1).getContainerPort());
}
private static class CreateFakeId implements Answer<String> {
private final AtomicLong string = new AtomicLong();
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return String.valueOf(string.incrementAndGet());
}
}
}
|
package it.angelic.soulissclient.model.typicals;
import android.content.Context;
import android.os.Looper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
import it.angelic.soulissclient.R;
import it.angelic.soulissclient.SoulissClient;
import it.angelic.soulissclient.helpers.ListButton;
import it.angelic.soulissclient.helpers.SoulissPreferenceHelper;
import it.angelic.soulissclient.model.ISoulissTypical;
import it.angelic.soulissclient.model.SoulissCommand;
import it.angelic.soulissclient.model.SoulissTypical;
import it.angelic.soulissclient.net.UDPHelper;
public class SoulissTypical19AnalogChannel extends SoulissTypical implements ISoulissTypical {
// SoulissNode parentd = getParentNode();
// SoulissTypical related =
// parentd.getTypical((short)(getTypicalDTO().getSlot()+1));
private static final long serialVersionUID = 45534215562542092L;
// Context ctx;
public SoulissTypical19AnalogChannel(SoulissPreferenceHelper pp) {
super(pp);
}
@Override
public ArrayList<SoulissCommand> getCommands(Context ctx) {
// ritorna le bozze dei comandi, da riempire con la schermata addProgram
ArrayList<SoulissCommand> ret = new ArrayList<>();
SoulissCommand t = new SoulissCommand( this);
t.getCommandDTO().setCommand(Constants.Souliss_T1n_OnCmd);
t.getCommandDTO().setSlot(getTypicalDTO().getSlot());
t.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(t);
SoulissCommand ff = new SoulissCommand( this);
ff.getCommandDTO().setCommand(Constants.Souliss_T1n_OffCmd);
ff.getCommandDTO().setSlot(getTypicalDTO().getSlot());
ff.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(ff);
SoulissCommand ft = new SoulissCommand( this);
ft.getCommandDTO().setCommand(Constants.Souliss_T1n_ToogleCmd);
ft.getCommandDTO().setSlot(getTypicalDTO().getSlot());
ft.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(ft);
SoulissCommand ftt = new SoulissCommand( this);
ftt.getCommandDTO().setCommand(Constants.Souliss_T19_Min);
ftt.getCommandDTO().setSlot(getTypicalDTO().getSlot());
ftt.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(ftt);
SoulissCommand fttd = new SoulissCommand( this);
ftt.getCommandDTO().setCommand(Constants.Souliss_T19_Med);
ftt.getCommandDTO().setSlot(getTypicalDTO().getSlot());
ftt.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(fttd);
SoulissCommand ftts = new SoulissCommand( this);
ftt.getCommandDTO().setCommand(Constants.Souliss_T19_Max);
ftt.getCommandDTO().setSlot(getTypicalDTO().getSlot());
ftt.getCommandDTO().setNodeId(getTypicalDTO().getNodeId());
ret.add(ftts);
return ret;
}
public int getIntensity() {
int r = getParentNode().getTypical((short) (typicalDTO.getSlot() + 1))
.getTypicalDTO().getOutput();
return r;
}
public String getIntensityPercent(){
return ""+String.valueOf((int)(Float.valueOf(getIntensity() / 255f) * 100)) + "%";
}
/**
* Ottiene il layout del pannello comandi
*
* @param ctx contesto
* @param convertView la View da popolare
*/
@Override
public void getActionsLayout(final Context ctx,
LinearLayout convertView) {
LinearLayout cont = convertView;
cont.removeAllViews();
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
cont.addView(getQuickActionTitle());
/*
*
* TRE BOTTONI: ON, OFF e TOGGLE
*/
final ListButton turnON = new ListButton(ctx);
turnON.setText("ON");
turnON.setLayoutParams(lp);
cont.addView(turnON);
final ListButton turnOFF = new ListButton(ctx);
turnOFF.setText("OFF");
turnOFF.setLayoutParams(lp);
cont.addView(turnOFF);
turnON.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
turnON.setEnabled(false);
turnOFF.setEnabled(false);
Thread t = new Thread() {
public void run() {
UDPHelper.issueSoulissCommand("" + getTypicalDTO().getNodeId(), "" + typicalDTO.getSlot(),
prefs, String.valueOf(Constants.Souliss_T1n_OnCmd));
}
};
t.start();
}
});
turnOFF.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
turnON.setEnabled(false);
turnOFF.setEnabled(false);
Thread t = new Thread() {
public void run() {
UDPHelper.issueSoulissCommand("" + getTypicalDTO().getNodeId(), "" + typicalDTO.getSlot(),
prefs, String.valueOf(Constants.Souliss_T1n_OffCmd));
}
};
t.start();
}
});
}
@Override
public void setOutputDescView(TextView textStatusVal) {
textStatusVal.setText(getOutputDesc());
if (typicalDTO.getOutput() == Constants.Souliss_T1n_OffCoil || "UNKNOWN".compareTo(getOutputDesc()) == 0) {
textStatusVal.setTextColor(SoulissClient.getAppContext().getResources().getColor(R.color.std_red));
textStatusVal.setBackgroundResource(R.drawable.borderedbackoff);
} else {
textStatusVal.setTextColor(SoulissClient.getAppContext().getResources().getColor(R.color.std_green));
textStatusVal.setBackgroundResource(R.drawable.borderedbackon);
}
}
@Override
public String getOutputDesc() {
if (typicalDTO.getOutput() == Constants.Souliss_T1n_OffCoil)
return SoulissClient.getAppContext().getString(R.string.OFF);
else
return SoulissClient.getAppContext().getString(R.string.ON) + " " +getIntensityPercent();
}
public void issueSingleChannelCommand(final short command, final int intensity, final boolean togMulticast) {
Thread t = new Thread() {
public void run() {
Looper.prepare();
if (togMulticast)//a tutti i nodi
UDPHelper.issueMassiveCommand("" + Constants.Souliss_T19, prefs, "" + command, "" + intensity);
else
UDPHelper.issueSoulissCommand("" + getParentNode().getId(), ""
+ getTypicalDTO().getSlot(), prefs, "" + command, "" + intensity);
}
};
t.start();
}
public void issueSingleChannelCommand(final short command, final boolean togMulticast) {
Thread t = new Thread() {
public void run() {
Looper.prepare();
if (togMulticast)//a tutti i nodi
UDPHelper.issueMassiveCommand("" + Constants.Souliss_T19, prefs, "" + command );
else
UDPHelper.issueSoulissCommand("" + getParentNode().getId(), ""
+ getTypicalDTO().getSlot(), prefs, "" + command );
}
};
t.start();
}
public void issueRefresh() {
Thread t = new Thread() {
public void run() {
Looper.prepare();
//refresh data for typical's node
UDPHelper.pollRequest(prefs, 1, getParentNode().getId());
}
};
t.start();
}
}
|
package edu.wustl.catissuecore.bizlogic.test;
import com.mockobjects.constraint.Constraint;
import com.mockobjects.constraint.IsAnything;
import com.mockobjects.constraint.IsInstanceOf;
import com.mockobjects.dynamic.FullConstraintMatcher;
import com.mockobjects.dynamic.Mock;
import edu.wustl.catissuecore.bizlogic.IdentifiedSurgicalPathologyReportBizLogic;
import edu.wustl.catissuecore.domain.pathology.IdentifiedSurgicalPathologyReport;
import edu.wustl.catissuecore.domain.pathology.TextContent;
import edu.wustl.catissuecore.test.MockDAOFactory;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.dao.DAOFactory;
import edu.wustl.common.dao.HibernateDAO;
import edu.wustl.common.dao.JDBCDAO;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.test.BaseTestCase;
import edu.wustl.common.util.global.Constants;
public class IdentifiedSurgicalPathologyReportBizLogicTest extends BaseTestCase
{
Mock hibDAO;
Mock jdbcDAO;
/**
* Constructor for IdentifiedSurgicalPathologyReportBizLogicTest.
* @param arg0 Name of the test case
*/
public IdentifiedSurgicalPathologyReportBizLogicTest(String name)
{
super(name);
}
/**
* This method makes an initial set up for test cases.
*
* JUnit calls setUp and tearDown for each test so that there can be no side effects among test runs.
* Here bizLogicInterfaceMock is instantiated.As this mock depicts the behaviour of BizLogicInterface,this
* interface is passed as an input parameter to the constructor.
*
* The original instance of BizLogicFactory is replaced with an instance of MockBizLogicFactory.
* Whenever a call to the BizLogicFactory is made,MockBizLogicFactory will come into picture.This
* mock factory will return the instance of bizLogicInterfaceMock.
*/
protected void setUp()
{
hibDAO = new Mock(HibernateDAO.class);
jdbcDAO = new Mock(JDBCDAO.class);
MockDAOFactory factory = new MockDAOFactory();
factory.setHibernateDAO((HibernateDAO) hibDAO.proxy());
factory.setJDBCDAO((JDBCDAO) jdbcDAO.proxy());
DAOFactory.setDAOFactory(factory);
}
public void testPathRptLoadBizLogicNullInputParametersInInsert()
{
hibDAO.expect("closeSession");
IdentifiedSurgicalPathologyReportBizLogic identifiedSurgicalPathologyReportBizLogic = new IdentifiedSurgicalPathologyReportBizLogic();
try
{
identifiedSurgicalPathologyReportBizLogic.insert(new IdentifiedSurgicalPathologyReport(),null,Constants.HIBERNATE_DAO);
fail("When null sessiondataBean is passes, it should throw NullPointerException");
}
catch(NullPointerException e)
{
e.printStackTrace();
assertTrue("When null sessiondataBean is passes, it throws NullPointerException",true);
}
catch (BizLogicException e)
{
e.printStackTrace();
}
catch (UserNotAuthorizedException e)
{
e.printStackTrace();
}
hibDAO.expect("closeSession");
Constraint[] constraints = {new IsInstanceOf(SessionDataBean.class)};
FullConstraintMatcher fullConstraintMatcher = new FullConstraintMatcher(constraints);
hibDAO.expect("openSession",fullConstraintMatcher);
try
{
identifiedSurgicalPathologyReportBizLogic.insert(null,new SessionDataBean(),Constants.HIBERNATE_DAO);
fail("When null sessiondataBean is passes, it should throw NullPointerException");
}
catch(NullPointerException e)
{
e.printStackTrace();
assertTrue("When null sessiondataBean is passes, it throws NullPointerException",true);
}
catch (BizLogicException e)
{
e.printStackTrace();
}
catch (UserNotAuthorizedException e)
{
e.printStackTrace();
}
}
public void testPathRptLoadBizLogicInsertWithEmptyObject()
{
IdentifiedSurgicalPathologyReportBizLogic identifiedSurgicalPathologyReportBizLogic = new IdentifiedSurgicalPathologyReportBizLogic();
SessionDataBean sessionDataBean = new SessionDataBean();
Constraint[] constraints = {new IsInstanceOf(SessionDataBean.class)};
hibDAO.expect("commit");
FullConstraintMatcher fullConstraintMatcher = new FullConstraintMatcher(constraints);
hibDAO.expect("openSession",fullConstraintMatcher);
Constraint[] insertConstraints = {new IsAnything(),new IsAnything(),new IsAnything(),new IsAnything()};
FullConstraintMatcher insertConstraintMatcher = new FullConstraintMatcher(insertConstraints);
hibDAO.expect("insert",insertConstraintMatcher);
hibDAO.expect("closeSession");
try
{
identifiedSurgicalPathologyReportBizLogic.insert(new IdentifiedSurgicalPathologyReport(),sessionDataBean,edu.wustl.common.util.global.Constants.HIBERNATE_DAO);
fail("Identified report inserted successfully");
}
catch (NullPointerException e) {
assertTrue("Null Pointer Exception",true);
}
catch (BizLogicException e)
{
fail(" Exception occured");
}
catch (UserNotAuthorizedException e)
{
fail(" Exception occured");
}
}
public void testPathRptLoadBizLogicInsert()
{
IdentifiedSurgicalPathologyReportBizLogic identifiedSurgicalPathologyReportBizLogic = new IdentifiedSurgicalPathologyReportBizLogic();
IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=setIdentifiedReport();
SessionDataBean sessionDataBean = new SessionDataBean();
Constraint[] constraints = {new IsInstanceOf(SessionDataBean.class)};
hibDAO.expect("commit");
FullConstraintMatcher fullConstraintMatcher = new FullConstraintMatcher(constraints);
hibDAO.expect("openSession",fullConstraintMatcher);
Constraint[] insertConstraints = {new IsAnything(),new IsAnything(),new IsAnything(),new IsAnything()};
FullConstraintMatcher insertConstraintMatcher = new FullConstraintMatcher(insertConstraints);
hibDAO.expect("insert",insertConstraintMatcher);
hibDAO.expect("closeSession");
try
{
identifiedSurgicalPathologyReportBizLogic.insert(identifiedSurgicalPathologyReport,sessionDataBean,edu.wustl.common.util.global.Constants.HIBERNATE_DAO);
fail("Identified report inserted successfully");
}
catch (NullPointerException e) {
assertTrue("Null Pointer Exception",true);
}
catch (BizLogicException e)
{
fail(" Exception occured");
}
catch (UserNotAuthorizedException e)
{
fail(" Exception occured");
}
}
public void testPathRptLoadBizLogicNullInputParametersInUpdate()
{
hibDAO.expect("closeSession");
IdentifiedSurgicalPathologyReportBizLogic identifiedSurgicalPathologyReportBizLogic = new IdentifiedSurgicalPathologyReportBizLogic();
try
{
identifiedSurgicalPathologyReportBizLogic.update(new TextContent(),null,Constants.HIBERNATE_DAO,null);
fail("When null sessiondataBean is passes, it should throw NullPointerException");
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch (BizLogicException e)
{
e.printStackTrace();
}
catch (UserNotAuthorizedException e)
{
e.printStackTrace();
}
hibDAO.expect("closeSession");
Constraint[] constraints = {new IsInstanceOf(SessionDataBean.class)};
FullConstraintMatcher fullConstraintMatcher = new FullConstraintMatcher(constraints);
hibDAO.expect("openSession",fullConstraintMatcher);
try
{
identifiedSurgicalPathologyReportBizLogic.insert(null,new SessionDataBean(),Constants.HIBERNATE_DAO);
fail("When null sessiondataBean is passes, it should throw NullPointerException");
}
catch(NullPointerException e)
{
e.printStackTrace();
}
catch (BizLogicException e)
{
e.printStackTrace();
}
catch (UserNotAuthorizedException e)
{
e.printStackTrace();
}
}
public void testPathRptLoadBizLogicUpdate()
{
IdentifiedSurgicalPathologyReportBizLogic identifiedSurgicalPathologyReportBizLogic = new IdentifiedSurgicalPathologyReportBizLogic();
IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=setIdentifiedReport();
SessionDataBean sessionDataBean = new SessionDataBean();
Constraint[] constraints = {new IsInstanceOf(SessionDataBean.class)};
hibDAO.expect("commit");
FullConstraintMatcher fullConstraintMatcher = new FullConstraintMatcher(constraints);
hibDAO.expect("openSession",fullConstraintMatcher);
Constraint[] updateConstraints = {new IsAnything(),new IsAnything(),new IsAnything(),new IsAnything(),new IsAnything()};
FullConstraintMatcher updateConstraintMatcher = new FullConstraintMatcher(updateConstraints);
hibDAO.expect("update",updateConstraintMatcher);
Constraint[] auditConstraints = {new IsAnything(),new IsAnything(),new IsAnything(),new IsAnything()};
FullConstraintMatcher auditConstraintMatcher = new FullConstraintMatcher(auditConstraints);
hibDAO.expect("audit",auditConstraintMatcher);
hibDAO.expect("audit",auditConstraintMatcher);
hibDAO.expect("closeSession");
try
{
identifiedSurgicalPathologyReportBizLogic.update(identifiedSurgicalPathologyReport,identifiedSurgicalPathologyReport,edu.wustl.common.util.global.Constants.HIBERNATE_DAO,sessionDataBean);
assertTrue("Text Content updated successfully",true);
}
catch (NullPointerException e) {
e.printStackTrace();
fail("Null Pointer Exception");
}
catch (BizLogicException e)
{
e.printStackTrace();
fail("Biz Logic Exception occured");
}
catch (UserNotAuthorizedException e)
{
e.printStackTrace();
fail(" User Not Authorised Exception occured");
}
}
private IdentifiedSurgicalPathologyReport setIdentifiedReport()
{
IdentifiedSurgicalPathologyReport identifiedSurgicalPathologyReport=new IdentifiedSurgicalPathologyReport();
return identifiedSurgicalPathologyReport;
}
}
|
package org.springframework.roo.addon.web.selenium;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.roo.addon.beaninfo.BeanInfoMetadata;
import org.springframework.roo.addon.web.menu.MenuOperations;
import org.springframework.roo.addon.web.mvc.controller.WebScaffoldMetadata;
import org.springframework.roo.classpath.PhysicalTypeIdentifier;
import org.springframework.roo.classpath.details.FieldMetadata;
import org.springframework.roo.classpath.details.MemberFindingUtils;
import org.springframework.roo.classpath.details.MethodMetadata;
import org.springframework.roo.metadata.MetadataService;
import org.springframework.roo.model.JavaSymbolName;
import org.springframework.roo.model.JavaType;
import org.springframework.roo.process.manager.FileManager;
import org.springframework.roo.process.manager.MutableFile;
import org.springframework.roo.project.Path;
import org.springframework.roo.project.PathResolver;
import org.springframework.roo.project.ProjectMetadata;
import org.springframework.roo.support.lifecycle.ScopeDevelopment;
import org.springframework.roo.support.util.Assert;
import org.springframework.roo.support.util.TemplateUtils;
import org.springframework.roo.support.util.XmlUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
/**
* Provides property file configuration operations.
*
* @author Stefan Schmidt
* @since 1.0
*/
@ScopeDevelopment
public class SeleniumOperations {
private FileManager fileManager;
private PathResolver pathResolver;
private MetadataService metadataService;
private BeanInfoMetadata beanInfoMetadata;
private DateFormat dateFormat;
private MenuOperations menuOperations;
public SeleniumOperations(MetadataService metadataService, FileManager fileManager, PathResolver pathResolver, MenuOperations menuOperations, DateFormat dateFormat) {
Assert.notNull(metadataService, "Metadata service required");
Assert.notNull(fileManager, "File manager required");
Assert.notNull(pathResolver, "Path resolver required");
Assert.notNull(menuOperations, "Menu operations required");
Assert.notNull(dateFormat, "Date format required");
this.fileManager = fileManager;
this.pathResolver = pathResolver;
this.metadataService = metadataService;
this.dateFormat = dateFormat;
this.menuOperations = menuOperations;
}
/**
* Creates a new Selenium testcase
*
* @param controller the JavaType of the controller under test (required)
* @param name the name of the test case (optional)
*/
public void generateTest(JavaType controller, String name, String serverURL) {
Assert.notNull(controller, "Controller type required");
if(!serverURL.endsWith("/")) {
serverURL = serverURL + "/";
}
String webScaffoldMetadataIdentifier = WebScaffoldMetadata.createIdentifier(controller, Path.SRC_MAIN_JAVA);
WebScaffoldMetadata webScaffoldMetadata = (WebScaffoldMetadata) metadataService.get(webScaffoldMetadataIdentifier);
this.beanInfoMetadata = (BeanInfoMetadata) metadataService.get(webScaffoldMetadata.getIdentifierForBeanInfoMetadata());
String relativeTestFilePath = "selenium/test-" + beanInfoMetadata.getJavaBean().getSimpleTypeName().toLowerCase() + ".xhtml";
String seleniumPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath);
MutableFile seleniumMutableFile = null;
name = (name != null ? name : "Selenium test for " + controller.getSimpleTypeName());
Document selenium;
try {
if (fileManager.exists(seleniumPath)) {
seleniumMutableFile = fileManager.updateFile(seleniumPath);
selenium = XmlUtils.getDocumentBuilder().parse(seleniumMutableFile.getInputStream());
} else {
seleniumMutableFile = fileManager.createFile(seleniumPath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-template.xhtml");
Assert.notNull(templateInputStream, "Could not acquire selenium.xhtml template");
selenium = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
Assert.notNull(projectMetadata, "Unable to obtain project metadata");
Element root = (Element) selenium.getLastChild();
if(root == null || !"html".equals(root.getNodeName())) {
throw new IllegalArgumentException("Could not parse selenium test case template file!");
}
XmlUtils.findRequiredElement("/html/head/title", root).setTextContent(name);
XmlUtils.findRequiredElement("/html/body/table/thead/tr/td", root).setTextContent(name);
Element tbody = XmlUtils.findRequiredElement("/html/body/table/tbody", root);
tbody.appendChild(openCommand(selenium, serverURL + projectMetadata.getProjectName().toLowerCase() + "/"));
tbody.appendChild(clickAndWaitCommand(selenium, "link=Create new " + beanInfoMetadata.getJavaBean().getSimpleTypeName()));
for (FieldMetadata field : getEligableFields()) {
if (!field.getFieldType().isCommonCollectionType() && !isSpecialType(field.getFieldType())) {
tbody.appendChild(typeCommand(selenium, field));
} else {
// tbody.appendChild(typeKeyCommand(selenium, field));
}
}
tbody.appendChild(clickAndWaitCommand(selenium, "//input[@value='Save']" ));
XmlUtils.writeXml(seleniumMutableFile.getOutputStream(), selenium);
manageTestSuite(relativeTestFilePath, name, serverURL);
installMavenPlugin();
}
private void manageTestSuite(String testPath, String name, String serverURL) {
String relativeTestFilePath = "selenium/test-suite.xhtml";
String seleniumPath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, relativeTestFilePath);
MutableFile seleniumMutableFile = null;
Document suite;
try {
if (fileManager.exists(seleniumPath)) {
seleniumMutableFile = fileManager.updateFile(seleniumPath);
suite = XmlUtils.getDocumentBuilder().parse(seleniumMutableFile.getInputStream());
} else {
seleniumMutableFile = fileManager.createFile(seleniumPath);
InputStream templateInputStream = TemplateUtils.getTemplate(getClass(), "selenium-test-suite-template.xhtml");
Assert.notNull(templateInputStream, "Could not acquire selenium test suite template");
suite = XmlUtils.getDocumentBuilder().parse(templateInputStream);
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
ProjectMetadata projectMetadata = (ProjectMetadata) metadataService.get(ProjectMetadata.getProjectIdentifier());
Assert.notNull(projectMetadata, "Unable to obtain project metadata");
Element root = (Element) suite.getLastChild();
XmlUtils.findRequiredElement("/html/head/title", root).setTextContent("Test suite for " + projectMetadata.getProjectName() + "project");
Element tr = suite.createElement("tr");
Element td = suite.createElement("td");
tr.appendChild(td);
Element a = suite.createElement("a");
a.setAttribute("href", serverURL + projectMetadata.getProjectName().toLowerCase() + "/static/" + testPath);
a.setTextContent(name);
td.appendChild(a);
XmlUtils.findRequiredElement("/html/body/table", root).appendChild(tr);
XmlUtils.writeXml(seleniumMutableFile.getOutputStream(), suite);
menuOperations.addMenuItem(
"selenium_category",
"Selenium Tests",
"selenium_test_suite_menu_item",
"Test suite",
"/" + projectMetadata.getProjectName().toLowerCase() + "/static/" + relativeTestFilePath);
}
private void installMavenPlugin(){
String pomFilePath = "pom.xml";
String pomPath = pathResolver.getIdentifier(Path.ROOT, pomFilePath);
MutableFile pomMutableFile = null;
Document pom;
try {
if (fileManager.exists(pomPath)) {
pomMutableFile = fileManager.updateFile(pomPath);
pom = XmlUtils.getDocumentBuilder().parse(pomMutableFile.getInputStream());
} else {
throw new IllegalStateException("This command cannot be run before a project has been created.");
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
Element root = (Element) pom.getLastChild();
//stop if the plugin is already installed
if (XmlUtils.findFirstElement("/project/build/plugins/plugin[artifactId='selenium-maven-plugin']", root) != null) {
return;
}
//install codehaus plugin snapshot repo until the selenium-maven-plugin (temporary solution until new version of the maven-selenium-plugin is released
Element pluginRepositories = pom.createElement("pluginRepositories");
Element pluginRepository = pom.createElement("pluginRepository");
pluginRepositories.appendChild(pluginRepository);
Element id = pom.createElement("id");
id.setTextContent("Codehaus Snapshots");
pluginRepository.appendChild(id);
Element url = pom.createElement("url");
url.setTextContent("http://snapshots.repository.codehaus.org");
pluginRepository.appendChild(url);
Element snapshots = pom.createElement("snapshots");
Element enabled = pom.createElement("enabled");
enabled.setTextContent("true");
snapshots.appendChild(enabled);
pluginRepository.appendChild(snapshots);
Element releases = pom.createElement("releases");
Element enabled2 = pom.createElement("enabled");
enabled2.setTextContent("true");
releases.appendChild(enabled2);
pluginRepository.appendChild(releases);
Element dependencies = XmlUtils.findRequiredElement("/project/dependencies", root);
Assert.notNull(dependencies, "Could not find the first dependencies element in pom.xml");
dependencies.getParentNode().insertBefore(pluginRepositories, dependencies);
//now install the plugin itself
Element plugin = pom.createElement("plugin");
Element groupId = pom.createElement("groupId");
groupId.setTextContent("org.codehaus.mojo");
plugin.appendChild(groupId);
Element artifactId = pom.createElement("artifactId");
artifactId.setTextContent("selenium-maven-plugin");
plugin.appendChild(artifactId);
Element version = pom.createElement("version");
version.setTextContent("1.0-rc-2-SNAPSHOT");
plugin.appendChild(version);
Element configuration = pom.createElement("configuration");
Element suite = pom.createElement("suite");
String suitePath = pathResolver.getIdentifier(Path.SRC_MAIN_WEBAPP, "selenium/test-suite.xhtml");
suitePath = suitePath.substring(pathResolver.getRoot(Path.ROOT).length()+1);
suite.setTextContent(suitePath);
configuration.appendChild(suite);
Element browser = pom.createElement("browser");
browser.setTextContent("*firefox");
configuration.appendChild(browser);
Element results = pom.createElement("results");
results.setTextContent("${project.build.directory}/target/selenium.txt");
configuration.appendChild(results);
Element startURL = pom.createElement("startURL");
startURL.setTextContent("http://localhost:4444/");
configuration.appendChild(startURL);
plugin.appendChild(configuration);
XmlUtils.findRequiredElement("/project/build/plugins", root).appendChild(plugin);
XmlUtils.writeXml(pomMutableFile.getOutputStream(), pom);
}
private List<FieldMetadata> getEligableFields() {
List<FieldMetadata> fields = new ArrayList<FieldMetadata>();
for (MethodMetadata method : beanInfoMetadata.getPublicAccessors(false)) {
JavaSymbolName propertyName = beanInfoMetadata.getPropertyNameForJavaBeanMethod(method);
FieldMetadata field = beanInfoMetadata.getFieldForPropertyName(propertyName);
if(field != null && hasMutator(field)) {
// Never include id field (it shouldn't normally have a mutator anyway, but the user might have added one)
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Id")) != null) {
continue;
}
// Never include version field (it shouldn't normally have a mutator anyway, but the user might have added one)
if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.persistence.Version")) != null) {
continue;
}
fields.add(field);
}
}
return fields;
}
private boolean hasMutator(FieldMetadata fieldMetadata) {
for (MethodMetadata mutator : beanInfoMetadata.getPublicMutators()) {
if (fieldMetadata.equals(beanInfoMetadata.getFieldForPropertyName(beanInfoMetadata.getPropertyNameForJavaBeanMethod(mutator)))) return true;
}
return false;
}
private Node clickAndWaitCommand(Document document, String linkTarget){
Node tr = document.createElement("tr");
Node td1 = tr.appendChild(document.createElement("td"));
td1.setTextContent("clickAndWait");
Node td2 = tr.appendChild(document.createElement("td"));
td2.setTextContent(linkTarget);
Node td3 = tr.appendChild(document.createElement("td"));
td3.setTextContent(" ");
return tr;
}
private Node typeCommand(Document document, FieldMetadata field){
Node tr = document.createElement("tr");
Node td1 = tr.appendChild(document.createElement("td"));
td1.setTextContent("type");
Node td2 = tr.appendChild(document.createElement("td"));
td2.setTextContent("_" + field.getFieldName().getSymbolName());
Node td3 = tr.appendChild(document.createElement("td"));
td3.setTextContent(convertToInitializer(field));
return tr;
}
private Node typeKeyCommand(Document document, FieldMetadata field){
Node tr = document.createElement("tr");
Node td1 = tr.appendChild(document.createElement("td"));
td1.setTextContent("typeKey");
Node td2 = tr.appendChild(document.createElement("td"));
td2.setTextContent(field.getFieldName().getSymbolName());
Node td3 = tr.appendChild(document.createElement("td"));
td3.setTextContent("1");
return tr;
}
private String convertToInitializer(FieldMetadata field) {
String initializer = " ";
short index = 1;
if (field.getFieldName().getSymbolName().contains("email") || field.getFieldName().getSymbolName().contains("Email")) {
initializer = "some@email.com";
} else if (field.getFieldType().equals(new JavaType(String.class.getName()))) {
initializer = "some" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + index;
} else if (field.getFieldType().equals(new JavaType(Date.class.getName()))) {
if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Past"))) {
initializer = dateFormat.format(new Date(new Date().getTime() - 10000000L));
} else if (null != MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), new JavaType("javax.validation.constraints.Future"))) {
initializer = dateFormat.format(new Date(new Date().getTime() + 10000000L));
} else {
initializer = dateFormat.format(new Date());
}
} else if (field.getFieldType().equals(new JavaType(Boolean.class.getName()))) {
initializer = new Boolean(true).toString();
} else if (field.getFieldType().equals(new JavaType(Integer.class.getName()))) {
initializer = new Integer(index).toString();
} else if (field.getFieldType().equals(new JavaType(Double.class.getName()))) {
initializer = new Double(index).toString();
} else if (field.getFieldType().equals(new JavaType(Float.class.getName()))) {
initializer = new Float(index).toString();
} else if (field.getFieldType().equals(new JavaType(Long.class.getName()))) {
initializer = new Long(index).toString();
} else if (field.getFieldType().equals(new JavaType(Short.class.getName()))) {
initializer = new Short(index).toString();
}
return initializer;
}
private Node openCommand(Document document, String linkTarget){
Node tr = document.createElement("tr");
Node td1 = tr.appendChild(document.createElement("td"));
td1.setTextContent("open");
Node td2 = tr.appendChild(document.createElement("td"));
td2.setTextContent(linkTarget);
Node td3 = tr.appendChild(document.createElement("td"));
td3.setTextContent(" ");
return tr;
}
private boolean isSpecialType(JavaType javaType) {
String physicalTypeIdentifier = PhysicalTypeIdentifier.createIdentifier(javaType, Path.SRC_MAIN_JAVA);
//we are only interested if the type is part of our application and if no editor exists for it already
if (metadataService.get(physicalTypeIdentifier) != null) {
return true;
}
return false;
}
}
|
package com.codenvy.analytics.pig.scripts;
import com.codenvy.analytics.BaseTest;
import com.codenvy.analytics.datamodel.ListValueData;
import com.codenvy.analytics.datamodel.LongValueData;
import com.codenvy.analytics.datamodel.MapValueData;
import com.codenvy.analytics.datamodel.ValueData;
import com.codenvy.analytics.metrics.AbstractMetric;
import com.codenvy.analytics.metrics.Context;
import com.codenvy.analytics.metrics.Metric;
import com.codenvy.analytics.metrics.MetricFactory;
import com.codenvy.analytics.metrics.MetricFilter;
import com.codenvy.analytics.metrics.MetricType;
import com.codenvy.analytics.metrics.Parameters;
import com.codenvy.analytics.metrics.Summaraziable;
import com.codenvy.analytics.metrics.users.UsersStatisticsList;
import com.codenvy.analytics.pig.scripts.util.Event;
import com.codenvy.analytics.pig.scripts.util.LogGenerator;
import com.codenvy.analytics.services.DataComputationFeature;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.testng.Assert.assertEquals;
/** @author <a href="mailto:abazko@codenvy.com">Anatoliy Bazko</a> */
public class TestProductUsageFactorySessions extends BaseTest {
@BeforeClass
public void init() throws Exception {
List<Event> events = new ArrayList<>();
events.add(Event.Builder.createUserCreatedEvent(UID1, "user1@gmail.com", "user1@gmail.com")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createUserCreatedEvent(AUID1, "anonymoususer_1", "anonymoususer_1")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createWorkspaceCreatedEvent(TWID1, "tmp-1", "user1@gmail.com")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createWorkspaceCreatedEvent(TWID2, "tmp-2", "user1@gmail.com")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createWorkspaceCreatedEvent(TWID3, "tmp-3", "anonymoususer_1")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(
Event.Builder
.createFactoryUrlAcceptedEvent("tmp-1", "factoryUrl1", "http://referrer1", "org1", "affiliate1", "named", "acceptor")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(
Event.Builder
.createFactoryUrlAcceptedEvent("tmp-2", "factoryUrl1", "http://referrer2", "org2", "affiliate1", "temp", "owner")
.withDate("2013-02-10").withTime("10:20:00").build());
events.add(
Event.Builder
.createFactoryUrlAcceptedEvent("tmp-3", "http:
.withDate("2013-02-10").withTime("11:00:00").build());
events.add(Event.Builder.createFactoryProjectImportedEvent("user1@gmail.com", "tmp-1", "project", "type")
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createSessionUsageEvent("user1@gmail.com", "tmp-1", "id1", true)
.withDate("2013-02-10").withTime("10:00:00").build());
events.add(Event.Builder.createSessionUsageEvent("user1@gmail.com", "tmp-1", "id1", true)
.withDate("2013-02-10").withTime("10:05:00").build());
events.add(Event.Builder.createSessionUsageEvent("user1@gmail.com", "tmp-2", "id2", true)
.withDate("2013-02-10").withTime("10:20:00").build());
events.add(Event.Builder.createSessionUsageEvent("user1@gmail.com", "tmp-2", "id2", true)
.withDate("2013-02-10").withTime("10:40:00").build());
events.add(Event.Builder.createSessionUsageEvent("anonymoususer_1", "tmp-3", "id3", true)
.withDate("2013-02-10").withTime("11:00:00").build());
events.add(Event.Builder.createSessionUsageEvent("anonymoususer_1", "tmp-3", "id3", true)
.withDate("2013-02-10").withTime("11:15:00").build());
// run event for session
events.add(Event.Builder.createRunStartedEvent("user1@gmail.com", "tmp-1", "project", "type", "id1", "60000", "128")
.withDate("2013-02-10").withTime("10:03:00").build());
/** BUILD EVENTS */
// #1 2min, stopped normally
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:00:00")
.withParam("EVENT", "build-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project1")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_b")
.withParam("TIMEOUT", "600")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:02:00")
.withParam("EVENT", "build-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project1")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_b")
.withParam("TIMEOUT", "600")
.build());
// #2 1m, stopped normally
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:10:00")
.withParam("EVENT", "build-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project2")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_b")
.withParam("TIMEOUT", "-1")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:11:00")
.withParam("EVENT", "build-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project2")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_b")
.withParam("TIMEOUT", "-1")
.build());
/** RUN EVENTS */
// #1 2min, stopped by user
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:20:00")
.withParam("EVENT", "run-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project1")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_r")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "600")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:22:00")
.withParam("EVENT", "run-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project1")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_r")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "600")
.build());
// #2 1m, stopped by user
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:30:00")
.withParam("EVENT", "run-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project2")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_r")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "-1")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:32:00")
.withParam("EVENT", "run-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project2")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_r")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "-1")
.build());
/** DEBUGS EVENTS */
// #1 2min, stopped by user
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:40:00")
.withParam("EVENT", "debug-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_d")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "600")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:42:00")
.withParam("EVENT", "debug-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project")
.withParam("TYPE", "projectType")
.withParam("ID", "id1_d")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "600")
.build());
// #2 1m, stopped by user
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:50:00")
.withParam("EVENT", "debug-started")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_d")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "-1")
.build());
events.add(new Event.Builder().withDate("2013-02-10")
.withTime("12:51:00")
.withParam("EVENT", "debug-finished")
.withParam("WS", "tmp-3")
.withParam("USER", "anonymoususer_1")
.withParam("PROJECT", "project")
.withParam("TYPE", "projectType")
.withParam("ID", "id2_d")
.withParam("MEMORY", "128")
.withParam("LIFETIME", "-1")
.build());
File log = LogGenerator.generateLog(events);
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
builder.put(Parameters.LOG, log.getAbsolutePath());
Context context = builder.build();
builder.putAll(scriptsManager.getScript(ScriptType.USERS_PROFILES, MetricType.USERS_PROFILES_LIST).getParamsAsMap());
pigServer.execute(ScriptType.USERS_PROFILES, context);
builder.putAll(scriptsManager.getScript(ScriptType.WORKSPACES_PROFILES, MetricType.WORKSPACES_PROFILES_LIST).getParamsAsMap());
pigServer.execute(ScriptType.WORKSPACES_PROFILES, context);
builder.putAll(scriptsManager.getScript(ScriptType.ACCEPTED_FACTORIES, MetricType.FACTORIES_ACCEPTED_LIST).getParamsAsMap());
pigServer.execute(ScriptType.ACCEPTED_FACTORIES, context);
builder.putAll(scriptsManager.getScript(ScriptType.TASKS, MetricType.TASKS_LIST).getParamsAsMap());
pigServer.execute(ScriptType.TASKS, context);
builder.putAll(scriptsManager.getScript(ScriptType.PRODUCT_USAGE_FACTORY_SESSIONS, MetricType.PRODUCT_USAGE_FACTORY_SESSIONS_LIST).getParamsAsMap());
pigServer.execute(ScriptType.PRODUCT_USAGE_FACTORY_SESSIONS, context);
builder.putAll(scriptsManager.getScript(ScriptType.CREATED_TEMPORARY_WORKSPACES, MetricType.TEMPORARY_WORKSPACES_CREATED).getParamsAsMap());
pigServer.execute(ScriptType.CREATED_TEMPORARY_WORKSPACES, context);
doIntegrity("20130210");
DataComputationFeature dataComputationFeature = new DataComputationFeature();
dataComputationFeature.forceExecute(context);
}
@Test
public void testSingleDateFilter() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_PRODUCT_USAGE_TIME_TOTAL);
assertEquals(metric.getValue(builder.build()), new LongValueData(2400000L));
metric = MetricFactory.getMetric(MetricType.FACTORY_SESSIONS);
assertEquals(metric.getValue(builder.build()), new LongValueData(3));
metric = MetricFactory.getMetric(MetricType.AUTHENTICATED_FACTORY_SESSIONS);
assertEquals(metric.getValue(builder.build()), new LongValueData(2));
metric = MetricFactory.getMetric(MetricType.CONVERTED_FACTORY_SESSIONS);
assertEquals(metric.getValue(builder.build()), new LongValueData(1));
}
@Test
public void testUserFilter() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
builder.put(MetricFilter.REFERRER, "referrer1");
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_PRODUCT_USAGE_TIME_TOTAL);
assertEquals(metric.getValue(builder.build()), new LongValueData(300000L));
}
@Test
public void testAbstractFactorySessions() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_SESSIONS_BELOW_10_MIN);
assertEquals(metric.getValue(builder.build()), new LongValueData(1));
}
@Test
public void testShouldReturnCountSessionsWithRun() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_SESSIONS_WITH_RUN);
assertEquals(metric.getValue(builder.build()), LongValueData.valueOf(1));
}
@Test
public void testShouldReturnAllTWC() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
Metric metric = MetricFactory.getMetric(MetricType.TEMPORARY_WORKSPACES_CREATED);
assertEquals(metric.getValue(builder.build()), LongValueData.valueOf(3));
}
@Test
public void testShouldReturnTWCForSpecificOrgId() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
builder.put(MetricFilter.ORG_ID, "org1");
Metric metric = MetricFactory.getMetric(MetricType.TEMPORARY_WORKSPACES_CREATED);
assertEquals(metric.getValue(builder.build()), LongValueData.valueOf(1));
}
@Test
public void testShouldReturnTWCForSpecificAffiliateId() throws Exception {
Context.Builder builder = new Context.Builder();
builder.put(Parameters.FROM_DATE, "20130210");
builder.put(Parameters.TO_DATE, "20130210");
builder.put(MetricFilter.AFFILIATE_ID, "affiliate1");
Metric metric = MetricFactory.getMetric(MetricType.TEMPORARY_WORKSPACES_CREATED);
assertEquals(metric.getValue(builder.build()), LongValueData.valueOf(2));
}
@Test
public void testSummarizedFactorySessions() throws Exception {
Summaraziable metric = (Summaraziable)MetricFactory.getMetric(MetricType.PRODUCT_USAGE_FACTORY_SESSIONS_LIST);
ListValueData summaryValue = (ListValueData)metric.getSummaryValue(Context.EMPTY);
assertEquals(summaryValue.size(), 1);
Map<String, ValueData> summary = ((MapValueData)summaryValue.getAll().get(0)).getAll();
assertEquals(summary.get(UsersStatisticsList.SESSIONS).getAsString(), "3");
assertEquals(summary.get(UsersStatisticsList.TIME).getAsString(), "2400000");
assertEquals(summary.get(UsersStatisticsList.AUTHENTICATED_SESSION).getAsString(), "2");
assertEquals(summary.get(UsersStatisticsList.CONVERTED_SESSION).getAsString(), "1");
}
@Test
public void testSummarizedFactoryStatistics() throws Exception {
Summaraziable metric = (Summaraziable)MetricFactory.getMetric(MetricType.FACTORY_STATISTICS_LIST);
ListValueData summaryValue = (ListValueData)metric.getSummaryValue(Context.EMPTY);
// verify summary data on metric FACTORY_STATISTICS_LIST_PRECOMPUTED
assertEquals(summaryValue.size(), 1);
Map<String, ValueData> summary = ((MapValueData)summaryValue.getAll().get(0)).getAll();
assertEquals(summary.get(UsersStatisticsList.SESSIONS).getAsString(), "3");
assertEquals(summary.get(UsersStatisticsList.TIME).getAsString(), "2400000");
assertEquals(summary.get(UsersStatisticsList.RUNS).getAsString(), "1");
assertEquals(summary.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(summary.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(summary.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(summary.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0767");
assertEquals(summary.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0085");
assertEquals(summary.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0064");
assertEquals(summary.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0062");
// verify the same summary data on metric FACTORY_STATISTICS_LIST
Context.Builder builder = new Context.Builder();
builder.put(Parameters.DATA_COMPUTATION_PROCESS, 1); // notes don't read precomputed data
summaryValue = (ListValueData)metric.getSummaryValue(builder.build());
assertEquals(summaryValue.size(), 1);
summary = ((MapValueData)summaryValue.getAll().get(0)).getAll();
assertEquals(summary.get(UsersStatisticsList.SESSIONS).getAsString(), "3");
assertEquals(summary.get(UsersStatisticsList.TIME).getAsString(), "2400000");
assertEquals(summary.get(UsersStatisticsList.RUNS).getAsString(), "1");
assertEquals(summary.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(summary.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(summary.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(summary.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0768");
assertEquals(summary.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0085");
assertEquals(summary.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0064");
assertEquals(summary.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0062");
}
@Test
public void testFactoryRoutingFlags() throws IOException {
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_STATISTICS_LIST);
List<ValueData> values = ((ListValueData) metric.getValue(Context.EMPTY)).getAll();
assertEquals(values.size(), 2);
Map<String, ValueData> m = ((MapValueData)values.get(0)).getAll();
assertEquals(m.get(AbstractMetric.FACTORY).getAsString(), "http://1.com?id=factory3");
assertEquals(m.get(AbstractMetric.FACTORY_ROUTING_FLAGS).getAsString(), "named");
assertEquals(m.get(UsersStatisticsList.SESSIONS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.TIME).getAsString(), "900000");
assertEquals(m.get(UsersStatisticsList.RUNS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(m.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0768");
assertEquals(m.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0085");
assertEquals(m.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0064");
assertEquals(m.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0062");
m = ((MapValueData)values.get(1)).getAll();
assertEquals(m.get(AbstractMetric.FACTORY).getAsString(), "factoryUrl1");
assertEquals(m.get(AbstractMetric.FACTORY_ROUTING_FLAGS).getAsString(), "temp+owner");
assertEquals(m.get(UsersStatisticsList.SESSIONS).getAsString(), "2");
assertEquals(m.get(UsersStatisticsList.TIME).getAsString(), "1500000");
assertEquals(m.get(UsersStatisticsList.RUNS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(m.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
}
@Test
public void testFilteringWsTypeAndLocation() throws IOException {
Context.Builder builder = new Context.Builder();
builder.put(MetricFilter.WS_TYPE, "temp");
builder.put(MetricFilter.WS_LOCATION, "owner");
Context context = builder.build();
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_STATISTICS_LIST);
List<ValueData> values = ((ListValueData) metric.getValue(context)).getAll();
assertEquals(values.size(), 1);
Map<String, ValueData> m = ((MapValueData)values.get(0)).getAll();
assertEquals(m.get(AbstractMetric.FACTORY).getAsString(), "factoryUrl1");
assertEquals(m.get(AbstractMetric.FACTORY_ROUTING_FLAGS).getAsString(), "temp+owner");
assertEquals(m.get(UsersStatisticsList.SESSIONS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.TIME).getAsString(), "1200000");
assertEquals(m.get(UsersStatisticsList.RUNS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(m.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
}
@Test
public void testFilteringWsType() throws IOException {
Context.Builder builder = new Context.Builder();
builder.put(MetricFilter.WS_TYPE, "named");
Context context = builder.build();
Metric metric = MetricFactory.getMetric(MetricType.FACTORY_STATISTICS_LIST);
List<ValueData> values = ((ListValueData) metric.getValue(context)).getAll();
assertEquals(values.size(), 2);
Map<String, ValueData> m = ((MapValueData)values.get(0)).getAll();
assertEquals(m.get(AbstractMetric.FACTORY).getAsString(), "http://1.com?id=factory3");
assertEquals(m.get(AbstractMetric.FACTORY_ROUTING_FLAGS).getAsString(), "named");
assertEquals(m.get(UsersStatisticsList.SESSIONS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.TIME).getAsString(), "900000");
assertEquals(m.get(UsersStatisticsList.RUNS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(m.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0768");
assertEquals(m.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0085");
assertEquals(m.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0064");
assertEquals(m.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0062");
m = ((MapValueData)values.get(1)).getAll();
assertEquals(m.get(AbstractMetric.FACTORY).getAsString(), "factoryUrl1");
assertEquals(m.get(AbstractMetric.FACTORY_ROUTING_FLAGS).getAsString(), "named+acceptor");
assertEquals(m.get(UsersStatisticsList.SESSIONS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.TIME).getAsString(), "300000");
assertEquals(m.get(UsersStatisticsList.RUNS).getAsString(), "1");
assertEquals(m.get(UsersStatisticsList.DEBUGS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.BUILDS).getAsString(), "0");
assertEquals(m.get(UsersStatisticsList.DEPLOYS).getAsString(), "0");
assertEquals(m.get(AbstractMetric.BUILDS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.RUNS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.DEBUGS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
assertEquals(m.get(AbstractMetric.EDITS_GIGABYTE_RAM_HOURS).getAsString(), "0.0");
}
}
|
package uk.ac.ebi.quickgo.annotation.download.converter;
import uk.ac.ebi.quickgo.annotation.download.converter.helpers.Extensions;
import uk.ac.ebi.quickgo.annotation.model.Annotation;
import uk.ac.ebi.quickgo.annotation.download.converter.helpers.GeneProductId;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.function.BiFunction;
import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.toList;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.Date.toYYYYMMDD;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.Helper.nullToEmptyString;
import static uk.ac.ebi.quickgo.annotation.download.converter.helpers.ConnectedXRefs.asString;
public class AnnotationToGPAD implements BiFunction<Annotation, List<String>, List<String>> {
private static final String GO_EVIDENCE = "goEvidence=";
private static final String OUTPUT_DELIMITER = "\t";
@Override
public List<String> apply(Annotation annotation, List<String> selectedFields) {
if (Objects.isNull(annotation.slimmedIds) || annotation.slimmedIds.isEmpty()) {
return Collections.singletonList(toOutputRecord(annotation, annotation.goId));
} else {
return annotation.slimmedIds.stream()
.map(goId -> this.toOutputRecord(annotation, goId))
.collect(toList());
}
}
private String toOutputRecord(Annotation annotation, String goId) {
StringJoiner tsvJoiner = new StringJoiner(OUTPUT_DELIMITER);
final GeneProductId geneProductId = GeneProductId.fromString(annotation.geneProductId);
return tsvJoiner
.add(ofNullable(geneProductId.db).orElse(""))
.add(ofNullable(geneProductId.id).orElse(""))
.add(nullToEmptyString.apply(annotation.qualifier))
.add(nullToEmptyString.apply(goId))
.add(nullToEmptyString.apply(annotation.reference))
.add(nullToEmptyString.apply(annotation.evidenceCode))
.add(asString(annotation.withFrom))
.add(taxonIdAsString(annotation.interactingTaxonId))
.add(ofNullable(annotation.date).map(toYYYYMMDD).orElse(""))
.add(nullToEmptyString.apply(annotation.assignedBy))
.add(Extensions.asString(annotation.extensions))
.add(GO_EVIDENCE + nullToEmptyString.apply(annotation.goEvidence)).toString();
}
private static final int LOWEST_VALID_TAXON_ID = 1;
private String taxonIdAsString(int taxonId) {
return taxonId < LOWEST_VALID_TAXON_ID ? "" : Integer.toString(taxonId);
}
}
|
package com.axelor.apps.prestashop.imports;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerException;
import org.apache.commons.io.output.StringBuilderWriter;
import org.apache.tika.io.IOUtils;
import com.axelor.apps.base.db.Batch;
import com.axelor.apps.prestashop.imports.service.ImportAddressService;
import com.axelor.apps.prestashop.imports.service.ImportCategoryService;
import com.axelor.apps.prestashop.imports.service.ImportCountryService;
import com.axelor.apps.prestashop.imports.service.ImportCurrencyService;
import com.axelor.apps.prestashop.imports.service.ImportCustomerService;
import com.axelor.apps.prestashop.imports.service.ImportOrderDetailService;
import com.axelor.apps.prestashop.imports.service.ImportOrderService;
import com.axelor.apps.prestashop.imports.service.ImportProductService;
import com.axelor.apps.prestashop.service.library.PrestaShopWebserviceException;
import com.axelor.meta.MetaFiles;
import com.axelor.meta.db.MetaFile;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import wslite.json.JSONException;
@Singleton
public class PrestaShopServiceImportImpl implements PrestaShopServiceImport {
private MetaFiles metaFiles;
private ImportCurrencyService currencyService;
private ImportCountryService countryService;
private ImportCustomerService customerService;
private ImportAddressService addressService;
private ImportCategoryService categoryService;
private ImportProductService productService;
private ImportOrderService orderService;
private ImportOrderDetailService orderDetailService;
@Inject
public PrestaShopServiceImportImpl(MetaFiles metaFiles, ImportCurrencyService currencyService, ImportCountryService countryService,
ImportCustomerService customerService, ImportAddressService addressService,
ImportCategoryService categoryService, ImportProductService productService, ImportOrderService orderService,
ImportOrderDetailService orderDetailService) throws IOException {
this.metaFiles = metaFiles;
this.currencyService = currencyService;
this.countryService = countryService;
this.customerService = customerService;
this.addressService = addressService;
this.categoryService = categoryService;
this.productService = productService;
this.orderService = orderService;
this.orderDetailService = orderDetailService;
}
/**
* Import base module from prestashop
*
* @throws IOException
* @throws PrestaShopWebserviceException
* @throws TransformerException
* @throws JAXBException
* @throws JSONException
*/
public void importAxelorBase(final BufferedWriter logBuffer) throws IOException, PrestaShopWebserviceException, TransformerException, JAXBException, JSONException {
currencyService.importCurrency(logBuffer);
countryService.importCountry(logBuffer);
customerService.importCustomer(logBuffer);
addressService.importAddress(logBuffer);
categoryService.importCategory(logBuffer);
productService.importProduct(logBuffer);
}
/**
* Import Axelor modules (Base, SaleOrder)
*/
@Override
public Batch importPrestShop(Batch batch) throws IOException, PrestaShopWebserviceException, TransformerException, JAXBException, JSONException {
StringBuilderWriter logWriter = new StringBuilderWriter(1024);
BufferedWriter bufferedWriter = new BufferedWriter(logWriter); // FIXME remove once refactored
try {
importAxelorBase(bufferedWriter);
orderService.importOrder(bufferedWriter);
orderDetailService.importOrderDetail(bufferedWriter);
logWriter.write(String.format("%n==== END OF LOG ====%n"));
} finally {
IOUtils.closeQuietly(bufferedWriter);
MetaFile importMetaFile = metaFiles.upload(new ByteArrayInputStream(logWriter.toString().getBytes()), "import-log.txt");
batch.setPrestaShopBatchLog(importMetaFile);
}
return batch;
}
}
|
package org.ovirt.engine.core.vdsbroker;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.businessentities.Cluster;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDynamic;
import org.ovirt.engine.core.common.businessentities.VmExitStatus;
import org.ovirt.engine.core.common.businessentities.VmJob;
import org.ovirt.engine.core.common.businessentities.VmStatic;
import org.ovirt.engine.core.common.businessentities.VmStatistics;
import org.ovirt.engine.core.common.vdscommands.DestroyVmVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSParametersBase;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogableBase;
import org.ovirt.engine.core.dao.ClusterDao;
import org.ovirt.engine.core.dao.VdsDao;
import org.ovirt.engine.core.dao.VmDao;
import org.ovirt.engine.core.dao.VmDynamicDao;
import org.ovirt.engine.core.dao.VmJobDao;
import org.ovirt.engine.core.dao.VmStaticDao;
import org.ovirt.engine.core.dao.VmStatisticsDao;
import org.ovirt.engine.core.dao.network.VmNetworkInterfaceDao;
@RunWith(Theories.class)
public class VmAnalyzerTest {
@DataPoints
public static VmTestPairs[] VMS = VmTestPairs.values();
VmAnalyzer vmAnalyzer;
@Mock
VmsMonitoring vmsMonitoring;
@Mock
private AuditLogDirector auditLogDirector;
@Captor
private ArgumentCaptor<AuditLogableBase> loggableCaptor;
@Captor
private ArgumentCaptor<AuditLogType> logTypeCaptor;
@Captor
private ArgumentCaptor<VDSCommandType> vdsCommandTypeCaptor;
@Captor
private ArgumentCaptor<VDSParametersBase> vdsParamsCaptor;
@Mock
private VmStatisticsDao vmStatisticsDao;
@Mock
private VmStaticDao vmStaticDao;
@Mock
private VmDynamicDao vmDynamicDao;
@Mock
private Cluster cluster;
@Mock
private ClusterDao clusterDao;
@Mock
private VdsDao vdsDao;
@Mock
private VDS srcHost;
@Mock
private VDS dstHost;
@Mock
private DbFacade dbFacade;
@Mock
private VdsManager vdsManager;
@Mock
private VmManager vmManager;
@Mock
private VDS vdsManagerVds;
@Mock
private ResourceManager resourceManager;
@Mock
private VmJobDao vmJobsDao;
@Mock
private VmDao vmDao;
@Mock
private VmNetworkInterfaceDao vmNetworkInterfaceDao;
@Theory
public void externalVMWhenMissingInDb(VmTestPairs data) {
//given
initMocks(data, false);
mockVmStatic(false);
mockVmNotInDb(data);
//when
assumeTrue(data.dbVm() == null);
assumeTrue(data.vdsmVm() != null);
//then
vmAnalyzer.analyze();
assertTrue(vmAnalyzer.isExternalVm());
}
@Theory
public void vmNotRunningOnHost(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeTrue(data.vdsmVm() == null);
//then
vmAnalyzer.analyze();
assertTrue(vmAnalyzer.isMovedToDown());
}
@Theory
public void proceedDownVmsNormalExistReason_MIGRATION_HANDOVER(VmTestPairs data) {
//given
initMocks(data, false);
if (data.dbVm() != null) {
when(vmsMonitoring.getDbFacade()
.getVmStatisticsDao()
.get(data.dbVm().getId())).thenReturn(data.dbVm().getStatisticsData());
}
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
assumeTrue(data.dbVm().getStatus() == VMStatus.MigratingFrom);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Down);
assumeTrue(data.vdsmVm().getVmDynamic().getExitStatus() == VmExitStatus.Normal);
//then
vmAnalyzer.analyze();
verify(auditLogDirector, atLeastOnce()).log(loggableCaptor.capture(), logTypeCaptor.capture());
verify(vmsMonitoring.getResourceManager(), never()).removeAsyncRunningVm(data.dbVm().getId());
verify(vmsMonitoring.getResourceManager()).runVdsCommand(vdsCommandTypeCaptor.capture(),
vdsParamsCaptor.capture());
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
assertEquals(VDSCommandType.Destroy, vdsCommandTypeCaptor.getValue());
assertEquals(DestroyVmVDSCommandParameters.class, vdsParamsCaptor.getValue().getClass());
}
@Theory
public void proceedDownVmsNormalExistReason(VmTestPairs data) {
//given
initMocks(data, false);
if (data.dbVm() != null) {
when(vmsMonitoring.getDbFacade()
.getVmStatisticsDao()
.get(data.dbVm().getId())).thenReturn(data.dbVm().getStatisticsData());
}
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
assumeTrue(data.dbVm().getStatus() != VMStatus.MigratingFrom);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Down);
assumeTrue(data.vdsmVm().getVmDynamic().getExitStatus() == VmExitStatus.Normal);
//then
vmAnalyzer.analyze();
verify(auditLogDirector, atLeastOnce()).log(loggableCaptor.capture(), logTypeCaptor.capture());
verify(vmsMonitoring.getResourceManager()).removeAsyncRunningVm(data.dbVm().getId());
verify(vmsMonitoring.getResourceManager()).runVdsCommand(vdsCommandTypeCaptor.capture(),
vdsParamsCaptor.capture());
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
assertTrue(logTypeCaptor.getAllValues().contains(AuditLogType.VM_DOWN));
assertEquals(VDSCommandType.Destroy, vdsCommandTypeCaptor.getValue());
assertEquals(vdsParamsCaptor.getValue().getClass(), DestroyVmVDSCommandParameters.class);
}
@Theory
public void proceedDownVmsErrorExitReason(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Down);
assumeTrue(data.vdsmVm().getVmDynamic().getExitStatus() != VmExitStatus.Normal);
//then
vmAnalyzer.analyze();
verify(auditLogDirector, atLeastOnce()).log(loggableCaptor.capture(), logTypeCaptor.capture());
verify(vmsMonitoring.getResourceManager(), atLeast(3)).isVmInAsyncRunningList(data.dbVm().getId());
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
}
@Theory
public void proceedWatchdogEvents(VmTestPairs data) {
//given
initMocks(data, true);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
//then
verify(auditLogDirector, atLeastOnce()).log(loggableCaptor.capture(), logTypeCaptor.capture());
assertTrue(logTypeCaptor.getAllValues().contains(AuditLogType.WATCHDOG_EVENT));
}
@Theory
public void proceedBalloonCheck(VmTestPairs data) {
//given
initMocks(data, true);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
//then
verify(auditLogDirector, atLeastOnce()).log(loggableCaptor.capture(), logTypeCaptor.capture());
assertTrue(logTypeCaptor.getAllValues().contains(AuditLogType.WATCHDOG_EVENT));
}
@Theory
public void vmNotRunningOnHostWithBalloonEnabled(VmTestPairs data) {
//given
initMocks(data, false);
when(vdsManagerVds.isBalloonEnabled()).thenReturn(true);
//when
assumeTrue(data.vdsmVm() == null);
//then
vmAnalyzer.analyze();
assertTrue(vmAnalyzer.isMovedToDown());
}
@Theory
public void proceedGuaranteedMemoryCheck() {
//TODO add tests here
}
@Theory
public void updateRepository_MIGRATION_FROM(VmTestPairs data) {
//given
initMocks(data, true);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
// when vm is migrating
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.MigratingFrom);
//then
assertTrue(vmAnalyzer.isClientIpChanged());
verify(vmsMonitoring.getResourceManager(), never()).internalSetVmStatus(data.dbVm(),
VMStatus.MigratingTo);
}
@Theory
public void updateRepository_MIGRATION_FROM_TO_DOWN(VmTestPairs data) {
//given
initMocks(data, true);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
// when vm ended migration
assumeTrue(data.dbVm().getStatus() == VMStatus.MigratingFrom);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Down);
//then
verify(vmsMonitoring.getResourceManager(), times(1)).internalSetVmStatus(data.dbVm(),
VMStatus.MigratingTo);
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
assertNotNull(vmAnalyzer.getVmStatisticsToSave());
assertEquals(VmTestPairs.DST_HOST_ID, data.dbVm().getRunOnVds());
}
@Theory
public void updateRepository_MIGRATION_FROM_TO_UP(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
// when migration failed
assumeTrue(data.dbVm().getStatus() == VMStatus.MigratingFrom);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Up);
//then
vmAnalyzer.analyze();
verify(vmsMonitoring.getResourceManager(), times(1)).removeVmFromDownVms(VmTestPairs.SRC_HOST_ID,
data.vdsmVm().getVmDynamic().getId());
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
assertEquals(VmTestPairs.SRC_HOST_ID, data.dbVm().getRunOnVds());
assertTrue(vmAnalyzer.isRerun());
assertNull(data.dbVm().getMigratingToVds());
}
@Theory
public void updateRepository_HA_VM_DOWN(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeNotNull(data.dbVm(), data.vdsmVm());
// when migration failed
assumeTrue(data.dbVm().getStatus() == VMStatus.Up);
assumeTrue(data.dbVm().isAutoStartup());
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Down);
//then
vmAnalyzer.analyze();
assertEquals(data.dbVm().getDynamicData(), vmAnalyzer.getVmDynamicToSave());
assertNotNull(vmAnalyzer.getVmStatisticsToSave());
assertEquals(VmTestPairs.SRC_HOST_ID, data.dbVm().getRunOnVds());
assertNull(data.vdsmVm().getVmDynamic().getRunOnVds());
assertFalse(vmAnalyzer.isRerun());
assertTrue(vmAnalyzer.isAutoVmToRun());
assertNull(data.dbVm().getMigratingToVds());
}
@Theory
public void updateRepository_PERSIST_DST_UP_VMS(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeNotNull(data.vdsmVm());
assumeTrue(data.vdsmVm().getVmDynamic().getRunOnVds() == VmTestPairs.DST_HOST_ID);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.Up);
//then
vmAnalyzer.analyze();
assertNotNull(vmAnalyzer.getVmDynamicToSave());
assertNotEquals(data.vdsmVm().getVmDynamic(), vmAnalyzer.getVmDynamicToSave());
}
@Theory
public void updateRepository_PERSIST_ALL_VMS_EXCEPT_MIGRATING_TO(VmTestPairs data) {
//given
initMocks(data, false);
//when
assumeNotNull(data.vdsmVm());
assumeTrue(data.vdsmVm().getVmDynamic().getRunOnVds() == VmTestPairs.DST_HOST_ID);
assumeTrue(data.vdsmVm().getVmDynamic().getStatus() == VMStatus.MigratingTo);
//then
vmAnalyzer.analyze();
assertNull(vmAnalyzer.getVmDynamicToSave());
}
@Theory
public void prepareGuestAgentNetworkDevicesForUpdate() {
// TODO add tests
}
@Theory
public void updateLunDisks() {
}
@Before
public void before() {
for (VmTestPairs data: VmTestPairs.values()) {
data.reset();
}
MockitoAnnotations.initMocks(this);
}
public void initMocks(VmTestPairs vmData, boolean run) {
stubDaos();
when(vdsManager.getVdsId()).thenReturn(VmTestPairs.SRC_HOST_ID);
when(vdsManager.getClusterId()).thenReturn(VmTestPairs.CLUSTER_ID);
when(vdsManager.getCopyVds()).thenReturn(vdsManagerVds);
when(vmManager.isColdReboot()).thenReturn(false);
when(vmsMonitoring.getVdsManager()).thenReturn(vdsManager);
when(vmsMonitoring.getVmManager(any())).thenReturn(vmManager);
when(vmsMonitoring.getResourceManager()).thenReturn(resourceManager);
when(resourceManager.getVdsManager(any(Guid.class))).thenReturn(vdsManager);
VDSReturnValue vdsReturnValue = new VDSReturnValue();
vdsReturnValue.setSucceeded(true);
when(vmsMonitoring.getResourceManager().runVdsCommand((VDSCommandType) anyObject(),
(org.ovirt.engine.core.common.vdscommands.VDSParametersBase) anyObject())).thenReturn(
vdsReturnValue);
// -- default behaviors --
// dst host is up
mockDstHostStatus(VDSStatus.Up);
// dst VM is in DB under the same Guid
mockVmInDbForDstVms(vmData);
// -- end of behaviors --
vmAnalyzer = new VmAnalyzer(vmData.dbVm(), vmData.vdsmVm(), vmsMonitoring, auditLogDirector);
if (run) {
vmAnalyzer.analyze();
}
}
private void stubDaos() {
mockStatistics();
mockVmDynamic();
mockVmStatic(true);
mockVmJob();
mockCluster();
mockVdsDao();
doReturn(dbFacade).when(vmsMonitoring).getDbFacade();
doReturn(vmStatisticsDao).when(dbFacade).getVmStatisticsDao();
doReturn(vmDynamicDao).when(dbFacade).getVmDynamicDao();
doReturn(vmStaticDao).when(dbFacade).getVmStaticDao();
doReturn(vmNetworkInterfaceDao).when(dbFacade).getVmNetworkInterfaceDao();
doReturn(vmJobsDao).when(dbFacade).getVmJobDao();
doReturn(clusterDao).when(dbFacade).getClusterDao();
doReturn(vdsDao).when(dbFacade).getVdsDao();
doReturn(vmDao).when(dbFacade).getVmDao();
}
private void mockStatistics() {
when(vmStatisticsDao.get((Guid) anyObject())).thenReturn(mock(VmStatistics.class));
}
private void mockVmDynamic() {
when(vmDynamicDao.get((Guid) anyObject())).thenReturn(mock(VmDynamic.class));
}
private void mockVmStatic(boolean stubExists) {
Mockito.reset(vmStaticDao);
when(vmStaticDao.get((Guid) anyObject())).thenReturn(stubExists ? mock(VmStatic.class) : null);
}
private void mockVmJob() {
Mockito.reset(vmJobsDao);
when(vmJobsDao.get((Guid) anyObject())).thenReturn(mock(VmJob.class));
}
private void mockCluster() {
when(clusterDao.get(VmTestPairs.CLUSTER_ID)).thenReturn(cluster);
}
private void mockVdsDao() {
when(vdsDao.get(VmTestPairs.SRC_HOST_ID)).thenReturn(srcHost);
when(vdsDao.get(VmTestPairs.DST_HOST_ID)).thenReturn(dstHost);
}
private void mockDstHostStatus(VDSStatus status) {
when(dstHost.getStatus()).thenReturn(status);
}
private void mockVmInDbForDstVms(VmTestPairs vmData) {
if (vmData.dbVm() == null && vmData.vdsmVm() != null) {
VM dbVm = vmData.createDbVm();
when(vmDao.get(vmData.vdsmVm().getVmDynamic().getId()))
.thenReturn(dbVm);
}
}
private void mockVmNotInDb(VmTestPairs vmData) {
if (vmData.vdsmVm() != null) {
when(vmDao.get(vmData.vdsmVm().getVmDynamic().getId()))
.thenReturn(null);
}
}
}
|
package org.intermine.bio.dataconversion;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.intermine.dataconversion.FileConverter;
import org.intermine.dataconversion.ItemWriter;
import org.intermine.metadata.Model;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.util.SAXParser;
import org.intermine.xml.full.Attribute;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ItemFactory;
import org.intermine.xml.full.ItemHelper;
import java.io.Reader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* Importer to add descriptions to UniProt keywords
* @author Julie Sullivan
*/
public class UniprotKeywordConverter extends FileConverter
{
//TODO: This should come from props files
protected static final String GENOMIC_NS = "http://www.flymine.org/model/genomic
private Map ontoMap = new HashMap();
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
*/
public UniprotKeywordConverter(ItemWriter writer) {
super(writer);
}
/**
* @see FileConverter#process(Reader)
*/
public void process(Reader reader) throws Exception {
UniprotHandler handler = new UniprotHandler(writer, ontoMap);
try {
SAXParser.parse(new InputSource(reader), handler);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Extension of PathQueryHandler to handle parsing TemplateQueries
*/
static class UniprotHandler extends DefaultHandler
{
private int nextClsId = 0;
private ItemFactory itemFactory;
private ItemWriter writer;
private Map ids = new HashMap();
private Map aliases = new HashMap();
private Map keywords = new HashMap();
private String attName = null;
private StringBuffer attValue = null;
private Map ontoMap;
/**
* Constructor
* @param writer the ItemWriter used to handle the resultant items
* @param ontoMap Holds the ontology variable that's used as 1/2 the key
*/
public UniprotHandler(ItemWriter writer, Map ontoMap) {
itemFactory = new ItemFactory(Model.getInstanceByName("genomic"));
this.writer = writer;
this.ontoMap = ontoMap;
}
/**
* @see DefaultHandler#startElement
*/
public void startElement(String uri, String localName, String qName, Attributes attrs)
throws SAXException {
if (qName.equals("name")) {
attName = "name";
} else if (qName.equals("description")) {
attName = "description";
} else if (qName.equals("keywordList")) {
setOnto("UniProtKeyword");
}
super.startElement(uri, localName, qName, attrs);
attValue = new StringBuffer();
}
/**
* @see DefaultHandler#endElement
*/
public void characters(char[] ch, int start, int length) {
if (attName != null) {
// DefaultHandler may call this method more than once for a single
// attribute content -> hold text & create attribute in endElement
while (length > 0) {
boolean whitespace = false;
switch(ch[start]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) {
break;
}
++start;
--length;
}
if (length > 0) {
StringBuffer s = new StringBuffer();
s.append(ch, start, length);
attValue.append(s);
}
}
}
/**
* @see DefaultHandler#endElement
*/
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
try {
if (qName.equals("name")) {
String name = attValue.toString();
Item keyword = createItem("OntologyTerm");
keyword.addAttribute(new Attribute("name", name));
keywords.put(name, keyword);
} else if (qName.equals("description")) {
String descr = attValue.toString();
Iterator i = keywords.keySet().iterator();
while (i.hasNext()) {
String name = (String) i.next();
Item keyword = (Item) keywords.get(name);
keyword.addAttribute(new Attribute("description", descr));
writer.store(ItemHelper.convert(keyword));
}
// reset list
keywords = new HashMap();
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
}
private Item setOnto(String title)
throws SAXException {
Item ontology = (Item) ontoMap.get(title);
try {
if (ontology == null) {
ontology = createItem("Ontology");
ontology.addAttribute(new Attribute("title", title));
ontoMap.put(title, ontology);
writer.store(ItemHelper.convert(ontology));
}
} catch (ObjectStoreException e) {
throw new SAXException(e);
}
return ontology;
}
/**
* Convenience method for creating a new Item
* @param className the name of the class
* @return a new Item
*/
protected Item createItem(String className) {
return itemFactory.makeItem(alias(className) + "_" + newId(className),
GENOMIC_NS + className, "");
}
private String newId(String className) {
Integer id = (Integer) ids.get(className);
if (id == null) {
id = new Integer(0);
ids.put(className, id);
}
id = new Integer(id.intValue() + 1);
ids.put(className, id);
return id.toString();
}
/**
* Uniquely alias a className
* @param className the class name
* @return the alias
*/
protected String alias(String className) {
String alias = (String) aliases.get(className);
if (alias != null) {
return alias;
}
String nextIndex = "" + (nextClsId++);
aliases.put(className, nextIndex);
return nextIndex;
}
}
}
|
package org.eclipse.birt.chart.model.component.impl;
import java.util.Collection;
import java.util.Map;
import org.eclipse.birt.chart.computation.IConstants;
import org.eclipse.birt.chart.engine.i18n.Messages;
import org.eclipse.birt.chart.model.Chart;
import org.eclipse.birt.chart.model.attribute.Cursor;
import org.eclipse.birt.chart.model.attribute.DataPoint;
import org.eclipse.birt.chart.model.attribute.LineAttributes;
import org.eclipse.birt.chart.model.attribute.LineStyle;
import org.eclipse.birt.chart.model.attribute.Position;
import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl;
import org.eclipse.birt.chart.model.attribute.impl.DataPointImpl;
import org.eclipse.birt.chart.model.attribute.impl.LineAttributesImpl;
import org.eclipse.birt.chart.model.component.ComponentFactory;
import org.eclipse.birt.chart.model.component.ComponentPackage;
import org.eclipse.birt.chart.model.component.CurveFitting;
import org.eclipse.birt.chart.model.component.Label;
import org.eclipse.birt.chart.model.component.Series;
import org.eclipse.birt.chart.model.data.DataSet;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.Trigger;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.EMap;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.impl.EObjectImpl;
import org.eclipse.emf.ecore.util.EObjectContainmentEList;
import org.eclipse.emf.ecore.util.EcoreEMap;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc --> An implementation of the model object '
* <em><b>Series</b></em>'. <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#isVisible <em>Visible</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getLabel <em>Label</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getDataDefinition <em>Data Definition</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getSeriesIdentifier <em>Series Identifier</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getDataPoint <em>Data Point</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getDataSets <em>Data Sets</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getLabelPosition <em>Label Position</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#isStacked <em>Stacked</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getTriggers <em>Triggers</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#isTranslucent <em>Translucent</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getCurveFitting <em>Curve Fitting</em>}</li>
* <li>{@link org.eclipse.birt.chart.model.component.impl.SeriesImpl#getCursor <em>Cursor</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class SeriesImpl extends EObjectImpl implements Series
{
/**
* The default value of the '{@link #isVisible() <em>Visible</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isVisible()
* @generated
* @ordered
*/
protected static final boolean VISIBLE_EDEFAULT = true;
/**
* The cached value of the '{@link #isVisible() <em>Visible</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isVisible()
* @generated
* @ordered
*/
protected boolean visible = VISIBLE_EDEFAULT;
/**
* This is true if the Visible attribute has been set.
* <!-- begin-user-doc
* --> <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean visibleESet;
/**
* The cached value of the '{@link #getLabel() <em>Label</em>}' containment reference.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getLabel()
* @generated
* @ordered
*/
protected Label label;
/**
* The cached value of the '{@link #getDataDefinition() <em>Data Definition</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDataDefinition()
* @generated
* @ordered
*/
protected EList<Query> dataDefinition;
/**
* The default value of the '{@link #getSeriesIdentifier() <em>Series Identifier</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getSeriesIdentifier()
* @generated
* @ordered
*/
protected static final Object SERIES_IDENTIFIER_EDEFAULT = null;
/**
* The cached value of the '{@link #getSeriesIdentifier() <em>Series Identifier</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getSeriesIdentifier()
* @generated
* @ordered
*/
protected Object seriesIdentifier = SERIES_IDENTIFIER_EDEFAULT;
/**
* The cached value of the '{@link #getDataPoint() <em>Data Point</em>}' containment reference.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDataPoint()
* @generated
* @ordered
*/
protected DataPoint dataPoint;
/**
* The cached value of the '{@link #getDataSets() <em>Data Sets</em>}' map.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getDataSets()
* @generated
* @ordered
*/
protected EMap<String, DataSet> dataSets;
/**
* The default value of the '
* {@link #getLabelPosition() <em>Label Position</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getLabelPosition()
* @generated
* @ordered
*/
protected static final Position LABEL_POSITION_EDEFAULT = Position.ABOVE_LITERAL;
/**
* The cached value of the '
* {@link #getLabelPosition() <em>Label Position</em>}' attribute. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @see #getLabelPosition()
* @generated
* @ordered
*/
protected Position labelPosition = LABEL_POSITION_EDEFAULT;
/**
* This is true if the Label Position attribute has been set. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean labelPositionESet;
/**
* The default value of the '{@link #isStacked() <em>Stacked</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isStacked()
* @generated
* @ordered
*/
protected static final boolean STACKED_EDEFAULT = false;
/**
* The cached value of the '{@link #isStacked() <em>Stacked</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isStacked()
* @generated
* @ordered
*/
protected boolean stacked = STACKED_EDEFAULT;
/**
* This is true if the Stacked attribute has been set.
* <!-- begin-user-doc
* --> <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean stackedESet;
/**
* The cached value of the '{@link #getTriggers() <em>Triggers</em>}' containment reference list.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getTriggers()
* @generated
* @ordered
*/
protected EList<Trigger> triggers;
/**
* The default value of the '{@link #isTranslucent() <em>Translucent</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isTranslucent()
* @generated
* @ordered
*/
protected static final boolean TRANSLUCENT_EDEFAULT = false;
/**
* The cached value of the '{@link #isTranslucent() <em>Translucent</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #isTranslucent()
* @generated
* @ordered
*/
protected boolean translucent = TRANSLUCENT_EDEFAULT;
/**
* This is true if the Translucent attribute has been set. <!--
* begin-user-doc --> <!-- end-user-doc -->
*
* @generated
* @ordered
*/
protected boolean translucentESet;
/**
* The cached value of the '{@link #getCurveFitting() <em>Curve Fitting</em>}' containment reference.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @see #getCurveFitting()
* @generated
* @ordered
*/
protected CurveFitting curveFitting;
/**
* The cached value of the '{@link #getCursor() <em>Cursor</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getCursor()
* @generated
* @ordered
*/
protected Cursor cursor;
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
protected SeriesImpl( )
{
super( );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass( )
{
return ComponentPackage.Literals.SERIES;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isVisible( )
{
return visible;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setVisible( boolean newVisible )
{
boolean oldVisible = visible;
visible = newVisible;
boolean oldVisibleESet = visibleESet;
visibleESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__VISIBLE,
oldVisible,
visible,
!oldVisibleESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetVisible( )
{
boolean oldVisible = visible;
boolean oldVisibleESet = visibleESet;
visible = VISIBLE_EDEFAULT;
visibleESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.SERIES__VISIBLE,
oldVisible,
VISIBLE_EDEFAULT,
oldVisibleESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetVisible( )
{
return visibleESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Label getLabel( )
{
return label;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetLabel( Label newLabel,
NotificationChain msgs )
{
Label oldLabel = label;
label = newLabel;
if ( eNotificationRequired( ) )
{
ENotificationImpl notification = new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__LABEL,
oldLabel,
newLabel );
if ( msgs == null )
msgs = notification;
else
msgs.add( notification );
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setLabel( Label newLabel )
{
if ( newLabel != label )
{
NotificationChain msgs = null;
if ( label != null )
msgs = ( (InternalEObject) label ).eInverseRemove( this,
EOPPOSITE_FEATURE_BASE - ComponentPackage.SERIES__LABEL,
null,
msgs );
if ( newLabel != null )
msgs = ( (InternalEObject) newLabel ).eInverseAdd( this,
EOPPOSITE_FEATURE_BASE - ComponentPackage.SERIES__LABEL,
null,
msgs );
msgs = basicSetLabel( newLabel, msgs );
if ( msgs != null )
msgs.dispatch( );
}
else if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__LABEL,
newLabel,
newLabel ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EList<Query> getDataDefinition( )
{
if ( dataDefinition == null )
{
dataDefinition = new EObjectContainmentEList<Query>( Query.class,
this,
ComponentPackage.SERIES__DATA_DEFINITION );
}
return dataDefinition;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Object getSeriesIdentifier( )
{
return seriesIdentifier;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setSeriesIdentifier( Object newSeriesIdentifier )
{
Object oldSeriesIdentifier = seriesIdentifier;
seriesIdentifier = newSeriesIdentifier;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__SERIES_IDENTIFIER,
oldSeriesIdentifier,
seriesIdentifier ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public DataPoint getDataPoint( )
{
return dataPoint;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetDataPoint( DataPoint newDataPoint,
NotificationChain msgs )
{
DataPoint oldDataPoint = dataPoint;
dataPoint = newDataPoint;
if ( eNotificationRequired( ) )
{
ENotificationImpl notification = new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__DATA_POINT,
oldDataPoint,
newDataPoint );
if ( msgs == null )
msgs = notification;
else
msgs.add( notification );
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setDataPoint( DataPoint newDataPoint )
{
if ( newDataPoint != dataPoint )
{
NotificationChain msgs = null;
if ( dataPoint != null )
msgs = ( (InternalEObject) dataPoint ).eInverseRemove( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__DATA_POINT,
null,
msgs );
if ( newDataPoint != null )
msgs = ( (InternalEObject) newDataPoint ).eInverseAdd( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__DATA_POINT,
null,
msgs );
msgs = basicSetDataPoint( newDataPoint, msgs );
if ( msgs != null )
msgs.dispatch( );
}
else if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__DATA_POINT,
newDataPoint,
newDataPoint ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EMap<String, DataSet> getDataSets( )
{
if ( dataSets == null )
{
dataSets = new EcoreEMap<String, DataSet>( ComponentPackage.Literals.ESTRING_TO_DATA_SET_MAP_ENTRY,
EStringToDataSetMapEntryImpl.class,
this,
ComponentPackage.SERIES__DATA_SETS );
}
return dataSets;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#getDataSet()
*/
public DataSet getDataSet( )
{
return getDataSets( ).get( null );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#setDataSet(org.eclipse.birt.chart.model.data.DataSet)
*/
public void setDataSet( DataSet newDataSet )
{
getDataSets( ).put( null, newDataSet );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#getDataSet(java.lang.String)
*/
public DataSet getDataSet( String userkey )
{
return getDataSets( ).get( userkey );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#setDataSet(java.lang.String,
* org.eclipse.birt.chart.model.data.DataSet)
*/
public void setDataSet( String userKey, DataSet newDataSet )
{
getDataSets( ).put( userKey, newDataSet );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public Position getLabelPosition( )
{
return labelPosition;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setLabelPosition( Position newLabelPosition )
{
Position oldLabelPosition = labelPosition;
labelPosition = newLabelPosition == null ? LABEL_POSITION_EDEFAULT
: newLabelPosition;
boolean oldLabelPositionESet = labelPositionESet;
labelPositionESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__LABEL_POSITION,
oldLabelPosition,
labelPosition,
!oldLabelPositionESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetLabelPosition( )
{
Position oldLabelPosition = labelPosition;
boolean oldLabelPositionESet = labelPositionESet;
labelPosition = LABEL_POSITION_EDEFAULT;
labelPositionESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.SERIES__LABEL_POSITION,
oldLabelPosition,
LABEL_POSITION_EDEFAULT,
oldLabelPositionESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetLabelPosition( )
{
return labelPositionESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isStacked( )
{
return stacked;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setStacked( boolean newStacked )
{
boolean oldStacked = stacked;
stacked = newStacked;
boolean oldStackedESet = stackedESet;
stackedESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__STACKED,
oldStacked,
stacked,
!oldStackedESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetStacked( )
{
boolean oldStacked = stacked;
boolean oldStackedESet = stackedESet;
stacked = STACKED_EDEFAULT;
stackedESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.SERIES__STACKED,
oldStacked,
STACKED_EDEFAULT,
oldStackedESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetStacked( )
{
return stackedESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public EList<Trigger> getTriggers( )
{
if ( triggers == null )
{
triggers = new EObjectContainmentEList<Trigger>( Trigger.class,
this,
ComponentPackage.SERIES__TRIGGERS );
}
return triggers;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isTranslucent( )
{
return translucent;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setTranslucent( boolean newTranslucent )
{
boolean oldTranslucent = translucent;
translucent = newTranslucent;
boolean oldTranslucentESet = translucentESet;
translucentESet = true;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__TRANSLUCENT,
oldTranslucent,
translucent,
!oldTranslucentESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void unsetTranslucent( )
{
boolean oldTranslucent = translucent;
boolean oldTranslucentESet = translucentESet;
translucent = TRANSLUCENT_EDEFAULT;
translucentESet = false;
if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.UNSET,
ComponentPackage.SERIES__TRANSLUCENT,
oldTranslucent,
TRANSLUCENT_EDEFAULT,
oldTranslucentESet ) );
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public boolean isSetTranslucent( )
{
return translucentESet;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public CurveFitting getCurveFitting( )
{
return curveFitting;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCurveFitting(
CurveFitting newCurveFitting, NotificationChain msgs )
{
CurveFitting oldCurveFitting = curveFitting;
curveFitting = newCurveFitting;
if ( eNotificationRequired( ) )
{
ENotificationImpl notification = new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__CURVE_FITTING,
oldCurveFitting,
newCurveFitting );
if ( msgs == null )
msgs = notification;
else
msgs.add( notification );
}
return msgs;
}
/**
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @generated
*/
public void setCurveFitting( CurveFitting newCurveFitting )
{
if ( newCurveFitting != curveFitting )
{
NotificationChain msgs = null;
if ( curveFitting != null )
msgs = ( (InternalEObject) curveFitting ).eInverseRemove( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__CURVE_FITTING,
null,
msgs );
if ( newCurveFitting != null )
msgs = ( (InternalEObject) newCurveFitting ).eInverseAdd( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__CURVE_FITTING,
null,
msgs );
msgs = basicSetCurveFitting( newCurveFitting, msgs );
if ( msgs != null )
msgs.dispatch( );
}
else if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__CURVE_FITTING,
newCurveFitting,
newCurveFitting ) );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Cursor getCursor( )
{
return cursor;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetCursor( Cursor newCursor,
NotificationChain msgs )
{
Cursor oldCursor = cursor;
cursor = newCursor;
if ( eNotificationRequired( ) )
{
ENotificationImpl notification = new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__CURSOR,
oldCursor,
newCursor );
if ( msgs == null )
msgs = notification;
else
msgs.add( notification );
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setCursor( Cursor newCursor )
{
if ( newCursor != cursor )
{
NotificationChain msgs = null;
if ( cursor != null )
msgs = ( (InternalEObject) cursor ).eInverseRemove( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__CURSOR,
null,
msgs );
if ( newCursor != null )
msgs = ( (InternalEObject) newCursor ).eInverseAdd( this,
EOPPOSITE_FEATURE_BASE
- ComponentPackage.SERIES__CURSOR,
null,
msgs );
msgs = basicSetCursor( newCursor, msgs );
if ( msgs != null )
msgs.dispatch( );
}
else if ( eNotificationRequired( ) )
eNotify( new ENotificationImpl( this,
Notification.SET,
ComponentPackage.SERIES__CURSOR,
newCursor,
newCursor ) );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove( InternalEObject otherEnd,
int featureID, NotificationChain msgs )
{
switch ( featureID )
{
case ComponentPackage.SERIES__LABEL :
return basicSetLabel( null, msgs );
case ComponentPackage.SERIES__DATA_DEFINITION :
return ( (InternalEList<?>) getDataDefinition( ) ).basicRemove( otherEnd,
msgs );
case ComponentPackage.SERIES__DATA_POINT :
return basicSetDataPoint( null, msgs );
case ComponentPackage.SERIES__DATA_SETS :
return ( (InternalEList<?>) getDataSets( ) ).basicRemove( otherEnd,
msgs );
case ComponentPackage.SERIES__TRIGGERS :
return ( (InternalEList<?>) getTriggers( ) ).basicRemove( otherEnd,
msgs );
case ComponentPackage.SERIES__CURVE_FITTING :
return basicSetCurveFitting( null, msgs );
case ComponentPackage.SERIES__CURSOR :
return basicSetCursor( 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 ComponentPackage.SERIES__VISIBLE :
return isVisible( ) ? Boolean.TRUE : Boolean.FALSE;
case ComponentPackage.SERIES__LABEL :
return getLabel( );
case ComponentPackage.SERIES__DATA_DEFINITION :
return getDataDefinition( );
case ComponentPackage.SERIES__SERIES_IDENTIFIER :
return getSeriesIdentifier( );
case ComponentPackage.SERIES__DATA_POINT :
return getDataPoint( );
case ComponentPackage.SERIES__DATA_SETS :
if ( coreType )
return getDataSets( );
else
return getDataSets( ).map( );
case ComponentPackage.SERIES__LABEL_POSITION :
return getLabelPosition( );
case ComponentPackage.SERIES__STACKED :
return isStacked( ) ? Boolean.TRUE : Boolean.FALSE;
case ComponentPackage.SERIES__TRIGGERS :
return getTriggers( );
case ComponentPackage.SERIES__TRANSLUCENT :
return isTranslucent( ) ? Boolean.TRUE : Boolean.FALSE;
case ComponentPackage.SERIES__CURVE_FITTING :
return getCurveFitting( );
case ComponentPackage.SERIES__CURSOR :
return getCursor( );
}
return super.eGet( featureID, resolve, coreType );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet( int featureID, Object newValue )
{
switch ( featureID )
{
case ComponentPackage.SERIES__VISIBLE :
setVisible( ( (Boolean) newValue ).booleanValue( ) );
return;
case ComponentPackage.SERIES__LABEL :
setLabel( (Label) newValue );
return;
case ComponentPackage.SERIES__DATA_DEFINITION :
getDataDefinition( ).clear( );
getDataDefinition( ).addAll( (Collection<? extends Query>) newValue );
return;
case ComponentPackage.SERIES__SERIES_IDENTIFIER :
setSeriesIdentifier( newValue );
return;
case ComponentPackage.SERIES__DATA_POINT :
setDataPoint( (DataPoint) newValue );
return;
case ComponentPackage.SERIES__DATA_SETS :
( (EStructuralFeature.Setting) getDataSets( ) ).set( newValue );
return;
case ComponentPackage.SERIES__LABEL_POSITION :
setLabelPosition( (Position) newValue );
return;
case ComponentPackage.SERIES__STACKED :
setStacked( ( (Boolean) newValue ).booleanValue( ) );
return;
case ComponentPackage.SERIES__TRIGGERS :
getTriggers( ).clear( );
getTriggers( ).addAll( (Collection<? extends Trigger>) newValue );
return;
case ComponentPackage.SERIES__TRANSLUCENT :
setTranslucent( ( (Boolean) newValue ).booleanValue( ) );
return;
case ComponentPackage.SERIES__CURVE_FITTING :
setCurveFitting( (CurveFitting) newValue );
return;
case ComponentPackage.SERIES__CURSOR :
setCursor( (Cursor) newValue );
return;
}
super.eSet( featureID, newValue );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset( int featureID )
{
switch ( featureID )
{
case ComponentPackage.SERIES__VISIBLE :
unsetVisible( );
return;
case ComponentPackage.SERIES__LABEL :
setLabel( (Label) null );
return;
case ComponentPackage.SERIES__DATA_DEFINITION :
getDataDefinition( ).clear( );
return;
case ComponentPackage.SERIES__SERIES_IDENTIFIER :
setSeriesIdentifier( SERIES_IDENTIFIER_EDEFAULT );
return;
case ComponentPackage.SERIES__DATA_POINT :
setDataPoint( (DataPoint) null );
return;
case ComponentPackage.SERIES__DATA_SETS :
getDataSets( ).clear( );
return;
case ComponentPackage.SERIES__LABEL_POSITION :
unsetLabelPosition( );
return;
case ComponentPackage.SERIES__STACKED :
unsetStacked( );
return;
case ComponentPackage.SERIES__TRIGGERS :
getTriggers( ).clear( );
return;
case ComponentPackage.SERIES__TRANSLUCENT :
unsetTranslucent( );
return;
case ComponentPackage.SERIES__CURVE_FITTING :
setCurveFitting( (CurveFitting) null );
return;
case ComponentPackage.SERIES__CURSOR :
setCursor( (Cursor) null );
return;
}
super.eUnset( featureID );
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet( int featureID )
{
switch ( featureID )
{
case ComponentPackage.SERIES__VISIBLE :
return isSetVisible( );
case ComponentPackage.SERIES__LABEL :
return label != null;
case ComponentPackage.SERIES__DATA_DEFINITION :
return dataDefinition != null && !dataDefinition.isEmpty( );
case ComponentPackage.SERIES__SERIES_IDENTIFIER :
return SERIES_IDENTIFIER_EDEFAULT == null ? seriesIdentifier != null
: !SERIES_IDENTIFIER_EDEFAULT.equals( seriesIdentifier );
case ComponentPackage.SERIES__DATA_POINT :
return dataPoint != null;
case ComponentPackage.SERIES__DATA_SETS :
return dataSets != null && !dataSets.isEmpty( );
case ComponentPackage.SERIES__LABEL_POSITION :
return isSetLabelPosition( );
case ComponentPackage.SERIES__STACKED :
return isSetStacked( );
case ComponentPackage.SERIES__TRIGGERS :
return triggers != null && !triggers.isEmpty( );
case ComponentPackage.SERIES__TRANSLUCENT :
return isSetTranslucent( );
case ComponentPackage.SERIES__CURVE_FITTING :
return curveFitting != null;
case ComponentPackage.SERIES__CURSOR :
return cursor != null;
}
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( " (visible: " ); //$NON-NLS-1$
if ( visibleESet )
result.append( visible );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ", seriesIdentifier: " ); //$NON-NLS-1$
result.append( seriesIdentifier );
result.append( ", labelPosition: " ); //$NON-NLS-1$
if ( labelPositionESet )
result.append( labelPosition );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ", stacked: " ); //$NON-NLS-1$
if ( stackedESet )
result.append( stacked );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ", translucent: " ); //$NON-NLS-1$
if ( translucentESet )
result.append( translucent );
else
result.append( "<unset>" ); //$NON-NLS-1$
result.append( ')' );
return result.toString( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#canParticipateInCombination()
*/
public boolean canParticipateInCombination( )
{
return false;
}
/**
* A convenience method to create an initialized 'Series' instance
*
* @return
*/
public static Series create( )
{
final Series se = ComponentFactory.eINSTANCE.createSeries( );
( (SeriesImpl) se ).initialize( );
return se;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#initialize()
*/
protected void initialize( )
{
setStacked( false );
setVisible( true );
final Label la = LabelImpl.create( );
LineAttributes lia = LineAttributesImpl.create( ColorDefinitionImpl.BLACK( ),
LineStyle.SOLID_LITERAL,
1 );
la.setOutline( lia );
lia.setVisible( false );
// la.setBackground(ColorDefinitionImpl.YELLOW());
setLabel( la );
la.setVisible( false );
setLabelPosition( Position.OUTSIDE_LITERAL );
setSeriesIdentifier( IConstants.UNDEFINED_STRING );
setDataPoint( DataPointImpl.create( null, null, ", " ) ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#canBeStacked()
*/
public boolean canBeStacked( )
{
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#canShareAxisUnit()
*/
public boolean canShareAxisUnit( )
{
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#translateFrom(org.eclipse.birt.chart.model.component.Series,
* org.eclipse.birt.chart.model.Chart)
*/
public void translateFrom( Series sourceSeries, int iSeriesDefinitionIndex,
Chart chart )
{
// Do nothing
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.model.component.Series#getDisplayName()
*/
public String getDisplayName( )
{
return Messages.getString( "SeriesImpl.displayName" ); //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.birt.chart.model.component.Series#isSingleCache()
*/
public boolean isSingleCache( )
{
return false;
}
/**
* A convenient method to get an instance copy. This is much faster than the
* ECoreUtil.copy().
*/
public Series copyInstance( )
{
SeriesImpl dest = new SeriesImpl( );
dest.set( this );
return dest;
}
protected void set( Series src )
{
if ( src.getLabel( ) != null )
{
setLabel( src.getLabel( ).copyInstance( ) );
}
if ( src.getDataDefinition( ) != null )
{
EList<Query> list = getDataDefinition( );
for ( Query element : src.getDataDefinition( ) )
{
list.add( element.copyInstance( ) );
}
}
if ( src.getDataPoint( ) != null )
{
setDataPoint( src.getDataPoint( ).copyInstance( ) );
}
if ( src.getDataSets( ) != null )
{
EMap<String, DataSet> map = getDataSets( );
for ( Map.Entry<String, DataSet> entry : src.getDataSets( )
.entrySet( ) )
{
DataSet entryValue = entry.getValue( ) != null ? entry.getValue( )
.copyInstance( )
: null;
map.put( entry.getKey( ), entryValue );
}
}
if ( src.getTriggers( ) != null )
{
EList<Trigger> list = getTriggers( );
for ( Trigger element : src.getTriggers( ) )
{
list.add( element.copyInstance( ) );
}
}
if ( src.getCurveFitting( ) != null )
{
setCurveFitting( src.getCurveFitting( ).copyInstance( ) );
}
if ( src.getCursor( ) != null )
{
setCursor( src.getCursor( ).copyInstance( ) );
}
visible = src.isVisible( );
visibleESet = src.isSetVisible( );
seriesIdentifier = src.getSeriesIdentifier( );
labelPosition = src.getLabelPosition( );
labelPositionESet = src.isSetLabelPosition( );
stacked = src.isStacked( );
stackedESet = src.isSetStacked( );
translucent = src.isTranslucent( );
translucentESet = src.isSetTranslucent( );
}
} // SeriesImpl
|
package edu.duke.cabig.c3pr.domain.repository.impl;
import java.util.List;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.springframework.context.MessageSource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.transaction.annotation.Transactional;
import edu.duke.cabig.c3pr.dao.HealthcareSiteDao;
import edu.duke.cabig.c3pr.dao.HealthcareSiteInvestigatorDao;
import edu.duke.cabig.c3pr.dao.InvestigatorDao;
import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.HealthcareSite;
import edu.duke.cabig.c3pr.domain.HealthcareSiteInvestigator;
import edu.duke.cabig.c3pr.domain.Investigator;
import edu.duke.cabig.c3pr.domain.OrganizationAssignedIdentifier;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyInvestigator;
import edu.duke.cabig.c3pr.domain.StudyOrganization;
import edu.duke.cabig.c3pr.domain.repository.StudyRepository;
import edu.duke.cabig.c3pr.exception.C3PRBaseRuntimeException;
import edu.duke.cabig.c3pr.exception.C3PRCodedException;
import edu.duke.cabig.c3pr.exception.C3PRExceptionHelper;
import edu.duke.cabig.c3pr.exception.StudyValidationException;
import edu.duke.cabig.c3pr.service.impl.StudyXMLImporterServiceImpl;
@Transactional
public class StudyRepositoryImpl implements StudyRepository {
private StudyDao studyDao;
private HealthcareSiteDao healthcareSiteDao;
private InvestigatorDao investigatorDao;
private HealthcareSiteInvestigatorDao healthcareSiteInvestigatorDao;
private Logger log = Logger.getLogger(StudyXMLImporterServiceImpl.class.getName());
private C3PRExceptionHelper c3PRExceptionHelper;
private MessageSource c3prErrorMessages;
public StudyRepositoryImpl() {
super();
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setBasename("error_messages_multisite");
ResourceBundleMessageSource resourceBundleMessageSource1 = new ResourceBundleMessageSource();
resourceBundleMessageSource1.setBasename("error_messages_c3pr");
resourceBundleMessageSource1.setParentMessageSource(resourceBundleMessageSource);
this.c3prErrorMessages = resourceBundleMessageSource1;
this.c3PRExceptionHelper = new C3PRExceptionHelper(c3prErrorMessages);
}
@Transactional(readOnly = false)
public void buildAndSave(Study study) throws C3PRCodedException {
// load study orgs from db Not to be imported
for (StudyOrganization organization : study.getStudyOrganizations()) {
HealthcareSite loadedSite = healthcareSiteDao.getByNciInstituteCode(organization
.getHealthcareSite().getNciInstituteCode());
if (loadedSite == null) {
throw getC3PRExceptionHelper()
.getException(
getCode("C3PR.EXCEPTION.STUDY.INVALID.HEALTHCARESITE_IDENTIFIER.CODE"),
new String[] {
organization
.getHealthcareSite().getNciInstituteCode()});
}
organization.setHealthcareSite(loadedSite);
// load Investigators from DB
for (StudyInvestigator sInv : organization.getStudyInvestigators()) {
Investigator inv = sInv.getHealthcareSiteInvestigator().getInvestigator();
Investigator loadedInv = investigatorDao.getByNciInstituteCode(inv
.getNciIdentifier());
if (loadedInv == null) {
throw getC3PRExceptionHelper()
.getException(
getCode("C3PR.EXCEPTION.STUDY.INVALID.NCI_IDENTIFIER.CODE"),
new String[] {
inv
.getNciIdentifier()});
}
HealthcareSiteInvestigator loadedSiteInv = healthcareSiteInvestigatorDao
.getSiteInvestigator(loadedSite, loadedInv);
if (loadedSiteInv == null) {
throw getC3PRExceptionHelper()
.getException(
getCode("C3PR.EXCEPTION.REGISTRATION.INVALID.HEALTHCARESITE_IDENTIFIER.CODE"),
new String[] {
loadedSite.getName(),
loadedInv.getFullName()});
}
sInv.setHealthcareSiteInvestigator(loadedSiteInv);
sInv.setSiteInvestigator(loadedSiteInv);
}
}
for (OrganizationAssignedIdentifier identifier : study.getOrganizationAssignedIdentifiers()) {
HealthcareSite loadedSite = healthcareSiteDao.getByNciInstituteCode(identifier
.getHealthcareSite().getNciInstituteCode());
identifier.setHealthcareSite(loadedSite);
}
studyDao.save(study);
log.debug("Study saved with grid ID" + study.getGridId());
}
/**
* Validate a study against a set of validation rules
*
* @param study
* @throws StudyValidationException
*/
public void validate(Study study) throws StudyValidationException {
// make sure grid id exists
if (study.getId() != null) {
if (studyDao.getById(study.getId()) != null) {
throw new StudyValidationException("Study exists");
}
}
if ((study.getCoordinatingCenterAssignedIdentifier()==null)){
throw new StudyValidationException("Coordinating Center identifier is required");
}
/* else if (studyDao.getCoordinatingCenterIdentifiersWithValue(study.getCoordinatingCenterAssignedIdentifier().getValue(), study.getCoordinatingCenterAssignedIdentifier().getHealthcareSite()).size()>0) {
throw new StudyValidationException("Study exists");
}*/
for (StudyOrganization organization : study.getStudyOrganizations()) {
if (healthcareSiteDao.getByNciInstituteCode(organization.getHealthcareSite()
.getNciInstituteCode()) == null) {
throw new StudyValidationException(
"Could not find Organization with NCI Institute code:"
+ organization.getHealthcareSite()
.getNciInstituteCode());
}
}
}
public List<Study> searchByCoOrdinatingCenterId(OrganizationAssignedIdentifier identifier)throws C3PRCodedException {
HealthcareSite healthcareSite = this.healthcareSiteDao
.getByNciInstituteCode(identifier.getHealthcareSite()
.getNciInstituteCode());
if (healthcareSite == null) {
throw getC3PRExceptionHelper()
.getException(
getCode("C3PR.EXCEPTION.STUDY.INVALID.HEALTHCARESITE_IDENTIFIER.CODE"),
new String[] {
identifier.getHealthcareSite()
.getNciInstituteCode(),
identifier.getType() });
}
identifier.setHealthcareSite(healthcareSite);
return studyDao.searchByOrgIdentifier(identifier);
}
public void setHealthcareSiteDao(HealthcareSiteDao healthcareSiteDao) {
this.healthcareSiteDao = healthcareSiteDao;
}
public void setInvestigatorDao(InvestigatorDao investigatorDao) {
this.investigatorDao = investigatorDao;
}
public void setStudyDao(StudyDao studyDao) {
this.studyDao = studyDao;
}
@Transient
public int getCode(String errortypeString) {
return Integer.parseInt(this.c3prErrorMessages.getMessage(errortypeString, null, null));
}
@Transient
public C3PRExceptionHelper getC3PRExceptionHelper() {
return c3PRExceptionHelper;
}
public void setExceptionHelper(C3PRExceptionHelper c3PRExceptionHelper) {
this.c3PRExceptionHelper = c3PRExceptionHelper;
}
@Transient
public MessageSource getC3prErrorMessages() {
return c3prErrorMessages;
}
public void setC3prErrorMessages(MessageSource errorMessages) {
c3prErrorMessages = errorMessages;
}
public void setHealthcareSiteInvestigatorDao(
HealthcareSiteInvestigatorDao healthcareSiteInvestigatorDao) {
this.healthcareSiteInvestigatorDao = healthcareSiteInvestigatorDao;
}
}
|
package com.example.e4.rcp.todo.service.internal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import org.eclipse.e4.core.services.events.IEventBroker;
import com.example.e4.rcp.todo.events.MyEventConstants;
import com.example.e4.rcp.todo.model.ITodoService;
import com.example.e4.rcp.todo.model.Todo;
public class MyTodoServiceImpl implements ITodoService {
static int current = 1;
private List<Todo> todos;
// Can now use @Inject in the MyTodoServiceImpl!
@Inject
private IEventBroker broker;
public MyTodoServiceImpl() {
todos = createInitialModel();
}
// Always return a new copy of the data
@Override
public List<Todo> getTodos() {
List<Todo> list = new ArrayList<Todo>();
for (Todo todo : todos) {
list.add(todo.copy());
}
return list;
}
// Saves or updates
@Override
public synchronized boolean saveTodo(Todo newTodo) {
Todo updateTodo = findById(newTodo.getId());
if (updateTodo != null) {
updateTodo.setSummary(newTodo.getSummary());
updateTodo.setDescription(newTodo.getDescription());
updateTodo.setDone(newTodo.isDone());
updateTodo.setDueDate(newTodo.getDueDate());
broker.send(MyEventConstants.TOPIC_TODO_UPDATE, updateTodo);
} else {
newTodo.setId(current++);
todos.add(newTodo);
broker.send(MyEventConstants.TOPIC_TODO_NEW, updateTodo);
}
return true;
}
@Override
public Todo getTodo(long id) {
Todo todo = findById(id);
if (todo != null) {
return todo.copy();
}
return null;
}
@Override
public boolean deleteTodo(long id) {
Todo deleteTodo = findById(id);
if (deleteTodo != null) {
todos.remove(deleteTodo);
broker.send(MyEventConstants.TOPIC_TODO_DELETE, deleteTodo);
return true;
}
return false;
}
// Example data, change if you like
private List<Todo> createInitialModel() {
List<Todo> list = new ArrayList<Todo>();
list.add(createTodo("Application model", "Flexible and extensible"));
list.add(createTodo("DI", "@Inject as programming mode"));
list.add(createTodo("SWT", "Widgets"));
list.add(createTodo("JFace", "Nice, especially Viewers!"));
list.add(createTodo("OSGi", "Services"));
list.add(createTodo("CSS Styling","style your application"));
list.add(createTodo("Eclipse services","Core"));
list.add(createTodo("Compatibility Layer", "Run Eclipse 3.x"));
return list;
}
private Todo createTodo(String summary, String description) {
return new Todo(current++, summary, description, false, new Date());
}
private Todo findById(long id) {
Todo item = null;
for (Todo todo : todos) {
if (id == todo.getId()) {
item = todo;
}
}
return item;
}
}
|
package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.config.provision.Environment;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.Zone;
import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.hosted.controller.Application;
import com.yahoo.vespa.hosted.controller.ApplicationController;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.application.ApplicationList;
import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.DeploymentJobs;
import com.yahoo.vespa.hosted.controller.application.DeploymentJobs.JobError;
import com.yahoo.vespa.hosted.controller.application.DeploymentJobs.JobReport;
import com.yahoo.vespa.hosted.controller.application.DeploymentJobs.JobType;
import com.yahoo.vespa.hosted.controller.application.JobStatus;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.logging.Logger;
/**
* Responsible for scheduling deployment jobs in a build system and keeping
* Application.deploying() in sync with what is scheduled.
*
* This class is multithread safe.
*
* @author bratseth
* @author mpolden
*/
public class DeploymentTrigger {
/** The max duration a job may run before we consider it dead/hanging */
private final Duration jobTimeout;
private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName());
private final Controller controller;
private final Clock clock;
private final BuildSystem buildSystem;
private final DeploymentOrder order;
public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) {
Objects.requireNonNull(controller,"controller cannot be null");
Objects.requireNonNull(curator,"curator cannot be null");
Objects.requireNonNull(clock,"clock cannot be null");
this.controller = controller;
this.clock = clock;
this.buildSystem = new PolledBuildSystem(controller, curator);
this.order = new DeploymentOrder(controller);
this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1);
}
/** Returns the time in the past before which jobs are at this moment considered unresponsive */
public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); }
/**
* Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs
* (which may possibly the same job once over).
*
* @param report information about the job that just completed
*/
public void triggerFromCompletion(JobReport report) {
try (Lock lock = applications().lock(report.applicationId())) {
Application application = applications().require(report.applicationId());
application = application.withJobCompletion(report, clock.instant(), controller);
// Handle successful starting and ending
if (report.success()) {
if (order.isFirst(report.jobType())) { // the first job tells us that a change occurred
if (acceptNewRevisionNow(application)) {
// Set this as the change we are doing, unless we are already pushing a platform change
if ( ! ( application.deploying().isPresent() &&
(application.deploying().get() instanceof Change.VersionChange)))
application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown()));
}
else { // postpone
applications().store(application.withOutstandingChange(true), lock);
return;
}
}
else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) {
// change completed
application = application.withDeploying(Optional.empty());
}
}
// Trigger next
if (report.success())
application = trigger(order.nextAfter(report.jobType(), application), application,
String.format("%s completed successfully in build %d",
report.jobType(), report.buildNumber()), lock);
else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType()))
application = trigger(report.jobType(), application, true,
String.format("Retrying due to out of capacity in build %d",
report.buildNumber()), lock);
else if (shouldRetryNow(application))
application = trigger(report.jobType(), application, false,
String.format("Retrying as build %d just started failing",
report.buildNumber()), lock);
applications().store(application, lock);
}
}
/**
* Find jobs that can and should run but are currently not.
*/
public void triggerReadyJobs() {
ApplicationList applications = ApplicationList.from(applications().asList());
applications = applications.notPullRequest();
for (Application application : applications.asList()) {
try (Lock lock = applications().lock(application.id())) {
application = controller.applications().get(application.id()).orElse(null); // re-get with lock
if (application == null) continue; // application removed
triggerReadyJobs(application, lock);
}
}
}
private void triggerReadyJobs(Application application, Lock lock) {
if ( ! application.deploying().isPresent()) return;
for (JobType jobType : order.jobsFrom(application.deploymentSpec())) {
JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType);
if (jobStatus == null) continue; // never run
if (jobStatus.isRunning(jobTimeoutLimit())) continue;
// Collect the subset of next jobs which have not run with the last changes
List<JobType> nextToTrigger = new ArrayList<>();
for (JobType nextJobType : order.nextAfter(jobType, application)) {
JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType);
if (changesAvailable(application, jobStatus, nextStatus))
nextToTrigger.add(nextJobType);
}
// Trigger them in parallel
application = trigger(nextToTrigger, application, "Triggering previously blocked jobs", lock);
controller.applications().store(application, lock);
}
}
/**
* Returns true if the previous job has completed successfully with a revision and/or version which is
* newer (different) than the one last completed successfully in next
*/
private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) {
if ( ! previous.lastSuccess().isPresent()) return false;
if ( ! application.deploying().isPresent()) return false;
Change change = application.deploying().get();
if (change instanceof Change.VersionChange && // the last completed is out of date - don't continue with it
! ((Change.VersionChange)change).version().equals(previous.lastSuccess().get().version()))
return false;
if (next == null) return true;
if ( ! next.lastSuccess().isPresent()) return true;
JobStatus.JobRun previousSuccess = previous.lastSuccess().get();
JobStatus.JobRun nextSuccess = next.lastSuccess().get();
if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get()))
return true;
if (! previousSuccess.version().equals(nextSuccess.version()))
return true;
return false;
}
/**
* Called periodically to cause triggering of jobs in the background
*/
public void triggerFailing(ApplicationId applicationId) {
try (Lock lock = applications().lock(applicationId)) {
Application application = applications().require(applicationId);
if ( ! application.deploying().isPresent()) return; // No ongoing change, no need to retry
// Retry first failing job
for (JobType jobType : order.jobsFrom(application.deploymentSpec())) {
JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType);
if (isFailing(application.deploying().get(), jobStatus)) {
if (shouldRetryNow(jobStatus)) {
application = trigger(jobType, application, false, "Retrying failing job", lock);
applications().store(application, lock);
}
break;
}
}
// Retry dead job
Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs());
if (firstDeadJob.isPresent()) {
application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job",
lock);
applications().store(application, lock);
}
}
}
/** Triggers jobs that have been delayed according to deployment spec */
public void triggerDelayed() {
for (Application application : applications().asList()) {
if ( ! application.deploying().isPresent() ) continue;
if (application.deploymentJobs().hasFailures()) continue;
if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue;
if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) {
continue; // Application does not have any delayed deployments
}
Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values()
.stream()
.filter(j -> j.lastSuccess().isPresent())
.sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed())
.findFirst();
if ( ! lastSuccessfulJob.isPresent() ) continue;
// Trigger next
try (Lock lock = applications().lock(application.id())) {
application = applications().require(application.id());
application = trigger(order.nextAfter(lastSuccessfulJob.get().type(), application), application,
"Resuming delayed deployment", lock);
applications().store(application, lock);
}
}
}
public void triggerChange(ApplicationId applicationId, Change change) {
try (Lock lock = applications().lock(applicationId)) {
Application application = applications().require(applicationId);
if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures())
throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " +
application.deploying() + " is already in progress");
application = application.withDeploying(Optional.of(change));
if (change instanceof Change.ApplicationChange)
application = application.withOutstandingChange(false);
application = trigger(JobType.systemTest, application, false, "Deploying change", lock);
applications().store(application, lock);
}
}
/**
* Cancels any ongoing upgrade of the given application
*
* @param applicationId the application to trigger
*/
public void cancelChange(ApplicationId applicationId) {
try (Lock lock = applications().lock(applicationId)) {
Application application = applications().require(applicationId);
buildSystem.removeJobs(application.id());
application = application.withDeploying(Optional.empty());
applications().store(application, lock);
}
}
private ApplicationController applications() { return controller.applications(); }
/** Returns whether a job is failing for the current change in the given application */
private boolean isFailing(Change change, JobStatus status) {
return status != null &&
!status.isSuccess() &&
status.lastCompletedFor(change);
}
private boolean isCapacityConstrained(JobType jobType) {
return jobType == JobType.stagingTest || jobType == JobType.systemTest;
}
/** Returns the first job that has been running for more than the given timeout */
private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) {
Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream()
.filter(job -> job.isRunning(Instant.ofEpochMilli(0)))
.sorted(Comparator.comparing(status -> status.lastTriggered().get().at()))
.findFirst();
return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit()));
}
/** Decide whether the job should be triggered by the periodic trigger */
private boolean shouldRetryNow(JobStatus job) {
if (job.isSuccess()) return false;
if (job.isRunning(jobTimeoutLimit())) return false;
// Retry after 10% of the time since it started failing
Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10);
if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true;
// ... or retry anyway if we haven't tried in 4 hours
if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true;
return false;
}
/** Retry immediately only if this just started failing. Otherwise retry periodically */
private boolean shouldRetryNow(Application application) {
return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10)));
}
/** Decide whether to retry due to capacity restrictions */
private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) {
Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType))
.flatMap(JobStatus::jobError)
.filter(e -> e.equals(JobError.outOfCapacity));
if ( ! outOfCapacityError.isPresent()) return false;
// Retry the job if it failed recently
return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at()
.isAfter(clock.instant().minus(Duration.ofMinutes(15)));
}
/** Returns whether the given job type should be triggered according to deployment spec */
private boolean deploysTo(Application application, JobType jobType) {
Optional<Zone> zone = jobType.zone(controller.system());
if (zone.isPresent() && jobType.isProduction()) {
// Skip triggering of jobs for zones where the application should not be deployed
if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) {
return false;
}
}
return true;
}
/**
* Trigger a job for an application
*
* @param jobType the type of the job to trigger, or null to trigger nothing
* @param application the application to trigger the job for
* @param first whether to trigger the job before other jobs
* @param cause describes why the job is triggered
* @return the application in the triggered state, which *must* be stored by the caller
*/
private Application trigger(JobType jobType, Application application, boolean first, String cause, Lock lock) {
if (isRunningProductionJob(application)) return application;
return triggerAllowParallel(jobType, application, first, false, cause, lock);
}
private Application trigger(List<JobType> jobs, Application application, String cause, Lock lock) {
if (isRunningProductionJob(application)) return application;
for (JobType job : jobs)
application = triggerAllowParallel(job, application, false, false, cause, lock);
return application;
}
/**
* Trigger a job for an application, if allowed
*
* @param jobType the type of the job to trigger, or null to trigger nothing
* @param application the application to trigger the job for
* @param first whether to trigger the job before other jobs
* @param force true to diable checks which should normally prevent this triggering from happening
* @param cause describes why the job is triggered
* @return the application in the triggered state, if actually triggered. This *must* be stored by the caller
*/
public Application triggerAllowParallel(JobType jobType, Application application,
boolean first, boolean force, String cause, Lock lock) {
if (jobType == null) return application; // we are passed null when the last job has been reached
// Never allow untested changes to go through
// Note that this may happen because a new change catches up and prevents an older one from continuing
if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) {
log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType,
application, cause));
return application;
}
if ( ! force && ! allowedTriggering(jobType, application)) return application;
log.info(String.format("Triggering %s for %s, %s: %s", jobType, application,
application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"),
cause));
buildSystem.addJob(application.id(), jobType, first);
return application.withJobTriggering(jobType, application.deploying(), clock.instant(), controller);
}
/** Returns true if the given proposed job triggering should be effected */
private boolean allowedTriggering(JobType jobType, Application application) {
// Note: We could make a more fine-grained and more correct determination about whether to block
// by instead basing the decision on what is currently deployed in the zone. However,
// this leads to some additional corner cases, and the possibility of blocking an application
// fix to a version upgrade, so not doing it now
if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false;
if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false;
if ( ! deploysTo(application, jobType)) return false;
// Ignore applications that are not associated with a project
if ( ! application.deploymentJobs().projectId().isPresent()) return false;
return true;
}
private boolean isRunningProductionJob(Application application) {
return application.deploymentJobs().jobStatus().entrySet().stream()
.anyMatch(entry -> entry.getKey().isProduction() && entry.getValue().isRunning(jobTimeoutLimit()));
}
private boolean acceptNewRevisionNow(Application application) {
if ( ! application.deploying().isPresent()) return true;
if ( application.deploying().get() instanceof Change.ApplicationChange) return true; // more changes are ok
if ( application.deploymentJobs().hasFailures()) return true; // allow changes to fix upgrade problems
if ( application.isBlocked(clock.instant())) return true; // allow testing changes while upgrade blocked (debatable)
return false;
}
public BuildSystem buildSystem() { return buildSystem; }
public DeploymentOrder deploymentOrder() { return order; }
}
|
package com.yahoo.vespa.hosted.controller.notification;
import com.yahoo.collections.Pair;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.vespa.curator.Lock;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.api.application.v4.model.ClusterMetrics;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Level;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Type;
/**
* Adds, updates and removes tenant notifications in ZK
*
* @author freva
*/
public class NotificationsDb {
private final Clock clock;
private final CuratorDb curatorDb;
public NotificationsDb(Controller controller) {
this(controller.clock(), controller.curator());
}
NotificationsDb(Clock clock, CuratorDb curatorDb) {
this.clock = clock;
this.curatorDb = curatorDb;
}
public List<Notification> listNotifications(NotificationSource source, boolean productionOnly) {
return curatorDb.readNotifications(source.tenant()).stream()
.filter(notification -> source.contains(notification.source()) && (!productionOnly || notification.source().isProduction()))
.collect(Collectors.toUnmodifiableList());
}
public void setNotification(NotificationSource source, Type type, Level level, String message) {
setNotification(source, type, level, List.of(message));
}
/**
* Add a notification with given source and type. If a notification with same source and type
* already exists, it'll be replaced by this one instead
*/
public void setNotification(NotificationSource source, Type type, Level level, List<String> messages) {
try (Lock lock = curatorDb.lockNotifications(source.tenant())) {
List<Notification> notifications = curatorDb.readNotifications(source.tenant()).stream()
.filter(notification -> !source.equals(notification.source()) || type != notification.type())
.collect(Collectors.toCollection(ArrayList::new));
notifications.add(new Notification(clock.instant(), type, level, source, messages));
curatorDb.writeNotifications(source.tenant(), notifications);
}
}
/** Remove the notification with the given source and type */
public void removeNotification(NotificationSource source, Type type) {
try (Lock lock = curatorDb.lockNotifications(source.tenant())) {
List<Notification> initial = curatorDb.readNotifications(source.tenant());
List<Notification> filtered = initial.stream()
.filter(notification -> !source.equals(notification.source()) || type != notification.type())
.collect(Collectors.toUnmodifiableList());
if (initial.size() > filtered.size())
curatorDb.writeNotifications(source.tenant(), filtered);
}
}
/** Remove all notifications for this source or sources contained by this source */
public void removeNotifications(NotificationSource source) {
try (Lock lock = curatorDb.lockNotifications(source.tenant())) {
if (source.application().isEmpty()) { // Source is tenant
curatorDb.deleteNotifications(source.tenant());
return;
}
List<Notification> initial = curatorDb.readNotifications(source.tenant());
List<Notification> filtered = initial.stream()
.filter(notification -> !source.contains(notification.source()))
.collect(Collectors.toUnmodifiableList());
if (initial.size() > filtered.size())
curatorDb.writeNotifications(source.tenant(), filtered);
}
}
/**
* Updates notifications based on deployment metrics (e.g. feed blocked and reindexing progress) for the given
* deployment based on current cluster metrics.
* Will clear notifications of any cluster not reporting the metrics or whose metrics indicate feed is not blocked
* or reindexing no longer in progress. Will set notification for clusters:
* - that are (Level.error) or are nearly (Level.warning) feed blocked,
* - that are (Level.info) currently reindexing at least 1 document type.
*/
public void setDeploymentMetricsNotifications(DeploymentId deploymentId, List<ClusterMetrics> clusterMetrics) {
Instant now = clock.instant();
List<Notification> newNotifications = clusterMetrics.stream()
.flatMap(metric -> {
NotificationSource source = NotificationSource.from(deploymentId, ClusterSpec.Id.from(metric.getClusterId()));
return Stream.of(createFeedBlockNotification(source, now, metric),
createReindexNotification(source, now, metric));
})
.flatMap(Optional::stream)
.collect(Collectors.toUnmodifiableList());
NotificationSource deploymentSource = NotificationSource.from(deploymentId);
try (Lock lock = curatorDb.lockNotifications(deploymentSource.tenant())) {
List<Notification> initial = curatorDb.readNotifications(deploymentSource.tenant());
List<Notification> updated = Stream.concat(
initial.stream()
.filter(notification ->
// Filter out old feed block notifications and reindex for this deployment
(notification.type() != Type.feedBlock && notification.type() != Type.reindex) ||
!deploymentSource.contains(notification.source())),
// ... and add the new notifications for this deployment
newNotifications.stream())
.collect(Collectors.toUnmodifiableList());
if (!initial.equals(updated))
curatorDb.writeNotifications(deploymentSource.tenant(), updated);
}
}
private static Optional<Notification> createFeedBlockNotification(NotificationSource source, Instant at, ClusterMetrics metric) {
Optional<Pair<Level, String>> memoryStatus =
resourceUtilToFeedBlockStatus("memory", metric.memoryUtil(), metric.memoryFeedBlockLimit());
Optional<Pair<Level, String>> diskStatus =
resourceUtilToFeedBlockStatus("disk", metric.diskUtil(), metric.diskFeedBlockLimit());
if (memoryStatus.isEmpty() && diskStatus.isEmpty()) return Optional.empty();
// Find the max among levels
Level level = Stream.of(memoryStatus, diskStatus)
.flatMap(status -> status.stream().map(Pair::getFirst))
.max(Comparator.comparing(Enum::ordinal)).get();
List<String> messages = Stream.concat(memoryStatus.stream(), diskStatus.stream())
.filter(status -> status.getFirst() == level) // Do not mix message from different levels
.map(Pair::getSecond)
.collect(Collectors.toUnmodifiableList());
return Optional.of(new Notification(at, Type.feedBlock, level, source, messages));
}
private static Optional<Notification> createReindexNotification(NotificationSource source, Instant at, ClusterMetrics metric) {
if (metric.reindexingProgress().isEmpty()) return Optional.empty();
List<String> messages = metric.reindexingProgress().entrySet().stream()
.map(entry -> String.format(Locale.US, "document type '%s' (%.1f%% done)", entry.getKey(), 100 * entry.getValue()))
.sorted()
.collect(Collectors.toUnmodifiableList());
return Optional.of(new Notification(at, Type.reindex, Level.info, source, messages));
}
/**
* Returns a feed block summary for the given resource: the notification level and
* notification message for the given resource utilization wrt. given resource limit.
* If utilization is well below the limit, Optional.empty() is returned.
*/
private static Optional<Pair<Level, String>> resourceUtilToFeedBlockStatus(
String resource, Optional<Double> util, Optional<Double> feedBlockLimit) {
if (util.isEmpty() || feedBlockLimit.isEmpty()) return Optional.empty();
double utilRelativeToLimit = util.get() / feedBlockLimit.get();
if (utilRelativeToLimit < 0.9) return Optional.empty();
String message = String.format(Locale.US, "%s (usage: %.1f%%, feed block limit: %.1f%%)",
resource, 100 * util.get(), 100 * feedBlockLimit.get());
if (utilRelativeToLimit < 1) return Optional.of(new Pair<>(Level.warning, message));
return Optional.of(new Pair<>(Level.error, message));
}
}
|
package org.jnosql.diana.keyvalue.query;
import jakarta.nosql.QueryException;
import jakarta.nosql.Value;
import jakarta.nosql.keyvalue.BucketManager;
import jakarta.nosql.keyvalue.KeyValuePreparedStatement;
import jakarta.nosql.keyvalue.KeyValueQueryParser;
import java.util.Objects;
import java.util.stream.Stream;
public class DefaultKeyValueQueryParser implements KeyValueQueryParser {
private final PutQueryParser putQueryParser = new PutQueryParser();
private final GetQueryParser getQueryParser = new GetQueryParser();
private final RemoveQueryParser removeQueryParser = new RemoveQueryParser();
@Override
public Stream<Value> query(String query, BucketManager manager) {
validation(query, manager);
String command = query.substring(0, 3);
switch (command) {
case "get":
return getQueryParser.query(query, manager);
case "rem":
return removeQueryParser.query(query, manager);
case "put":
return putQueryParser.query(query, manager);
default:
throw new QueryException(String.format("The command was not recognized at the query %s ", query));
}
}
@Override
public KeyValuePreparedStatement prepare(String query, BucketManager manager) {
validation(query, manager);
String command = query.substring(0, 3);
switch (command) {
case "get":
return getQueryParser.prepare(query, manager);
case "rem":
return removeQueryParser.prepare(query, manager);
case "put":
return putQueryParser.prepare(query, manager);
default:
throw new QueryException(String.format("The command was not recognized at the query %s ", query));
}
}
private void validation(String query, BucketManager manager) {
Objects.requireNonNull(query, "query is required");
Objects.requireNonNull(manager, "manager is required");
if (query.length() <= 4) {
throw new QueryException(String.format("The query %s is invalid", query));
}
}
}
|
package org.neo4j.kernel.ha.cluster;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import java.net.URI;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.neo4j.cluster.InstanceId;
import org.neo4j.cluster.member.ClusterMemberEvents;
import org.neo4j.cluster.member.ClusterMemberListener;
import org.neo4j.cluster.protocol.election.Election;
import org.neo4j.kernel.AvailabilityGuard;
import org.neo4j.kernel.ha.cluster.member.ClusterMembers;
import org.neo4j.kernel.impl.util.StringLogger;
public class HighAvailabilityMemberStateMachineTest
{
@Test
public void shouldStartFromPending() throws Exception
{
// Given
HighAvailabilityMemberContext context = mock( HighAvailabilityMemberContext.class );
AvailabilityGuard guard = mock( AvailabilityGuard.class );
ClusterMembers members = mock( ClusterMembers.class );
ClusterMemberEvents events = mock( ClusterMemberEvents.class );
Election election = mock( Election.class );
StringLogger logger = mock( StringLogger.class );
HighAvailabilityMemberStateMachine toTest =
new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
// Then
assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );
}
@Test
public void shouldMoveToToMasterFromPendingOnMasterElectedForItself() throws Throwable
{
// Given
InstanceId me = new InstanceId( 1 );
HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me );
AvailabilityGuard guard = mock( AvailabilityGuard.class );
ClusterMembers members = mock( ClusterMembers.class );
ClusterMemberEvents events = mock( ClusterMemberEvents.class );
final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
return null;
}
} ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );
Election election = mock( Election.class );
StringLogger logger = mock( StringLogger.class );
HighAvailabilityMemberStateMachine toTest =
new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
toTest.init();
ClusterMemberListener theListener = listener.iterator().next();
// When
theListener.coordinatorIsElected( me );
// Then
assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.TO_MASTER ) );
}
@Test
public void shouldRemainToPendingOnMasterElectedForSomeoneElse() throws Throwable
{
// Given
InstanceId me = new InstanceId( 1 );
HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me );
AvailabilityGuard guard = mock( AvailabilityGuard.class );
ClusterMembers members = mock( ClusterMembers.class );
ClusterMemberEvents events = mock( ClusterMemberEvents.class );
final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
return null;
}
} ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );
Election election = mock( Election.class );
StringLogger logger = mock( StringLogger.class );
HighAvailabilityMemberStateMachine toTest =
new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
toTest.init();
ClusterMemberListener theListener = listener.iterator().next();
// When
theListener.coordinatorIsElected( new InstanceId( 2 ) );
// Then
assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.PENDING ) );
}
@Test
public void shouldSwitchToToSlaveOnMasterAvailableForSomeoneElse() throws Throwable
{
// Given
InstanceId me = new InstanceId( 1 );
HighAvailabilityMemberContext context = new SimpleHighAvailabilityMemberContext( me );
AvailabilityGuard guard = mock( AvailabilityGuard.class );
ClusterMembers members = mock( ClusterMembers.class );
ClusterMemberEvents events = mock( ClusterMemberEvents.class );
final Set<ClusterMemberListener> listener = new HashSet<ClusterMemberListener>();
doAnswer( new Answer()
{
@Override
public Object answer( InvocationOnMock invocation ) throws Throwable
{
listener.add( (ClusterMemberListener) invocation.getArguments()[0] );
return null;
}
} ).when( events ).addClusterMemberListener( Matchers.<ClusterMemberListener>any() );
Election election = mock( Election.class );
StringLogger logger = mock( StringLogger.class );
HighAvailabilityMemberStateMachine toTest =
new HighAvailabilityMemberStateMachine( context, guard, members, events, election, logger );
toTest.init();
ClusterMemberListener theListener = listener.iterator().next();
HAStateChangeListener probe = new HAStateChangeListener();
toTest.addHighAvailabilityMemberListener( probe );
// When
theListener.memberIsAvailable( HighAvailabilityModeSwitcher.MASTER, new InstanceId( 2 ), URI.create( "ha://whatever" ) );
// Then
assertThat( listener.size(), equalTo( 1 ) ); // Sanity check.
assertThat( toTest.getCurrentState(), equalTo( HighAvailabilityMemberState.TO_SLAVE ) );
assertThat( probe.masterIsAvailable, is( true ) );
}
private static final class HAStateChangeListener implements HighAvailabilityMemberListener
{
boolean masterIsElected = false;
boolean masterIsAvailable = false;
boolean slaveIsAvailable = false;
boolean instanceStops = false;
HighAvailabilityMemberChangeEvent lastEvent = null;
@Override
public void masterIsElected( HighAvailabilityMemberChangeEvent event )
{
masterIsElected = true;
masterIsAvailable = false;
slaveIsAvailable = false;
instanceStops = false;
lastEvent = event;
}
@Override
public void masterIsAvailable( HighAvailabilityMemberChangeEvent event )
{
masterIsElected = false;
masterIsAvailable = true;
slaveIsAvailable = false;
instanceStops = false;
lastEvent = event;
}
@Override
public void slaveIsAvailable( HighAvailabilityMemberChangeEvent event )
{
masterIsElected = false;
masterIsAvailable = false;
slaveIsAvailable = true;
instanceStops = false;
lastEvent = event;
}
@Override
public void instanceStops( HighAvailabilityMemberChangeEvent event )
{
masterIsElected = false;
masterIsAvailable = false;
slaveIsAvailable = false;
instanceStops = true;
lastEvent = event;
}
}
}
|
package it.xsemantics.example.fj.tests.loader;
import it.xsemantics.example.fj.FJStandaloneSetup;
import it.xsemantics.example.fj.fj.Program;
import it.xsemantics.example.fj.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import com.google.inject.Injector;
/**
* @author bettini
*
* Loads (and parses) a local test fj file
*/
public class FJTestLoader {
public static final String OBJECT_FJ = "Object.fj";
public static final String PLATFORM_URI_FOR_FJ_LIB = "platform:/resource/it.xsemantics.example.fj.tests/src/it/xsemantics/example/fj/lib/";
public static final String OBJECT_FJ_URI = PLATFORM_URI_FOR_FJ_LIB
+ OBJECT_FJ;
Injector injector = new FJStandaloneSetup()
.createInjectorAndDoEMFRegistration();
private XtextResourceSet resourceSet;
public FJTestLoader() throws IOException {
new org.eclipse.emf.mwe.utils.StandaloneSetup().setPlatformUri("../");
resourceSet = injector.getInstance(XtextResourceSet.class);
resourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL,
Boolean.TRUE);
//resourceSet.getResource(uriForFjLibFiles(OBJECT_FJ), true);
Resource resource = resourceSet.createResource(URI
.createURI("dummy:/Object.fj"));
String program = "class Object { } ";
InputStream in = new ByteArrayInputStream(program.getBytes());
resource.load(in, resourceSet.getLoadOptions());
}
public Resource createResource() {
return resourceSet.createResource(URI.createURI("http:///My.fj"));
}
public Resource loadResource(String fileName) {
return resourceSet.getResource(uriForFjTestFiles(fileName), true);
}
protected URI uriForFjTestFiles(String fileName) {
return URI
.createURI("platform:/resource/it.xsemantics.example.fj.tests/tests/"
+ fileName);
}
protected URI uriForFjLibFiles(String fileName) {
return URI
.createURI(PLATFORM_URI_FOR_FJ_LIB
+ fileName);
}
public Resource loadFromString(String program) throws IOException {
Resource resource = resourceSet.createResource(URI
.createURI("dummy:/example.fj"));
InputStream in = new ByteArrayInputStream(program.getBytes());
resource.load(in, resourceSet.getLoadOptions());
return resource;
}
public Injector getInjector() {
return injector;
}
public Program loadProgramFromString(String program) throws IOException {
return (Program)loadFromString(program).getContents().get(0);
}
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
FJTestLoader loader = new FJTestLoader();
Resource resource = loader.loadResource("one_class.fj");
EObject program = resource.getContents().get(0);
System.out.println(new ModelPrinter().doSwitch(program));
resource = loader.loadFromString("class A { A a; } class B extends A { B b; }");
program = resource.getContents().get(0);
System.out.println(new ModelPrinter().doSwitch(program));
}
}
|
package org.exist.indexing.lucene.analyzers;
import org.apache.lucene.analysis.*;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopAnalyzer;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.miscellaneous.ASCIIFoldingFilter;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.StopwordAnalyzerBase;
import org.apache.lucene.analysis.util.WordlistLoader;
import org.apache.lucene.util.Version;
import org.exist.indexing.lucene.LuceneIndex;
import java.io.IOException;
import java.io.Reader;
/**
* A copy of StandardAnalyzer using an additional ASCIIFoldingFilter to
* strip diacritics.
*/
public class NoDiacriticsStandardAnalyzer extends StopwordAnalyzerBase {
/** Default maximum allowed token length */
public static final int DEFAULT_MAX_TOKEN_LENGTH = 255;
private int maxTokenLength = DEFAULT_MAX_TOKEN_LENGTH;
private final boolean replaceInvalidAcronym;
/** An unmodifiable set containing some common English words that are usually not
useful for searching. */
public static final CharArraySet STOP_WORDS_SET = StopAnalyzer.ENGLISH_STOP_WORDS_SET;
/** Builds an analyzer with the given stop words.
* @param matchVersion Lucene version to match See {@link
* <a href="#version">above</a>}
* @param stopWords stop words */
public NoDiacriticsStandardAnalyzer(Version matchVersion, CharArraySet stopWords) {
super(matchVersion, stopWords);
replaceInvalidAcronym = matchVersion.onOrAfter(LuceneIndex.LUCENE_VERSION_IN_USE);
}
/** Builds an analyzer with the default stop words ({@link
* #STOP_WORDS_SET}).
* @param matchVersion Lucene version to match See {@link
* <a href="#version">above</a>}
*/
public NoDiacriticsStandardAnalyzer(Version matchVersion) {
this(matchVersion, STOP_WORDS_SET);
}
/** Builds an analyzer with the stop words from the given reader.
* @see WordlistLoader#getWordSet(Reader, Version)
* @param matchVersion Lucene version to match See {@link
* <a href="#version">above</a>}
* @param stopwords Reader to read stop words from */
public NoDiacriticsStandardAnalyzer(Version matchVersion, Reader stopwords) throws IOException {
this(matchVersion, WordlistLoader.getWordSet(stopwords, matchVersion));
}
/**
* Set maximum allowed token length. If a token is seen
* that exceeds this length then it is discarded. This
* setting only takes effect the next time tokenStream or
* reusableTokenStream is called.
*/
public void setMaxTokenLength(int length) {
maxTokenLength = length;
}
/**
* @see #setMaxTokenLength
*/
public int getMaxTokenLength() {
return maxTokenLength;
}
@Override
protected TokenStreamComponents createComponents(final String fieldName, final Reader reader) {
final StandardTokenizer src = new StandardTokenizer(matchVersion, reader);
src.setMaxTokenLength(maxTokenLength);
// src.setReplaceInvalidAcronym(replaceInvalidAcronym);
TokenStream tok = new StandardFilter(matchVersion, src);
tok = new ASCIIFoldingFilter(tok);
tok = new LowerCaseFilter(matchVersion, tok);
tok = new StopFilter(matchVersion, tok, stopwords);
return new TokenStreamComponents(src, tok);
// @Override
// protected boolean reset(final Reader reader) throws IOException {
// src.setMaxTokenLength(NoDiacriticsStandardAnalyzer.this.maxTokenLength);
// return super.reset(reader);
}
}
|
package io.github.factoryfx.factory.storage.migration.datamigration;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode;
import io.github.factoryfx.factory.FactoryBase;
import io.github.factoryfx.factory.jackson.SimpleObjectMapper;
import io.github.factoryfx.factory.storage.migration.metadata.DataStorageMetadataDictionary;
import java.util.*;
public class DataJsonNode {
private final ObjectNode jsonNode;
public DataJsonNode(ObjectNode jsonNode) {
this.jsonNode = jsonNode;
}
public void removeAttribute(String name){
jsonNode.remove(name);
}
public String getDataClassName(){
return jsonNode.get("@class").textValue();
}
public boolean match(String dataClassNameFullQualified){
return getDataClassName().equals(dataClassNameFullQualified);
}
public void renameAttribute(String previousAttributeName, String newAttributeName) {
jsonNode.set(newAttributeName, jsonNode.get(previousAttributeName));
jsonNode.remove(previousAttributeName);
}
public void renameClass(Class<? extends FactoryBase<?,?>> newDataClass) {
jsonNode.set("@class",new TextNode(newDataClass.getName()));
}
public DataJsonNode getChild(String attributeName) {
return new DataJsonNode((ObjectNode)jsonNode.get(attributeName).get("v"));
}
public DataJsonNode getChild(String attributeName, int index) {
if (!jsonNode.get(attributeName).isArray()){
throw new IllegalArgumentException("is not a reflist attribute: "+attributeName);
}
return new DataJsonNode((ObjectNode)jsonNode.get(attributeName).get(index));
}
public JsonNode getAttributeValue(String attribute) {
if (jsonNode.get(attribute)==null){
return null;
}
if (jsonNode.get(attribute).isArray()){
return jsonNode.get(attribute);
}
return jsonNode.get(attribute).get("v");
}
public void setAttributeValue(String attribute, JsonNode jsonNode) {
try {
if (jsonNode==null) {
((ObjectNode)jsonNode.get(attribute)).remove("v");
}
ObjectNode objectNode = JsonNodeFactory.instance.objectNode();
this.jsonNode.set(attribute, objectNode);
objectNode.set("v",jsonNode);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <V> V getAttributeValue(String attributeName, Class<V> valueClass, SimpleObjectMapper simpleObjectMapper) {
JsonNode attributeValue = getAttributeValue(attributeName);
if (attributeValue==null){
return null;
}
return simpleObjectMapper.treeToValue(attributeValue, valueClass);
}
public boolean isValidFactoryAttributeOrFactoryListAttribute(String attributeName, DataStorageMetadataDictionary dataStorageMetadataDictionary) {
return dataStorageMetadataDictionary.isReferenceAttribute(getDataClassName(),attributeName) && !dataStorageMetadataDictionary.isRemovedAttribute(getDataClassName(),attributeName);
}
public String getAttributeIdValue(String attributeName) {
return jsonNode.get(attributeName).get("v").asText();
}
private boolean isData(JsonNode jsonNode){
if (jsonNode==null){
return false;
}
if (jsonNode.fieldNames().hasNext()){
String fieldName = jsonNode.fieldNames().next();
return "@class".equals(fieldName);
}
return false;
}
public void collectChildren(List<DataJsonNode> dataJsonNodes){
for (JsonNode element : jsonNode) {
if (element.isArray()) {
for (JsonNode arrayElement : element) {
if (isData(arrayElement)) {
DataJsonNode child = new DataJsonNode((ObjectNode) arrayElement);
dataJsonNodes.add(child);
child.collectChildren(dataJsonNodes);
}
}
} else {
if (isData(element.get("v"))) {
DataJsonNode child = new DataJsonNode((ObjectNode) element.get("v"));
dataJsonNodes.add(child);
child.collectChildren(dataJsonNodes);
}
}
}
}
/**
* get children including himself
* @return children
*/
public List<DataJsonNode> collectChildrenFromRoot(){
List<DataJsonNode> dataJsonNode = new ArrayList<>();
dataJsonNode.add(this);
this.collectChildren(dataJsonNode);
return dataJsonNode;
}
//TODO return UUID
public String getId() {
return jsonNode.get("id").asText();
}
public <D/*extends Data*/> D asData(Class<D> valueClass, SimpleObjectMapper simpleObjectMapper) {
return simpleObjectMapper.treeToValue(jsonNode, valueClass);
}
public List<String> getAttributes(){
ArrayList<String> result = new ArrayList<>();
Iterator<Map.Entry<String, JsonNode>> field = jsonNode.fields();
while (field.hasNext()) {
Map.Entry<String, JsonNode> element = field.next();
if (element.getValue().isObject()){
result.add(element.getKey());
}
if (element.getValue().isArray()){
result.add(element.getKey());
}
}
return result;
}
public Map<String,DataJsonNode> collectChildrenMapFromRoot() {
HashMap<String, DataJsonNode> result = new HashMap<>();
for (DataJsonNode dataJsonNode : collectChildrenFromRoot()) {
result.put(dataJsonNode.getId(),dataJsonNode);
}
return result;
}
/**
* fix objects in removed attributes.
*
* References are serialized using JsonIdentityInfo
* That means first occurrence is the object and following are just the ids
* If the first occurrence is a removed attribute Jackson can't read the reference.
*
* @param dataStorageMetadataDictionary dataStorageMetadataDictionary
*/
public void fixIdsDeepFromRoot(DataStorageMetadataDictionary dataStorageMetadataDictionary){
Map<String, DataJsonNode> idToDataJson = collectChildrenMapFromRoot();
DataObjectIdFixer dataObjectIdFixer = new DataObjectIdFixer(idToDataJson);
for (DataJsonNode dataJsonNode : idToDataJson.values()) {
for (String attributeVariableName : dataJsonNode.getAttributes()) {
if (isValidFactoryAttributeOrFactoryListAttribute(attributeVariableName, dataStorageMetadataDictionary)) {
JsonNode attributeValue = dataJsonNode.getAttributeValue(attributeVariableName);
if (attributeValue != null) {
if (attributeValue.isArray()) {
int index = 0;
for (JsonNode arrayElement : attributeValue) {
final int setIndex=index;
dataObjectIdFixer.fixFactoryId(arrayElement, (value) -> ((ArrayNode)attributeValue).set(setIndex,value));
index++;
}
} else {
dataObjectIdFixer.fixFactoryId(attributeValue, (value) -> setAttributeValue(attributeVariableName, value));
}
}
}
}
}
}
public JsonNode getJsonNode(){
return this.jsonNode;
}
}
|
package org.ow2.chameleon.fuchsia.fake.discovery;
import org.apache.felix.ipojo.*;
import org.apache.felix.ipojo.annotations.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.ow2.chameleon.fuchsia.core.component.AbstractDiscoveryComponent;
import org.ow2.chameleon.fuchsia.core.component.DiscoveryService;
import org.ow2.chameleon.fuchsia.core.declaration.Constants;
import org.ow2.chameleon.fuchsia.core.declaration.ImportDeclaration;
import org.ow2.chameleon.fuchsia.core.declaration.ImportDeclarationBuilder;
import org.ow2.chameleon.fuchsia.fake.device.GenericDevice;
import org.ow2.chameleon.fuchsia.fake.discovery.monitor.Deployer;
import org.ow2.chameleon.fuchsia.fake.discovery.monitor.DirectoryMonitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;
import static org.apache.felix.ipojo.Factory.INSTANCE_NAME_PROPERTY;
/**
* This component instantiate a directory monitor (initially pointed to a directory in chameleon called "load") that reads all file placed there (as property files)
* and instantiate a {@link org.ow2.chameleon.fuchsia.fake.device.GenericDevice} according with the same properties as the ones declared in the property file and
* published an {@link ImportDeclaration}
*
* @author jeremy.savonet@gmail.com
* @author botelho (at) imag.fr
*/
@Component(name = "Fuchsia-FakeDiscovery-Factory")
@Provides(specifications = {DiscoveryService.class,Deployer.class})
@Instantiate(name = "Fuchsia-FakeDiscovery")
public class FakeDiscoveryBridge extends AbstractDiscoveryComponent implements Deployer {
@ServiceProperty(name = INSTANCE_NAME_PROPERTY)
private String name;
@ServiceProperty(name = FakeDiscoveryConstants.FAKE_DISCOVERY_PROPERTY_KEY_MONITORED_DIR_KEY,value = FakeDiscoveryConstants.FAKE_DISCOVERY_PROPERTY_KEY_MONITORED_DIR_VALUE)
private String monitoredDirectory;
@ServiceProperty(name = FakeDiscoveryConstants.FAKE_DISCOVERY_PROPERTY_POLLING_TIME_KEY,value = FakeDiscoveryConstants.FAKE_DISCOVERY_PROPERTY_POLLING_TIME_VALUE)
private Long pollingTime;
private final HashMap<String,ImportDeclaration> importDeclarationsFile = new HashMap<String, ImportDeclaration>();
private final HashMap<String,InstanceManager> devicesManaged =new LinkedHashMap<String, InstanceManager>();
public FakeDiscoveryBridge(BundleContext bundleContext) {
super(bundleContext);
}
@Validate
public void start() {
super.start();
try {
new DirectoryMonitor(new File(monitoredDirectory),pollingTime).start(getBundleContext());
getLogger().info("Discovery up and running.");
} catch (Exception e) {
getLogger().error("Failed to start {} for the directory {} and polling time {}, with the message '{}'", new String[]{DirectoryMonitor.class.getName(), monitoredDirectory, pollingTime.toString(), e.getMessage()});
}
}
@Invalidate
public void stop() {
super.stop();
getLogger().info("Discovery stopped.");
}
@Override
public Logger getLogger() {
return LoggerFactory.getLogger(this.getClass());
}
public String getName() {
return name;
}
private InstanceManager createAndRegisterFakeDevice(String deviceId) throws Exception {
try {
Collection<ServiceReference<Factory>> factory=getBundleContext().getServiceReferences(Factory.class,String.format("(%s=%s)","factory.name",FakeDiscoveryConstants.FAKE_DEVICE_FACTORY_NAME));
if(factory.size()==0) {
getLogger().error("No {} component is available in the platform. Impossible to create a fake device.", GenericDevice.class.getName());
throw new Exception(String.format("No %s component is available in the platform. Impossible to create a fake device.",GenericDevice.class.getName()));
}
if(factory.size()>1) {
getLogger().warn("Several components implementing {} were found. One will be picket randomly but this may indicate an issue.", GenericDevice.class.getName());
}
for (ServiceReference<Factory> factoryServiceReference : factory) {
Factory deviceIpojoFactory=(Factory)getBundleContext().getService(factoryServiceReference);
Hashtable deviceProperties=new Hashtable<String,Object>();
deviceProperties.put(Factory.INSTANCE_NAME_PROPERTY, "GenericDeviceInst-" + deviceId);
deviceProperties.put(GenericDevice.DEVICE_SERIAL_NUMBER, "SN-" + deviceId);
InstanceManager deviceInstanceManager=(InstanceManager)deviceIpojoFactory.createComponentInstance(deviceProperties);
devicesManaged.put(deviceId,deviceInstanceManager);
return deviceInstanceManager;
}
} catch (Exception e) {
throw new Exception(e);
}
return null;
}
private ImportDeclaration createAndRegisterImportDeclaration(HashMap<String, Object> metadata){
ImportDeclaration declaration = ImportDeclarationBuilder.fromMetadata(metadata).build();
registerImportDeclaration(declaration);
return declaration;
}
public boolean accept(File file) {
return true;
}
private Properties parseFile(File file) throws Exception {
Properties deviceReificationProperties = new Properties();
try {
InputStream is = new FileInputStream(file);
deviceReificationProperties.load(is);
} catch (Exception e) {
throw new Exception(String.format("Error reading file that represents a device. %s",file.getAbsoluteFile()));
}
if( !deviceReificationProperties.containsKey(Constants.ID) ||
!deviceReificationProperties.containsKey(Constants.DEVICE_TYPE)||
!deviceReificationProperties.containsKey(Constants.DEVICE_TYPE_SUB)){
throw new Exception(String.format("File cannot represent a device since it does not contain the information base to work as such",file.getAbsoluteFile()));
}
return deviceReificationProperties;
}
public void onFileCreate(File file) {
getLogger().info("File created {}", file.getAbsolutePath());
try {
Properties deviceReificationProperties=parseFile(file);
String deviceId=deviceReificationProperties.getProperty(Constants.ID);
createAndRegisterFakeDevice(deviceId);
HashMap<String, Object> metadata = new HashMap<String, Object>();
metadata.put(Constants.DEVICE_ID, deviceId);
for(Map.Entry<Object,Object> element:deviceReificationProperties.entrySet()){
Object replacedObject=metadata.put(element.getKey().toString(), element.getValue());
if(replacedObject!=null){
getLogger().warn("ImportationDeclaration: replacing metadata key {}, that contained the value {} by the new value {}",new Object[]{element.getKey(),replacedObject,element.getValue()});
}
}
ImportDeclaration declaration=createAndRegisterImportDeclaration(metadata);
importDeclarationsFile.put(file.getAbsolutePath(),declaration);
} catch (Exception e) {
getLogger().error(e.getMessage());
}
}
//TODO this have to be rechecked, this is an pessimist approach
public void onFileChange(File file) {
getLogger().info("File updated {}",file.getAbsolutePath());
onFileDelete(file);
onFileCreate(file);
}
public void onFileDelete(File file) {
getLogger().info("File removed {}",file.getAbsolutePath() );
ImportDeclaration declaration=importDeclarationsFile.get(file.getAbsolutePath());
if(importDeclarationsFile.remove(file.getAbsolutePath())==null){
getLogger().error("Failed to unregister device-file mapping ({}), it did not existed before.",file.getAbsolutePath());
} else {
getLogger().info("Device-file mapping removed.");
}
try{
unregisterImportDeclaration(declaration);
} catch(IllegalStateException e){
getLogger().error("Failed to unregister import declaration for the device {}, it did not existed before.",declaration.getMetadata());
}
try {
String deviceId=(String)declaration.getMetadata().get(Constants.DEVICE_ID);
devicesManaged.get(deviceId).dispose();
} catch(NullPointerException e){
getLogger().error("Failed to disconnect device {}, this device was not registered by this discovery",(String)declaration.getMetadata().get(Constants.DEVICE_ID));
}
}
public void open(Collection<File> files) {
for (File file : files) {
onFileChange(file);
}
}
public void close() { }
}
|
package edu.wustl.catissuecore.domain.pathology;
import edu.wustl.common.actionForm.AbstractActionForm;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.exception.AssignDataException;
/**
* Represents the concept referent of the pathology report.
* @hibernate.class
* table="CATISSUE_CONCEPT_REFERENT"
*/
public class ConceptReferent extends AbstractDomainObject
{
/**
* End offset of the concept in the report.
*/
protected Long endOffset;
/**
* system generated unique id.
*/
protected Long id;
/**
* modifier flag.
*/
protected Boolean isModifier;
/**
* The concept is negated one or not.
*/
protected Boolean isNegated;
/**
* start offset of the concept in the report.
*/
protected Long startOffset;
/**
* concept associated with the report.
*/
protected Concept concept;
/**
* Concept referent classification associated with the current concept referent.
*/
protected ConceptReferentClassification conceptReferentClassification;
/**
* Deidentified report of the current concept referent.
*/
protected DeidentifiedSurgicalPathologyReport deidentifiedSurgicalPathologyReport;
/**
* Constructor
*/
public ConceptReferent()
{
}
/**
* @return concept associated with current concept referent.
* @hibernate.many-to-one column="CONCEPT_ID" class="edu.wustl.catissuecore.domain.pathology.Concept" cascade="save-update"
*/
public Concept getConcept()
{
return concept;
}
/**
* @param concept sets concept
*/
public void setConcept(Concept concept)
{
this.concept = concept;
}
/**
* @return concept referent classification
* @hibernate.many-to-one class="edu.wustl.catissuecore.domain.pathology.ConceptReferentClassification" column="CONCEPT_CLASSIFICATION_ID" cascade="save-update"
*/
public ConceptReferentClassification getConceptReferentClassification()
{
return conceptReferentClassification;
}
/**
* @param conceptReferentClassification concept referent classification
*/
public void setConceptReferentClassification(
ConceptReferentClassification conceptReferentClassification)
{
this.conceptReferentClassification = conceptReferentClassification;
}
/**
* @return deidentified report associated with the concept referent.
* @hibernate.many-to-one name="deidentifiedSurgicalPathologyReport"
* class="edu.wustl.catissuecore.domain.pathology.DeidentifiedSurgicalPathologyReport"
* column="DEIDENTIFIED_REPORT_ID" not-null="false"
*/
public DeidentifiedSurgicalPathologyReport getDeidentifiedSurgicalPathologyReport()
{
return deidentifiedSurgicalPathologyReport;
}
/**
* @param deidentifiedSurgicalPathologyReport sets the deidentified report.
*/
public void setDeidentifiedSurgicalPathologyReport(
DeidentifiedSurgicalPathologyReport deidentifiedSurgicalPathologyReport)
{
this.deidentifiedSurgicalPathologyReport = deidentifiedSurgicalPathologyReport;
}
/**
* @return end offset
* @hibernate.property type="long" column="END_OFFSET" length="30"
*/
public Long getEndOffset()
{
return endOffset;
}
/**
* @param endOffset sets end offset
*/
public void setEndOffset(Long endOffset)
{
this.endOffset = endOffset;
}
/**
* @return system generated id for concept referent
* @hibernate.id name="id" column="IDENTIFIER" type="long" length="30"
* unsaved-value="null" generator-class="native"
* @hibernate.generator-param name="sequence" value="CATISSUE_CONCEPT_REFERENT_SEQ"
*/
public Long getId()
{
return id;
}
/**
* @param id sets system generated id
*/
public void setId(Long id)
{
this.id = id;
}
/**
* @return modifier flag
* @hibernate.property type="int" length="30" column="IS_MODIFIER"
*/
public Boolean getIsModifier()
{
return isModifier;
}
/**
* @param isModifier sets modifier flag
*/
public void setIsModifier(Boolean isModifier)
{
this.isModifier = isModifier;
}
/**
* @return negated flag
* @hibernate.property type="int" length="30" column="IS_NEGATED"
*/
public Boolean getIsNegated()
{
return isNegated;
}
/**
* @param isNegated sets negated flag
*/
public void setIsNegated(Boolean isNegated)
{
this.isNegated = isNegated;
}
/**
* @return start offset
* @hibernate.property type="long" length="30" column="START_OFFSET"
*/
public Long getStartOffset()
{
return startOffset;
}
/**
* @param startOffset sets start offset
*/
public void setStartOffset(Long startOffset)
{
this.startOffset = startOffset;
}
public void setAllValues(AbstractActionForm abstractForm) throws AssignDataException
{
// TODO Auto-generated method stub
}
}
|
package uk.gov.hscic.appointments;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.composite.CodingDt;
import ca.uhn.fhir.model.dstu2.composite.IdentifierDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.resource.Appointment;
import ca.uhn.fhir.model.dstu2.resource.Appointment.Participant;
import ca.uhn.fhir.model.dstu2.resource.OperationOutcome;
import ca.uhn.fhir.model.dstu2.valueset.AppointmentStatusEnum;
import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum;
import ca.uhn.fhir.model.dstu2.valueset.IssueTypeEnum;
import ca.uhn.fhir.model.dstu2.valueset.ParticipationStatusEnum;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.annotation.Create;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.ResourceParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.annotation.Update;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.param.DateRangeParam;
import ca.uhn.fhir.rest.param.ParamPrefixEnum;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException;
import ca.uhn.fhir.rest.server.exceptions.UnclassifiedServerFailureException;
import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException;
import java.text.MessageFormat;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.stream.Collectors;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import uk.gov.hscic.OperationOutcomeFactory;
import uk.gov.hscic.SystemCode;
import uk.gov.hscic.SystemURL;
import uk.gov.hscic.appointment.appointment.AppointmentSearch;
import uk.gov.hscic.appointment.appointment.AppointmentStore;
import uk.gov.hscic.appointment.slot.SlotSearch;
import uk.gov.hscic.appointment.slot.SlotStore;
import uk.gov.hscic.common.validators.ValueSetValidator;
import uk.gov.hscic.location.LocationSearch;
import uk.gov.hscic.model.appointment.AppointmentDetail;
import uk.gov.hscic.model.appointment.SlotDetail;
import uk.gov.hscic.model.location.LocationDetails;
import uk.gov.hscic.model.patient.PatientDetails;
import uk.gov.hscic.model.practitioner.PractitionerDetails;
import uk.gov.hscic.patient.details.PatientSearch;
import uk.gov.hscic.practitioner.PractitionerSearch;
@Component
public class AppointmentResourceProvider implements IResourceProvider {
@Autowired
private AppointmentSearch appointmentSearch;
@Autowired
private AppointmentStore appointmentStore;
@Autowired
private SlotSearch slotSearch;
@Autowired
private SlotStore slotStore;
@Autowired
private PatientSearch patientSearch;
@Autowired
private PractitionerSearch practitionerSearch;
@Autowired
private LocationSearch locationSearch;
@Autowired
private ValueSetValidator valueSetValidator;
@Override
public Class<Appointment> getResourceType() {
return Appointment.class;
}
@Read(version = true)
public Appointment getAppointmentById(@IdParam IdDt appointmentId) {
Appointment appointment = null;
try {
Long id = appointmentId.getIdPartAsLong();
AppointmentDetail appointmentDetail = null;
// are we dealing with a request for a specific version of the
// appointment
if (appointmentId.hasVersionIdPart()) {
try {
Long versionId = appointmentId.getVersionIdPartAsLong();
appointmentDetail = appointmentSearch.findAppointmentByIDAndLastUpdated(id, new Date(versionId));
if (appointmentDetail == null) {
// 404 version of resource not found
String msg = String.format("No appointment details found for ID: %s with versionId %s",
appointmentId.getIdPart(), versionId);
throw OperationOutcomeFactory.buildOperationOutcomeException(new ResourceNotFoundException(msg),
SystemCode.REFERENCE_NOT_FOUND, IssueTypeEnum.NOT_FOUND);
}
} catch (NumberFormatException nfe) {
// 404 resource not found - the versionId is valid according
// to FHIR
// however we have no entities matching that versionId
String msg = String.format("The version ID %s of the Appointment (ID - %s) is not valid",
appointmentId.getVersionIdPart(), id);
throw OperationOutcomeFactory.buildOperationOutcomeException(new ResourceNotFoundException(msg),
SystemCode.REFERENCE_NOT_FOUND, IssueTypeEnum.NOT_FOUND);
}
} else {
appointmentDetail = appointmentSearch.findAppointmentByID(id);
if (appointmentDetail == null) {
// 404 resource not found
String msg = String.format("No appointment details found for ID: %s", appointmentId.getIdPart());
throw OperationOutcomeFactory.buildOperationOutcomeException(new ResourceNotFoundException(msg),
SystemCode.REFERENCE_NOT_FOUND, IssueTypeEnum.NOT_FOUND);
}
}
appointment = appointmentDetailToAppointmentResourceConverter(appointmentDetail);
} catch (NumberFormatException nfe) {
// 404 resource not found - the identifier is valid according to
// FHIR
// however we have no entities matching that identifier
throw OperationOutcomeFactory.buildOperationOutcomeException(
new ResourceNotFoundException("No appointment details found for ID: " + appointmentId.getIdPart()),
SystemCode.REFERENCE_NOT_FOUND, IssueTypeEnum.NOT_FOUND);
}
return appointment;
}
@Search
public List<Appointment> getAppointmentsForPatientIdAndDates(@RequiredParam(name = "patient") IdDt patientLocalId,
@OptionalParam(name = "start") DateRangeParam startDate) {
Date startLowerDate = null;
Date startUppderDate = null;
if (startDate != null) {
if (startDate.getLowerBound() != null) {
if (startDate.getLowerBound().getPrefix() == ParamPrefixEnum.GREATERTHAN) {
startLowerDate = startDate.getLowerBound().getValue();
} else {
if (startDate.getLowerBound().getPrecision() == TemporalPrecisionEnum.DAY) {
startLowerDate = startDate.getLowerBound().getValue(); // Remove
// day
// make
// time
// inclusive
// parameter
// date
} else {
startLowerDate = new Date(startDate.getLowerBound().getValue().getTime() - 1000); // Remove
// second
// make
// time
// inclusive
// parameter
// date
}
}
}
if (startDate.getUpperBound() != null) {
if (startDate.getUpperBound().getPrefix() == ParamPrefixEnum.LESSTHAN) {
startUppderDate = startDate.getUpperBound().getValue();
} else {
if (startDate.getUpperBound().getPrecision() == TemporalPrecisionEnum.DAY) {
startUppderDate = new Date(startDate.getUpperBound().getValue().getTime() + 86400000); // Add
// day
// make
// time
// inclusive
// parameter
// date
} else {
startUppderDate = new Date(startDate.getUpperBound().getValue().getTime() + 1000); // Add
// second
// make
// time
// inclusive
// parameter
// date
}
}
}
}
return appointmentSearch.searchAppointments(patientLocalId.getIdPartAsLong(), startLowerDate, startUppderDate)
.stream().map(this::appointmentDetailToAppointmentResourceConverter).collect(Collectors.toList());
}
@Create
public MethodOutcome createAppointment(@ResourceParam Appointment appointment) {
if (appointment.getStatus() == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("No status supplied"), SystemCode.INVALID_RESOURCE,
IssueTypeEnum.INVALID_CONTENT);
}
if (appointment.getStart() == null || appointment.getEnd() == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Both start and end date are required"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
if (appointment.getSlot().isEmpty()) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("At least one slot is required"), SystemCode.INVALID_RESOURCE,
IssueTypeEnum.INVALID_CONTENT);
}
if (appointment.getParticipant().isEmpty()) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("At least one participant is required"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
if (!appointment.getIdentifierFirstRep().isEmpty() && appointment.getIdentifierFirstRep().getValue() == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Appointment identifier value is required"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
boolean hasRequiredResources = appointment.getParticipant().stream()
.map(participant -> participant.getActor().getReference().getResourceType())
.collect(Collectors.toList()).containsAll(Arrays.asList("Patient", "Practitioner"));
if (!hasRequiredResources) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException(
"Appointment resource is not a valid resource required valid Patient and Practitioner"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
for (Participant participant : appointment.getParticipant()) {
String resourcePart = participant.getActor().getReference().getResourceType();
String idPart = participant.getActor().getReference().getIdPart();
switch (resourcePart) {
case "Patient":
PatientDetails patient = patientSearch.findPatientByInternalID(idPart);
if (patient == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Patient resource reference is not a valid resource"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
break;
case "Practitioner":
PractitionerDetails practitioner = practitionerSearch.findPractitionerDetails(idPart);
if (practitioner == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Practitioner resource reference is not a valid resource"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
break;
case "Location":
LocationDetails location = locationSearch.findLocationById(idPart);
if (location == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Location resource reference is not a valid resource"),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
break;
}
}
// Store New Appointment
AppointmentDetail appointmentDetail = appointmentResourceConverterToAppointmentDetail(appointment);
List<SlotDetail> slots = new ArrayList<>();
for (Long slotId : appointmentDetail.getSlotIds()) {
SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
if (slotDetail == null) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException(String.format("Slot resource reference value %s is not a valid resource.",
slotId)),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
slots.add(slotDetail);
}
appointmentDetail = appointmentStore.saveAppointment(appointmentDetail, slots);
for (SlotDetail slot : slots) {
// slot.setAppointmentId(appointmentDetail.getId());
slot.setFreeBusyType("BUSY");
slot.setLastUpdated(new Date());
slotStore.saveSlot(slot);
}
// Build response containing the new resource id
MethodOutcome methodOutcome = new MethodOutcome();
methodOutcome.setId(new IdDt("Appointment", appointmentDetail.getId()));
methodOutcome.setResource(appointmentDetailToAppointmentResourceConverter(appointmentDetail));
methodOutcome.setCreated(Boolean.TRUE);
return methodOutcome;
}
@Update
public MethodOutcome updateAppointment(@IdParam IdDt appointmentId, @ResourceParam Appointment appointment) {
MethodOutcome methodOutcome = new MethodOutcome();
OperationOutcome operationalOutcome = new OperationOutcome();
AppointmentDetail appointmentDetail = appointmentResourceConverterToAppointmentDetail(appointment);
// URL ID and Resource ID must be the same
if (!Objects.equals(appointmentId.getIdPartAsLong(), appointmentDetail.getId())) {
operationalOutcome.addIssue().setSeverity(IssueSeverityEnum.ERROR).setDetails("Id in URL ("
+ appointmentId.getIdPart() + ") should match Id in Resource (" + appointmentDetail.getId() + ")");
methodOutcome.setOperationOutcome(operationalOutcome);
return methodOutcome;
}
// Make sure there is an existing appointment to be amended
AppointmentDetail oldAppointmentDetail = appointmentSearch.findAppointmentByID(appointmentId.getIdPartAsLong());
if (oldAppointmentDetail == null) {
operationalOutcome.addIssue().setSeverity(IssueSeverityEnum.ERROR)
.setDetails("No appointment details found for ID: " + appointmentId.getIdPart());
methodOutcome.setOperationOutcome(operationalOutcome);
return methodOutcome;
}
String oldAppointmentVersionId = String.valueOf(oldAppointmentDetail.getLastUpdated().getTime());
String newAppointmentVersionId = appointmentId.getVersionIdPart();
if (newAppointmentVersionId != null && !newAppointmentVersionId.equalsIgnoreCase(oldAppointmentVersionId)) {
throw new ResourceVersionConflictException("The specified version (" + newAppointmentVersionId
+ ") did not match the current resource version (" + oldAppointmentVersionId + ")");
}
// Determin if it is a cancel or an amend
if (appointmentDetail.getCancellationReason() != null) {
if (appointmentDetail.getCancellationReason().isEmpty()) {
operationalOutcome.addIssue().setSeverity(IssueSeverityEnum.ERROR)
.setDetails("The cancellation reason can not be blank");
methodOutcome.setOperationOutcome(operationalOutcome);
return methodOutcome;
}
// This is a Cancellation - so copy across fields which can be
// altered
boolean cancelComparisonResult = compareAppointmentsForInvalidPropertyCancel(oldAppointmentDetail,
appointmentDetail);
if (cancelComparisonResult) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnclassifiedServerFailureException(403, "Invalid Appointment property has been amended"),
SystemCode.BAD_REQUEST, IssueTypeEnum.FORBIDDEN);
}
oldAppointmentDetail.setCancellationReason(appointmentDetail.getCancellationReason());
String oldStatus = oldAppointmentDetail.getStatus();
appointmentDetail = oldAppointmentDetail;
appointmentDetail.setStatus("cancelled");
if (!"cancelled".equalsIgnoreCase(oldStatus)) {
for (Long slotId : appointmentDetail.getSlotIds()) {
SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
// slotDetail.setAppointmentId(null);
slotDetail.setFreeBusyType("FREE");
slotDetail.setLastUpdated(new Date());
slotStore.saveSlot(slotDetail);
}
}
} else {
boolean amendComparisonResult = compareAppointmentsForInvalidPropertyAmend(appointmentDetail,
oldAppointmentDetail);
if (amendComparisonResult) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnclassifiedServerFailureException(403, "Invalid Appointment property has been amended"),
SystemCode.BAD_REQUEST, IssueTypeEnum.FORBIDDEN);
}
// This is an Amend
oldAppointmentDetail.setComment(appointmentDetail.getComment());
oldAppointmentDetail.setReasonCode(appointmentDetail.getReasonCode());
oldAppointmentDetail.setDescription(appointmentDetail.getDescription());
oldAppointmentDetail.setReasonDisplay(appointmentDetail.getReasonDisplay());
oldAppointmentDetail.setTypeCode(appointmentDetail.getTypeCode());
oldAppointmentDetail.setTypeDisplay(appointmentDetail.getTypeDisplay());
appointmentDetail = oldAppointmentDetail;
}
List<SlotDetail> slots = new ArrayList<>();
for (Long slotId : appointmentDetail.getSlotIds()) {
SlotDetail slotDetail = slotSearch.findSlotByID(slotId);
if (slotDetail == null) {
throw new UnprocessableEntityException("Slot resource reference is not a valid resource");
}
slots.add(slotDetail);
}
appointmentDetail.setLastUpdated(new Date()); // Update version and
// lastUpdated timestamp
appointmentDetail = appointmentStore.saveAppointment(appointmentDetail, slots);
methodOutcome.setId(new IdDt("Appointment", appointmentDetail.getId()));
methodOutcome.setResource(appointmentDetailToAppointmentResourceConverter(appointmentDetail));
return methodOutcome;
}
private boolean compareAppointmentsForInvalidPropertyAmend(AppointmentDetail oldAppointmentDetail,
AppointmentDetail appointmentDetail) {
List<Boolean> results = new ArrayList<>();
results.add(Objects.equals(oldAppointmentDetail.getDescription(), appointmentDetail.getDescription()));
results.add(Objects.equals(oldAppointmentDetail.getId(), appointmentDetail.getId()));
results.add(Objects.equals(oldAppointmentDetail.getStatus(), appointmentDetail.getStatus()));
results.add(Objects.equals(oldAppointmentDetail.getTypeCode(), appointmentDetail.getTypeCode()));
results.add(Objects.equals(oldAppointmentDetail.getTypeDisplay(), appointmentDetail.getTypeDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getTypeText(), appointmentDetail.getTypeText()));
results.add(Objects.equals(oldAppointmentDetail.getStartDateTime(), appointmentDetail.getStartDateTime()));
results.add(Objects.equals(oldAppointmentDetail.getEndDateTime(), appointmentDetail.getEndDateTime()));
results.add(Objects.equals(oldAppointmentDetail.getPatientId(), appointmentDetail.getPatientId()));
results.add(Objects.equals(oldAppointmentDetail.getPractitionerId(), appointmentDetail.getPractitionerId()));
results.add(Objects.equals(oldAppointmentDetail.getLocationId(), appointmentDetail.getLocationId()));
results.add(Objects.equals(oldAppointmentDetail.getMinutesDuration(), appointmentDetail.getMinutesDuration()));
results.add(Objects.equals(oldAppointmentDetail.getPriority(), appointmentDetail.getPriority()));
results.add(Objects.equals(oldAppointmentDetail.getComment(), appointmentDetail.getComment()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionBookURL(), appointmentDetail.getExtensionBookURL()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionBookCode(), appointmentDetail.getExtensionBookCode()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionBookDisplay(),
appointmentDetail.getExtensionBookDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionCatURL(), appointmentDetail.getExtensionCatURL()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionCatCode(), appointmentDetail.getExtensionCatCode()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionCatDisplay(),
appointmentDetail.getExtensionCatDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConURL(), appointmentDetail.getExtensionConURL()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConURL(), appointmentDetail.getExtensionConURL()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConDisplay(),
appointmentDetail.getExtensionConDisplay()));
return results.contains(false);
}
private boolean compareAppointmentsForInvalidPropertyCancel(AppointmentDetail oldAppointmentDetail,
AppointmentDetail appointmentDetail) {
List<Boolean> results = new ArrayList<>();
results.add(Objects.equals(oldAppointmentDetail.getDescription(), appointmentDetail.getDescription()));
results.add(Objects.equals(oldAppointmentDetail.getId(), appointmentDetail.getId()));
results.add(Objects.equals(oldAppointmentDetail.getTypeCode(), appointmentDetail.getTypeCode()));
results.add(Objects.equals(oldAppointmentDetail.getTypeDisplay(), appointmentDetail.getTypeDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getTypeText(), appointmentDetail.getTypeText()));
results.add(Objects.equals(oldAppointmentDetail.getPatientId(), appointmentDetail.getPatientId()));
results.add(Objects.equals(oldAppointmentDetail.getPractitionerId(), appointmentDetail.getPractitionerId()));
results.add(Objects.equals(oldAppointmentDetail.getLocationId(), appointmentDetail.getLocationId()));
results.add(Objects.equals(oldAppointmentDetail.getMinutesDuration(), appointmentDetail.getMinutesDuration()));
results.add(Objects.equals(oldAppointmentDetail.getPriority(), appointmentDetail.getPriority()));
results.add(Objects.equals(oldAppointmentDetail.getComment(), appointmentDetail.getComment()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionBookURL(), appointmentDetail.getExtensionBookURL()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionBookCode(), appointmentDetail.getExtensionBookCode()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionBookDisplay(),
appointmentDetail.getExtensionBookDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionCatURL(), appointmentDetail.getExtensionCatURL()));
results.add(
Objects.equals(oldAppointmentDetail.getExtensionCatCode(), appointmentDetail.getExtensionCatCode()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionCatDisplay(),
appointmentDetail.getExtensionCatDisplay()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConURL(), appointmentDetail.getExtensionConURL()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConURL(), appointmentDetail.getExtensionConURL()));
results.add(Objects.equals(oldAppointmentDetail.getExtensionConDisplay(),
appointmentDetail.getExtensionConDisplay()));
return results.contains(false);
}
public Appointment appointmentDetailToAppointmentResourceConverter(AppointmentDetail appointmentDetail) {
Appointment appointment = new Appointment();
appointment.setId(String.valueOf(appointmentDetail.getId()));
appointment.getMeta().setLastUpdated(appointmentDetail.getLastUpdated());
appointment.getMeta().setVersionId(String.valueOf(appointmentDetail.getLastUpdated().getTime()));
appointment.getMeta().addProfile(SystemURL.SD_GPC_APPOINTMENT);
appointment.addUndeclaredExtension(false, SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CANCELLATION_REASON,
new StringDt(appointmentDetail.getCancellationReason()));
appointment.setIdentifier(Collections.singletonList(
new IdentifierDt(SystemURL.ID_GPC_APPOINTMENT_IDENTIFIER, String.valueOf(appointmentDetail.getId()))));
switch (appointmentDetail.getStatus().toLowerCase(Locale.UK)) {
case "pending":
appointment.setStatus(AppointmentStatusEnum.PENDING);
break;
case "booked":
appointment.setStatus(AppointmentStatusEnum.BOOKED);
break;
case "arrived":
appointment.setStatus(AppointmentStatusEnum.ARRIVED);
break;
case "fulfilled":
appointment.setStatus(AppointmentStatusEnum.FULFILLED);
break;
case "cancelled":
appointment.setStatus(AppointmentStatusEnum.CANCELLED);
break;
case "noshow":
appointment.setStatus(AppointmentStatusEnum.NO_SHOW);
break;
default:
appointment.setStatus(AppointmentStatusEnum.PENDING);
break;
}
CodingDt coding = new CodingDt().setSystem(SystemURL.HL7_VS_C80_PRACTICE_CODES)
.setCode(String.valueOf(appointmentDetail.getTypeCode()))
.setDisplay(appointmentDetail.getTypeDisplay());
CodeableConceptDt codableConcept = new CodeableConceptDt().addCoding(coding);
codableConcept.setText(appointmentDetail.getTypeDisplay());
appointment.setType(codableConcept);
appointment.getType().setText(appointmentDetail.getTypeText());
String reasonCode = appointmentDetail.getReasonCode();
String reasonDisplay = appointmentDetail.getReasonDisplay();
if (reasonCode != null && reasonDisplay != null) {
CodingDt codingReason = new CodingDt().setSystem(SystemURL.SNOMED).setCode(String.valueOf(reasonCode))
.setDisplay(reasonDisplay);
CodeableConceptDt codableConceptReason = new CodeableConceptDt().addCoding(codingReason);
codableConceptReason.setText(reasonDisplay);
appointment.setReason(codableConceptReason);
}
appointment.setStartWithMillisPrecision(appointmentDetail.getStartDateTime());
appointment.setEndWithMillisPrecision(appointmentDetail.getEndDateTime());
List<ResourceReferenceDt> slotResources = new ArrayList<>();
for (Long slotId : appointmentDetail.getSlotIds()) {
slotResources.add(new ResourceReferenceDt("Slot/" + slotId));
}
appointment.setSlot(slotResources);
appointment.setComment(appointmentDetail.getComment());
appointment.setDescription(appointmentDetail.getDescription());
appointment.addParticipant().setActor(new ResourceReferenceDt("Patient/" + appointmentDetail.getPatientId()))
.setStatus(ParticipationStatusEnum.ACCEPTED);
appointment.addParticipant()
.setActor(new ResourceReferenceDt("Practitioner/" + appointmentDetail.getPractitionerId()))
.setStatus(ParticipationStatusEnum.ACCEPTED);
if (null != appointmentDetail.getLocationId()) {
appointment.addParticipant()
.setActor(new ResourceReferenceDt("Location/" + appointmentDetail.getLocationId()))
.setStatus(ParticipationStatusEnum.ACCEPTED);
}
return appointment;
}
private Date getLastUpdated(Date lastUpdated) {
if (lastUpdated == null) {
lastUpdated = new Date();
}
// trim off milliseconds as we do not store
// to this level of granularity
Instant instant = lastUpdated.toInstant();
instant = instant.truncatedTo(ChronoUnit.SECONDS);
lastUpdated = Date.from(instant);
return lastUpdated;
}
public AppointmentDetail appointmentResourceConverterToAppointmentDetail(Appointment appointment) {
validateAppointmentExtensions(appointment.getUndeclaredExtensions());
AppointmentDetail appointmentDetail = new AppointmentDetail();
appointmentDetail.setId(appointment.getId().getIdPartAsLong());
appointmentDetail.setLastUpdated(getLastUpdated(appointment.getMeta().getLastUpdated()));
List<ExtensionDt> extension = appointment
.getUndeclaredExtensionsByUrl(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CANCELLATION_REASON);
List<ExtensionDt> bookingExtension = appointment
.getUndeclaredExtensionsByUrl(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_BOOKING_METHOD);
List<ExtensionDt> contactExtension = appointment
.getUndeclaredExtensionsByUrl(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CONTACT_METHOD);
List<ExtensionDt> categoryExtension = appointment
.getUndeclaredExtensionsByUrl(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CATEGORY);
if (extension != null && !extension.isEmpty()) {
IBaseDatatype value = extension.get(0).getValue();
if (null == value) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new InvalidRequestException("Cancellation reason missing."), SystemCode.BAD_REQUEST,
IssueTypeEnum.INVALID_CONTENT);
}
appointmentDetail.setCancellationReason(value.toString());
}
if (bookingExtension != null && !bookingExtension.isEmpty()) {
CodeableConceptDt values = (CodeableConceptDt) bookingExtension.get(0).getValue();
appointmentDetail = addBookExtensionDetails(values, appointmentDetail);
}
if (contactExtension != null && !contactExtension.isEmpty()) {
CodeableConceptDt values = (CodeableConceptDt) contactExtension.get(0).getValue();
appointmentDetail = addContactExtensionDetails(values, appointmentDetail);
}
if (categoryExtension != null && !categoryExtension.isEmpty()) {
CodeableConceptDt values = (CodeableConceptDt) categoryExtension.get(0).getValue();
appointmentDetail = addCategoryExtensionDetails(values, appointmentDetail);
}
appointmentDetail.setStatus(appointment.getStatus().toLowerCase(Locale.UK));
appointmentDetail.setTypeDisplay(appointment.getType().getCodingFirstRep().getDisplay());
appointmentDetail.setMinutesDuration(appointment.getMinutesDuration());
appointmentDetail.setPriority(appointment.getPriority());
appointmentDetail.setTypeText(appointment.getType().getText());
CodingDt codingFirstRep = appointment.getReason().getCodingFirstRep();
// we only support the SNOMED coding system
if (!codingFirstRep.isEmpty()) {
if (!SystemURL.SNOMED.equals(codingFirstRep.getSystem())) {
String message = String.format(
"Problem with reason property of the appointment. If the reason is provided then the system property must be %s",
SystemURL.SNOMED);
throw OperationOutcomeFactory.buildOperationOutcomeException(new UnprocessableEntityException(message),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.REQUIRED_ELEMENT_MISSING);
} else {
String reasonCode = codingFirstRep.getCode();
if (reasonCode == null) {
String message = "Problem with reason property of the appointment. If the reason is provided then the code property must be set.";
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException(message), SystemCode.INVALID_RESOURCE,
IssueTypeEnum.REQUIRED_ELEMENT_MISSING);
} else {
appointmentDetail.setReasonCode(reasonCode);
}
String reasonDisplay = codingFirstRep.getDisplay();
if (reasonDisplay == null) {
String message = "Problem with reason property of the appointment. If the reason is provided then the display property must be set.";
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException(message), SystemCode.INVALID_RESOURCE,
IssueTypeEnum.REQUIRED_ELEMENT_MISSING);
} else {
appointmentDetail.setReasonDisplay(reasonDisplay);
}
}
}
appointmentDetail.setStartDateTime(appointment.getStart());
appointmentDetail.setEndDateTime(appointment.getEnd());
List<Long> slotIds = new ArrayList<>();
for (ResourceReferenceDt slotReference : appointment.getSlot()) {
try {
slotIds.add(slotReference.getReference().getIdPartAsLong());
} catch (NumberFormatException ex) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException(String.format("The slot reference value data type for %s is not valid.",
slotReference.getReference().getIdPart())),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
}
appointmentDetail.setSlotIds(slotIds);
appointmentDetail.setComment(appointment.getComment());
appointmentDetail.setDescription(appointment.getDescription());
for (Appointment.Participant participant : appointment.getParticipant()) {
if (participant.getActor() != null) {
String participantReference = participant.getActor().getReference().getValue();
Long actorId = Long.valueOf(participantReference.substring(participantReference.lastIndexOf("/") + 1));
if (participantReference.contains("Patient/")) {
appointmentDetail.setPatientId(actorId);
} else if (participantReference.contains("Practitioner/")) {
appointmentDetail.setPractitionerId(actorId);
} else if (participantReference.contains("Location/")) {
appointmentDetail.setLocationId(actorId);
}
}
}
return appointmentDetail;
}
private AppointmentDetail addBookExtensionDetails(CodeableConceptDt values, AppointmentDetail appointmentDetail) {
String extensionDisplay = values.getCoding().get(0).getDisplay();
String extensionCode = values.getCoding().get(0).getCode();
appointmentDetail.setExtensionBookURL(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_BOOKING_METHOD);
appointmentDetail.setExtensionBookDisplay(extensionDisplay);
appointmentDetail.setExtensionBookCode(extensionCode);
return appointmentDetail;
}
private AppointmentDetail addCategoryExtensionDetails(CodeableConceptDt values,
AppointmentDetail appointmentDetail) {
String extensionDisplay = values.getCoding().get(0).getDisplay();
String extensionCode = values.getCoding().get(0).getCode();
appointmentDetail.setExtensionCatURL(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CATEGORY);
appointmentDetail.setExtensionCatDisplay(extensionDisplay);
appointmentDetail.setExtensionCatCode(extensionCode);
return appointmentDetail;
}
private AppointmentDetail addContactExtensionDetails(CodeableConceptDt values,
AppointmentDetail appointmentDetail) {
String extensionDisplay = values.getCoding().get(0).getDisplay();
String extensionCode = values.getCoding().get(0).getCode();
appointmentDetail.setExtensionConURL(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CONTACT_METHOD);
appointmentDetail.setExtensionConDisplay(extensionDisplay);
appointmentDetail.setExtensionConCode(extensionCode);
return appointmentDetail;
}
private void validateAppointmentExtensions(List<ExtensionDt> undeclaredExtensions) {
List<String> extensionURLs = undeclaredExtensions.stream().map(ExtensionDt::getUrlAsString)
.collect(Collectors.toList());
extensionURLs.remove(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_BOOKING_METHOD);
extensionURLs.remove(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CANCELLATION_REASON);
extensionURLs.remove(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CATEGORY);
extensionURLs.remove(SystemURL.SD_EXTENSION_GPC_APPOINTMENT_CONTACT_METHOD);
if (!extensionURLs.isEmpty()) {
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Invalid/multiple appointment extensions found. The following are in excess or invalid: "
+ extensionURLs.stream().collect(Collectors.joining(", "))),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
List<String> invalidCodes = new ArrayList<>();
for (ExtensionDt ue : undeclaredExtensions) {
CodeableConceptDt codeConc = (CodeableConceptDt) ue.getValue();
CodingDt code = codeConc.getCodingFirstRep();
Boolean isValid = valueSetValidator.validateCode(code);
if(isValid == false) {
invalidCodes.add(MessageFormat.format("Code: {0} [Display: {1}, System: {2}]", code.getCode(), code.getDisplay(), code.getSystem()));
}
}
if(!invalidCodes.isEmpty()){
throw OperationOutcomeFactory.buildOperationOutcomeException(
new UnprocessableEntityException("Invalid appointment extension codes: "
+ invalidCodes.stream().collect(Collectors.joining(", "))),
SystemCode.INVALID_RESOURCE, IssueTypeEnum.INVALID_CONTENT);
}
}
}
|
package uk.ac.ebi.gxa.index.builder.service;
import ucar.ma2.ArrayFloat;
import uk.ac.ebi.gxa.index.builder.IndexAllCommand;
import uk.ac.ebi.gxa.index.builder.IndexBuilderException;
import uk.ac.ebi.gxa.index.builder.UpdateIndexForExperimentCommand;
import uk.ac.ebi.gxa.netcdf.reader.AtlasNetCDFDAO;
import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy;
import uk.ac.ebi.gxa.properties.AtlasProperties;
import uk.ac.ebi.gxa.statistics.*;
import uk.ac.ebi.gxa.utils.EscapeUtil;
import uk.ac.ebi.microarray.atlas.model.OntologyMapping;
import java.io.*;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class GeneAtlasBitIndexBuilderService extends IndexBuilderService {
private static final String NCDF_EF_EFV_SEP = "\\|\\|";
private static final String EF_EFV_SEP = "_";
private AtlasProperties atlasProperties;
private AtlasNetCDFDAO atlasNetCDFDAO;
private String indexFileName;
private File atlasIndex;
File indexFile = null;
private StatisticsStorage statistics;
public void setAtlasNetCDFDAO(AtlasNetCDFDAO atlasNetCDFDAO) {
this.atlasNetCDFDAO = atlasNetCDFDAO;
}
public void setAtlasProperties(AtlasProperties atlasProperties) {
this.atlasProperties = atlasProperties;
}
public void setAtlasIndex(File atlasIndex) {
this.atlasIndex = atlasIndex;
}
/**
* Constructor
*
* @param indexFileName name of the serialized index file
*/
public GeneAtlasBitIndexBuilderService(String indexFileName) {
this.indexFileName = indexFileName;
}
@Override
public void processCommand(IndexAllCommand indexAll, IndexBuilderService.ProgressUpdater progressUpdater) throws IndexBuilderException {
indexFile = new File(atlasIndex + File.separator + getName());
if (indexFile.exists()) {
indexFile.delete();
}
statistics = bitIndexNetCDFs(progressUpdater, atlasProperties.getGeneAtlasIndexBuilderNumberOfThreads(), 500);
}
@Override
public void processCommand(UpdateIndexForExperimentCommand cmd, IndexBuilderService.ProgressUpdater progressUpdater) throws IndexBuilderException {
throw new IndexBuilderException("Unsupported Operation - genes bit index can be built only for all experiments");
}
@Override
public void finalizeCommand(IndexAllCommand indexAll, ProgressUpdater progressUpdater) throws IndexBuilderException {
try {
indexFile.createNewFile();
FileOutputStream fout = new FileOutputStream(indexFile);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(statistics);
oos.close();
getLog().info("Wrote serialized index successfully to: " + indexFile.getAbsolutePath());
} catch (IOException ioe) {
getLog().error("Error when saving serialized index: " + indexFile.getAbsolutePath(), ioe);
}
}
@Override
public void finalizeCommand(UpdateIndexForExperimentCommand updateIndexForExperimentCommand, ProgressUpdater progressUpdater) throws IndexBuilderException {
throw new IndexBuilderException("Unsupported Operation - genes bit index can be built only for all experiments");
}
/**
* Generates a ConciseSet-based index for all statistics types in StatisticsType enum, across all Atlas ncdfs
*
* @param progressUpdater
* @param fnoth how many threads to parallelise thsi tas over
* @param progressLogFreq how often this operation should be logged (i.e. every progressLogFreq ncfds processed)
* @return StatisticsStorage containing statistics for all statistics types in StatisticsType enum - collected over all Atlas ncdfs
*/
private StatisticsStorage bitIndexNetCDFs(
final ProgressUpdater progressUpdater,
final Integer fnoth,
final Integer progressLogFreq) {
StatisticsStorage statisticsStorage = new StatisticsStorage();
final ObjectIndex<Long> geneIndex = new ObjectIndex<Long>();
final ObjectIndex<Experiment> experimentIndex = new ObjectIndex<Experiment>();
final ObjectIndex<Attribute> attributeIndex = new ObjectIndex<Attribute>();
final Statistics upStats = new Statistics();
final Statistics dnStats = new Statistics();
final Statistics updnStats = new Statistics();
final Statistics noStats = new Statistics();
List<File> ncdfs = atlasNetCDFDAO.getAllNcdfs();
final AtomicInteger totalStatCount = new AtomicInteger();
final Integer total = ncdfs.size();
getLog().info("Found total ncdfs to index: " + total);
final AtomicInteger processedNcdfsCoCount = new AtomicInteger(0);
// Count of ncdfs in which no efvs were found
final AtomicInteger noEfvsNcdfCount = new AtomicInteger(0);
final long timeStart = System.currentTimeMillis();
List<Callable<Boolean>> tasks = new ArrayList<Callable<Boolean>>(total);
for (final File nc : ncdfs)
tasks.add(new Callable<Boolean>() {
public Boolean call() throws IOException {
try {
NetCDFProxy ncdf = new NetCDFProxy(nc);
Experiment experiment = new Experiment(ncdf.getExperiment(), ncdf.getExperimentId() + "");
Integer expIdx = experimentIndex.addObject(experiment);
String[] uefvs = ncdf.getUniqueFactorValues();
int car = 0; // count of all Statistics records added for this ncdf
if (uefvs.length == 0) {
ncdf.close();
processedNcdfsCoCount.incrementAndGet();
noEfvsNcdfCount.incrementAndGet();
return null;
}
long[] genes = ncdf.getGenes();
for (long gene : genes) if (gene != 0) geneIndex.addObject(gene);
ArrayFloat.D2 tstat = ncdf.getTStatistics();
ArrayFloat.D2 pvals = ncdf.getPValues();
int[] shape = tstat.getShape();
Set<Integer> efAttrIndexes = new HashSet<Integer>();
for (int j = 0; j < uefvs.length; j++) {
String[] efefv = uefvs[j].split(NCDF_EF_EFV_SEP);
Integer efvAttributeIndex = attributeIndex.addObject(new Attribute(EscapeUtil.encode(uefvs[j].replaceAll(NCDF_EF_EFV_SEP, EF_EFV_SEP))));
Integer efAttributeIndex = attributeIndex.addObject(new Attribute(EscapeUtil.encode(efefv[0])));
efAttrIndexes.add(efAttributeIndex);
SortedSet<Integer> upGeneIndexes = new TreeSet<Integer>();
SortedSet<Integer> dnGeneIndexes = new TreeSet<Integer>();
SortedSet<Integer> noGeneIndexes = new TreeSet<Integer>();
for (int i = 0; i < shape[0]; i++) {
if (genes[i] == 0) continue;
float t = tstat.get(i, j);
float p = pvals.get(i, j);
Integer idx = geneIndex.getIndexForObject(genes[i]);
if (null == idx) continue;
if (p > 0.05) {
noGeneIndexes.add(idx);
car++;
} else {
if (t > 0) {
upGeneIndexes.add(idx);
car++;
} else {
dnGeneIndexes.add(idx);
car++;
}
}
}
upStats.addStatistics(efvAttributeIndex, expIdx, upGeneIndexes);
dnStats.addStatistics(efvAttributeIndex, expIdx, dnGeneIndexes);
updnStats.addStatistics(efvAttributeIndex, expIdx, upGeneIndexes);
updnStats.addStatistics(efvAttributeIndex, expIdx, dnGeneIndexes);
noStats.addStatistics(efvAttributeIndex, expIdx, noGeneIndexes);
upStats.addStatistics(efAttributeIndex, expIdx, upGeneIndexes);
dnStats.addStatistics(efAttributeIndex, expIdx, dnGeneIndexes);
updnStats.addStatistics(efAttributeIndex, expIdx, upGeneIndexes);
updnStats.addStatistics(efAttributeIndex, expIdx, dnGeneIndexes);
noStats.addStatistics(efAttributeIndex, expIdx, noGeneIndexes);
}
// Add data count for aggregations of efvs also (ef, efo)
for (Integer efAttrIndex : efAttrIndexes) {
car += upStats.getNumStatistics(efAttrIndex, expIdx);
car += dnStats.getNumStatistics(efAttrIndex, expIdx);
car += updnStats.getNumStatistics(efAttrIndex, expIdx);
car += noStats.getNumStatistics(efAttrIndex, expIdx);
}
tstat = null;
pvals = null;
ncdf.close();
totalStatCount.addAndGet(car);
if (car == 0) {
getLog().debug(nc.getName() + " num uefvs : " + uefvs.length + " [" + car + "]");
}
int processedNow = processedNcdfsCoCount.incrementAndGet();
if (processedNow % progressLogFreq == 0 || processedNow == total) {
long timeNow = System.currentTimeMillis();
long elapsed = timeNow - timeStart;
double speed = (processedNow / (elapsed / Double.valueOf(progressLogFreq))); // (item/s)
double estimated = (total - processedNow) / (speed * 60);
getLog().info(
String.format("Processed %d/%d (# ncdfs with no EFVs so far: %d) ncdfs %d%%, %.1f ncdfs/sec overall, estimated %.1f min remaining",
processedNow, total, noEfvsNcdfCount.get(), (processedNow * 100 / total), speed, estimated));
if (processedNow == total) {
getLog().info("Overall processing time: " + (elapsed / 60000) + " min");
}
progressUpdater.update(processedNow + "/" + total);
}
return true;
} catch (Throwable t) {
getLog().error("Error occurred: ", t);
}
return false;
}
});
ExecutorService svc = Executors.newFixedThreadPool(fnoth);
try {
svc.invokeAll(tasks);
getLog().info("Total statistics data set " + (totalStatCount.get() * 8L) / 1024 + " kB");
// Set statistics
statisticsStorage.addStatistics(StatisticsType.UP, upStats);
statisticsStorage.addStatistics(StatisticsType.DOWN, dnStats);
statisticsStorage.addStatistics(StatisticsType.UP_DOWN, updnStats);
statisticsStorage.addStatistics(StatisticsType.NON_D_E, noStats);
// Set indexes for genes, experiments and indexes
statisticsStorage.setGeneIndex(geneIndex);
statisticsStorage.setExperimentIndex(experimentIndex);
statisticsStorage.setAttributeIndex(attributeIndex);
EfoIndex efoIndex = loadEfoMapping(attributeIndex, experimentIndex);
statisticsStorage.setEfoIndex(efoIndex);
} catch (InterruptedException e) {
getLog().error("Indexing interrupted!", e);
} finally {
// shutdown the service
getLog().info("Gene statistics index building tasks finished, cleaning up resources and exiting");
svc.shutdown();
}
return statisticsStorage;
}
public String getName() {
return indexFileName;
}
private EfoIndex loadEfoMapping(ObjectIndex<Attribute> attributeIndex, ObjectIndex<Experiment> experimentIndex) {
EfoIndex efoIndex = new EfoIndex();
getLog().info("Fetching ontology mappings...");
int missingExpsNum = 0, loadedEfos = 0, notLoadedEfos = 0;
List<OntologyMapping> mappings = getAtlasDAO().getOntologyMappingsByOntology("EFO");
for (OntologyMapping mapping : mappings) {
Experiment exp = new Experiment(mapping.getExperimentAccession(), String.valueOf(mapping.getExperimentId()));
Attribute attr = new Attribute(EscapeUtil.encode(mapping.getProperty(), mapping.getPropertyValue()));
Integer attributeIdx = attributeIndex.getIndexForObject(attr);
Integer experimentIdx = experimentIndex.getIndexForObject(exp);
if (attributeIdx == null) {
attributeIndex.addObject(attr);
getLog().debug("BitIndex build: efo term: " + mapping.getOntologyTerm() + " maps to a missing attribute: " + attr + " -> adding it to Attribute Index");
}
if (experimentIdx == null) {
missingExpsNum++;
getLog().error("BitIndex build: Failed to load efo term: " + mapping.getOntologyTerm() + " because experiment: " + exp + " could not be found in Experiment Index");
// TODO should RuntimeException be thrown here??
}
if (attributeIdx != null && experimentIdx != null) {
loadedEfos++;
efoIndex.addMapping(mapping.getOntologyTerm(), attributeIdx, experimentIdx);
getLog().debug("Adding: " + mapping.getOntologyTerm() + ":" + attr + " (" + attributeIdx + "):" + exp + " (" + experimentIdx + ")");
} else {
notLoadedEfos++;
}
}
getLog().info(String.format("Loaded %d ontology mappings (not loaded: %d due to missing %d experiments",
loadedEfos, notLoadedEfos, missingExpsNum));
return efoIndex;
}
}
|
package com.temenos.interaction.core.hypermedia;
import java.util.List;
import java.util.Map;
public class CollectionResourceState extends ResourceState {
public CollectionResourceState(String entityName, String name, List<Action> actions, String path) {
super(entityName, name, actions, path, "collection".split(" "));
}
public CollectionResourceState(String entityName, String name, List<Action> actions, String path, UriSpecification uriSpec) {
super(entityName, name, actions, path, "collection".split(" "), uriSpec);
}
public CollectionResourceState(String entityName, String name, List<Action> actions, String path, String[] rels, UriSpecification uriSpec) {
super(entityName, name, actions, path, rels != null ? rels : "collection".split(" "), uriSpec);
}
public void addTransitionForEachItem(String httpMethod, ResourceState targetState, Map<String, String> uriLinkageMap) {
addTransition(httpMethod, targetState, uriLinkageMap, null, targetState.getPath(), true);
}
public void addTransitionForEachItem(String httpMethod, ResourceState targetState, Map<String, String> uriLinkageMap, Map<String, String> uriLinkageProperties) {
addTransition(httpMethod, targetState, uriLinkageMap, uriLinkageProperties, targetState.getPath(), true);
}
public void addTransitionForEachItem(String httpMethod, ResourceState targetState, Map<String, String> uriLinkageMap, int transitionFlags) {
addTransition(httpMethod, targetState, uriLinkageMap, null, targetState.getPath(), transitionFlags | Transition.FOR_EACH, null);
}
public void addTransitionForEachItem(String httpMethod, ResourceState targetState, Map<String, String> uriLinkageMap, Map<String, String> uriLinkageProperties, int transitionFlags) {
addTransition(httpMethod, targetState, uriLinkageMap, uriLinkageProperties, targetState.getPath(), transitionFlags | Transition.FOR_EACH, null);
}
}
|
package org.to2mbn.jmccc.mcdownloader.provider;
public class MojangDownloadProvider extends DefaultLayoutProvider {
@Override
protected String getLibraryBaseURL() {
return "https://libraries.minecraft.net/";
}
@Override
protected String getVersionBaseURL() {
return "http://s3.amazonaws.com/Minecraft.Download/versions/";
}
@Override
protected String getAssetIndexBaseURL() {
return "http://s3.amazonaws.com/Minecraft.Download/indexes/";
}
@Override
protected String getVersionListURL() {
return "https://launchermeta.mojang.com/mc/game/version_manifest.json";
}
@Override
protected String getAssetBaseURL() {
return "http://resources.download.minecraft.net/";
}
}
|
package alien4cloud.topology;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.function.BiConsumer;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import javax.inject.Inject;
import org.alien4cloud.tosca.catalog.ArchiveDelegateType;
import org.alien4cloud.tosca.catalog.index.ICsarDependencyLoader;
import org.alien4cloud.tosca.catalog.index.IToscaTypeSearchService;
import org.alien4cloud.tosca.editor.EditionContext;
import org.alien4cloud.tosca.model.CSARDependency;
import org.alien4cloud.tosca.model.Csar;
import org.alien4cloud.tosca.model.templates.NodeTemplate;
import org.alien4cloud.tosca.model.templates.RelationshipTemplate;
import org.alien4cloud.tosca.model.templates.Topology;
import org.alien4cloud.tosca.model.types.AbstractToscaType;
import org.alien4cloud.tosca.model.types.NodeType;
import org.alien4cloud.tosca.model.types.RelationshipType;
import org.alien4cloud.tosca.topology.TopologyDTOBuilder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.elasticsearch.common.collect.Lists;
import org.elasticsearch.mapping.FilterValuesStrategy;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import alien4cloud.application.ApplicationService;
import alien4cloud.dao.IGenericSearchDAO;
import alien4cloud.dao.model.GetMultipleDataResult;
import alien4cloud.exception.AlreadyExistException;
import alien4cloud.exception.NotFoundException;
import alien4cloud.exception.VersionConflictException;
import alien4cloud.model.application.Application;
import alien4cloud.security.AuthorizationUtil;
import alien4cloud.security.model.ApplicationRole;
import alien4cloud.security.model.Role;
import alien4cloud.topology.exception.UpdateTopologyException;
import alien4cloud.topology.task.SuggestionsTask;
import alien4cloud.topology.task.TaskCode;
import alien4cloud.tosca.container.ToscaTypeLoader;
import alien4cloud.tosca.context.ToscaContext;
import alien4cloud.tosca.context.ToscaContextual;
import alien4cloud.utils.MapUtil;
import alien4cloud.utils.VersionUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class TopologyService {
@Resource
private IToscaTypeSearchService toscaTypeSearchService;
@Resource(name = "alien-es-dao")
private IGenericSearchDAO alienDAO;
@Resource
private ICsarDependencyLoader csarDependencyLoader;
@Resource
private TopologyServiceCore topologyServiceCore;
@Inject
private ApplicationService appService;
@Inject
private TopologyDTOBuilder topologyDTOBuilder;
public static final Pattern NODE_NAME_PATTERN = Pattern.compile("^\\w+$");
public static final Pattern NODE_NAME_REPLACE_PATTERN = Pattern.compile("\\W");
private ToscaTypeLoader initializeTypeLoader(Topology topology, boolean failOnTypeNotFound) {
// FIXME we should use ToscaContext here, and why not allowing the caller to pass ona Context?
ToscaTypeLoader loader = new ToscaTypeLoader(csarDependencyLoader);
Map<String, NodeType> nodeTypes = topologyServiceCore.getIndexedNodeTypesFromTopology(topology, false, false, failOnTypeNotFound);
Map<String, RelationshipType> relationshipTypes = topologyServiceCore.getIndexedRelationshipTypesFromTopology(topology, failOnTypeNotFound);
if (topology.getNodeTemplates() != null) {
for (NodeTemplate nodeTemplate : topology.getNodeTemplates().values()) {
NodeType nodeType = nodeTypes.get(nodeTemplate.getType());
// just load found types.
// the type might be null when failOnTypeNotFound is set to false.
if (nodeType != null) {
loader.loadType(nodeTemplate.getType(), csarDependencyLoader.buildDependencyBean(nodeType.getArchiveName(), nodeType.getArchiveVersion()));
}
if (nodeTemplate.getRelationships() != null) {
for (RelationshipTemplate relationshipTemplate : nodeTemplate.getRelationships().values()) {
RelationshipType relationshipType = relationshipTypes.get(relationshipTemplate.getType());
// just load found types.
// the type might be null when failOnTypeNotFound is set to false.
if (relationshipType != null) {
loader.loadType(relationshipTemplate.getType(),
csarDependencyLoader.buildDependencyBean(relationshipType.getArchiveName(), relationshipType.getArchiveVersion()));
}
}
}
}
}
if (topology.getSubstitutionMapping() != null && topology.getSubstitutionMapping().getSubstitutionType() != null) {
NodeType substitutionType = topology.getSubstitutionMapping().getSubstitutionType();
loader.loadType(substitutionType.getElementId(),
csarDependencyLoader.buildDependencyBean(substitutionType.getArchiveName(), substitutionType.getArchiveVersion()));
}
return loader;
}
/**
* Find replacements nodes for a node template
*
* @param nodeTemplateName the node to search for replacements
* @param topology the topology
* @return all possible replacement types for this node
*/
@SneakyThrows(IOException.class)
public NodeType[] findReplacementForNode(String nodeTemplateName, Topology topology) {
NodeTemplate nodeTemplate = topology.getNodeTemplates().get(nodeTemplateName);
Map<String, Map<String, Set<String>>> nodeTemplatesToFilters = Maps.newHashMap();
Entry<String, NodeTemplate> nodeTempEntry = Maps.immutableEntry(nodeTemplateName, nodeTemplate);
NodeType indexedNodeType = toscaTypeSearchService.getRequiredElementInDependencies(NodeType.class, nodeTemplate.getType(), topology.getDependencies());
processNodeTemplate(topology, nodeTempEntry, nodeTemplatesToFilters);
List<SuggestionsTask> topoTasks = searchForNodeTypes(topology.getWorkspace(), nodeTemplatesToFilters,
MapUtil.newHashMap(new String[] { nodeTemplateName }, new NodeType[] { indexedNodeType }));
if (CollectionUtils.isEmpty(topoTasks)) {
return null;
}
return topoTasks.get(0).getSuggestedNodeTypes();
}
private void addFilters(String nodeTempName, String filterKey, String filterValueToAdd, Map<String, Map<String, Set<String>>> nodeTemplatesToFilters) {
Map<String, Set<String>> filters = nodeTemplatesToFilters.get(nodeTempName);
if (filters == null) {
filters = Maps.newHashMap();
}
Set<String> filterValues = filters.get(filterKey);
if (filterValues == null) {
filterValues = Sets.newHashSet();
}
filterValues.add(filterValueToAdd);
filters.put(filterKey, filterValues);
nodeTemplatesToFilters.put(nodeTempName, filters);
}
/**
* Process a node template to retrieve filters for node replacements search.
*
* TODO cleanup this method, better return a filter for node rather than adding it to a parameter list.
*
* @param topology The topology for which to search filters.
* @param nodeTempEntry The node template for which to find replacement filter.
* @param nodeTemplatesToFilters The map of filters in which to add the filter for the new Node.
*/
public void processNodeTemplate(final Topology topology, final Entry<String, NodeTemplate> nodeTempEntry,
Map<String, Map<String, Set<String>>> nodeTemplatesToFilters) {
String capabilityFilterKey = "capabilities.type";
String requirementFilterKey = "requirements.type";
NodeTemplate template = nodeTempEntry.getValue();
Map<String, RelationshipTemplate> relTemplates = template.getRelationships();
nodeTemplatesToFilters.put(nodeTempEntry.getKey(), null);
// process the node template source of relationships
if (relTemplates != null && !relTemplates.isEmpty()) {
for (RelationshipTemplate relationshipTemplate : relTemplates.values()) {
addFilters(nodeTempEntry.getKey(), requirementFilterKey, relationshipTemplate.getRequirementType(), nodeTemplatesToFilters);
}
}
// process the node template target of relationships
List<RelationshipTemplate> relTemplatesTargetRelated = topologyServiceCore.getTargetRelatedRelatonshipsTemplate(nodeTempEntry.getKey(),
topology.getNodeTemplates());
for (RelationshipTemplate relationshipTemplate : relTemplatesTargetRelated) {
addFilters(nodeTempEntry.getKey(), capabilityFilterKey, relationshipTemplate.getRequirementType(), nodeTemplatesToFilters);
}
}
private NodeType[] getIndexedNodeTypesFromSearchResponse(final GetMultipleDataResult<NodeType> searchResult, final NodeType toExcludeIndexedNodeType)
throws IOException {
NodeType[] toReturnArray = null;
for (int j = 0; j < searchResult.getData().length; j++) {
NodeType nodeType = searchResult.getData()[j];
if (toExcludeIndexedNodeType == null || !nodeType.getId().equals(toExcludeIndexedNodeType.getId())) {
toReturnArray = ArrayUtils.add(toReturnArray, nodeType);
}
}
return toReturnArray;
}
/**
* Search for nodeTypes given some filters. Apply AND filter strategy when multiple values for a filter key.
*/
public List<SuggestionsTask> searchForNodeTypes(String workspace, Map<String, Map<String, Set<String>>> nodeTemplatesToFilters,
Map<String, NodeType> toExcludeIndexedNodeTypes) throws IOException {
if (nodeTemplatesToFilters == null || nodeTemplatesToFilters.isEmpty()) {
return null;
}
List<SuggestionsTask> toReturnTasks = Lists.newArrayList();
for (Map.Entry<String, Map<String, Set<String>>> nodeTemplatesToFiltersEntry : nodeTemplatesToFilters.entrySet()) {
Map<String, String[]> formattedFilters = Maps.newHashMap();
Map<String, FilterValuesStrategy> filterValueStrategy = Maps.newHashMap();
NodeType[] data = null;
if (nodeTemplatesToFiltersEntry.getValue() != null) {
for (Map.Entry<String, Set<String>> filterEntry : nodeTemplatesToFiltersEntry.getValue().entrySet()) {
formattedFilters.put(filterEntry.getKey(), filterEntry.getValue().toArray(new String[filterEntry.getValue().size()]));
// AND strategy if multiple values
filterValueStrategy.put(filterEntry.getKey(), FilterValuesStrategy.AND);
}
// retrieve only non abstract components
formattedFilters.put("abstract", ArrayUtils.toArray("false"));
// use topology workspace + global workspace
formattedFilters.put("workspace", ArrayUtils.toArray(workspace, "ALIEN_GLOBAL_WORKSPACE"));
GetMultipleDataResult<NodeType> searchResult = alienDAO.search(NodeType.class, null, formattedFilters, filterValueStrategy, 20);
data = getIndexedNodeTypesFromSearchResponse(searchResult, toExcludeIndexedNodeTypes.get(nodeTemplatesToFiltersEntry.getKey()));
}
TaskCode taskCode = data == null || data.length < 1 ? TaskCode.IMPLEMENT : TaskCode.REPLACE;
SuggestionsTask task = new SuggestionsTask();
task.setNodeTemplateName(nodeTemplatesToFiltersEntry.getKey());
task.setComponent(toExcludeIndexedNodeTypes.get(nodeTemplatesToFiltersEntry.getKey()));
task.setCode(taskCode);
task.setSuggestedNodeTypes(data);
toReturnTasks.add(task);
}
return toReturnTasks;
}
/**
* Check that the user has enough rights for a given topology.
*
* @param topology The topology for which to check roles.
* @param applicationRoles The roles required to edit the topology for an application.
*/
private void checkAuthorizations(Topology topology, ApplicationRole[] applicationRoles, Role[] roles) {
Csar relatedCsar = ToscaContext.get().getArchive(topology.getArchiveName(), topology.getArchiveVersion());
if (Objects.equals(relatedCsar.getDelegateType(), ArchiveDelegateType.APPLICATION.toString())) {
String applicationId = relatedCsar.getDelegateId();
Application application = appService.getOrFail(applicationId);
AuthorizationUtil.checkAuthorizationForApplication(application, applicationRoles);
} else {
AuthorizationUtil.checkHasOneRoleIn(roles);
}
}
/**
* Check that the current user can retrieve the given topology.
*
* @param topology The topology that is subject to being updated.
*/
@ToscaContextual
public void checkAccessAuthorizations(Topology topology) {
checkAuthorizations(topology,
new ApplicationRole[] { ApplicationRole.APPLICATION_MANAGER, ApplicationRole.APPLICATION_DEVOPS, ApplicationRole.APPLICATION_USER },
new Role[] { Role.COMPONENTS_BROWSER, Role.ARCHITECT });
}
/**
* Check that the current user can update the given topology.
*
* @param topology The topology that is subject to being updated.
*/
@ToscaContextual
public void checkEditionAuthorizations(Topology topology) {
checkAuthorizations(topology, new ApplicationRole[] { ApplicationRole.APPLICATION_MANAGER, ApplicationRole.APPLICATION_DEVOPS },
new Role[] { Role.ARCHITECT });
}
/**
* Build a node template
*
* @param dependencies the dependencies on which new node will be constructed
* @param indexedNodeType the type of the node
* @param templateToMerge the template that can be used to merge into the new node template
* @return new constructed node template
*/
public NodeTemplate buildNodeTemplate(Set<CSARDependency> dependencies, NodeType indexedNodeType, NodeTemplate templateToMerge) {
return topologyServiceCore.buildNodeTemplate(dependencies, indexedNodeType, templateToMerge);
}
/**
* Load a type into the topology (add dependency for this new type, upgrade if necessary ...)
*
* @param topology the topology
* @param element the element to load
* @param <T> tosca element type
* @return The real loaded element if element given in argument is from older archive than topology's dependencies
*/
@SuppressWarnings("unchecked")
public <T extends AbstractToscaType> T loadType(Topology topology, T element) {
String type = element.getElementId();
String archiveName = element.getArchiveName();
String archiveVersion = element.getArchiveVersion();
CSARDependency toLoadDependency = csarDependencyLoader.buildDependencyBean(archiveName, archiveVersion);
// FIXME Transitive dependencies could change here and thus types be affected ?
ToscaTypeLoader typeLoader = initializeTypeLoader(topology, true);
typeLoader.loadType(type, toLoadDependency);
ToscaContext.get().resetDependencies(typeLoader.getLoadedDependencies());
// TODO update csar dependencies also ?
topology.setDependencies(typeLoader.getLoadedDependencies());
return element;
}
public void unloadType(Topology topology, String... types) {
// make sure to set the failOnTypeNotFound to false, to deal with topology recovering when a type is deleted from a dependency
ToscaTypeLoader typeLoader = initializeTypeLoader(topology, false);
for (String type : types) {
typeLoader.unloadType(type);
}
ToscaContext.get().resetDependencies(typeLoader.getLoadedDependencies());
// TODO update csar dependencies also ?
topology.setDependencies(typeLoader.getLoadedDependencies());
}
/**
* Throw an UpdateTopologyException if the topology is released
*
* @param topology topology to be checked
*/
public void throwsErrorIfReleased(Topology topology) {
if (isReleased(topology)) {
throw new UpdateTopologyException("The topology " + topology.getId() + " cannot be updated because it's released");
}
}
/**
* True when an topology is released.
*/
public boolean isReleased(Topology topology) {
return !VersionUtil.isSnapshot(topology.getArchiveVersion());
}
public void isUniqueNodeTemplateName(Topology topology, String newNodeTemplateName) {
if (topology.getNodeTemplates() != null && topology.getNodeTemplates().containsKey(newNodeTemplateName)) {
log.debug("Add Node Template <{}> impossible (already exists)", newNodeTemplateName);
// a node template already exist with the given name.
throw new AlreadyExistException(
"A node template with the given name " + newNodeTemplateName + " already exists in the topology " + topology.getId() + ".");
}
}
public void updateDependencies(EditionContext context, CSARDependency newDependency) {
final Set<CSARDependency> oldDependencies = new HashSet<>(context.getTopology().getDependencies());
final Set<CSARDependency> newDependencies = csarDependencyLoader.getDependencies(newDependency.getName(), newDependency.getVersion());
newDependencies.add(newDependency);
// Update context with the new dependencies.
newDependencies.forEach(csarDependency -> context.getToscaContext().updateDependency(csarDependency));
// Validate that the dependency change does not induce missing types.
try {
this.checkForMissingTypes(context);
} catch (NotFoundException e) {
// Revert changes made to the Context then throw.
context.getToscaContext().resetDependencies(oldDependencies);
context.getTopology().setDependencies(oldDependencies);
throw new VersionConflictException("Changing the dependency ["+ newDependency.getName() + "] to version ["
+ newDependency.getVersion() + "] induces missing types in the topology. Not found : [" + e.getMessage() + "].", e);
}
// Perform the dependency update on the topology.
context.getTopology().setDependencies(new HashSet<>(context.getToscaContext().getDependencies()));
}
/**
* Check for missing types in the Topology
* @param context
* @throws NotFoundException if the Type is used in the topology and not found in its context.
*/
private void checkForMissingTypes(EditionContext context) {
/* TODO: Cache the result or do not use TopologyDTOBuilder
* because it is then called again at the end of the operation execution (EditorController.execute)
*/
TopologyDTO topologyDTO = topologyDTOBuilder.buildTopologyDTO(context);
topologyDTO.getNodeTypes().forEach(throwTypeNotFound());
topologyDTO.getRelationshipTypes().forEach(throwTypeNotFound());
topologyDTO.getCapabilityTypes().forEach(throwTypeNotFound());
topologyDTO.getDataTypes().forEach(throwTypeNotFound());
}
private BiConsumer<String, AbstractToscaType> throwTypeNotFound() {
return (s, type) -> {
if (type == null) {
throw new NotFoundException(s);
}
};
}
public void rebuildDependencies(Topology topology) {
ToscaTypeLoader typeLoader = initializeTypeLoader(topology, true);
topology.setDependencies(typeLoader.getLoadedDependencies());
}
}
|
package com.github.ambry.network;
import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.MetricRegistry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
/**
* Metrics for the network layer
*/
public class NetworkMetrics {
private final MetricRegistry registry;
// SocketRequestResponseChannel metrics
private final List<Gauge<Integer>> responseQueueSize;
private final Gauge<Integer> requestQueueSize;
// SocketServer metrics
public final Counter sendInFlight;
public final Counter acceptConnectionErrorCount;
public final Counter acceptorShutDownErrorCount;
public final Counter processorShutDownErrorCount;
public final Counter processNewResponseErrorCount;
public Gauge<Integer> numberOfProcessorThreads;
// Selector metrics
public final Counter selectorConnectionClosed;
public final Counter selectorConnectionCreated;
public final Counter selectorSelectRate;
public final Histogram selectorSelectTime;
public final Counter selectorIORate;
public final Histogram selectorIOTime;
public final Counter selectorNioCloseErrorCount;
public final Counter selectorDisconnectedErrorCount;
public final Counter selectorIOErrorCount;
public final Counter selectorKeyOperationErrorCount;
public final Counter selectorCloseKeyErrorCount;
public final Counter selectorCloseSocketErrorCount;
public Gauge<Long> selectorActiveConnections;
public final Map<String, SelectorNodeMetric> selectorNodeMetricMap;
// Plaintext metrics
public final Histogram plaintextReceiveBytesRate; // the bytes rate to receive the entire request
public final Histogram plaintextSendBytesRate; // the bytes rate to send the entire response
public final Histogram plaintextReceiveTimePerKB; // the time to receive 1KB data in one read call
public final Histogram plaintextSendTime; // the time to send data in one write call
// SSL metrics
public final Counter sslFactoryInitializationCount;
public final Counter sslTransmissionInitializationCount;
public final Counter sslFactoryInitializationErrorCount;
public final Counter sslTransmissionInitializationErrorCount;
public final Histogram sslHandshakeTime;
public final Counter sslHandshakeCount;
public final Counter sslHandshakeErrorCount;
public final Histogram sslReceiveBytesRate; // the bytes rate to receive the entire request
public final Histogram sslSendBytesRate; // the bytes rate to send the entire response
public final Histogram sslReceiveTimePerKB; // the time to receive 1KB data in one read call
public final Histogram sslSendTime; // the time to send data in one write call
public final Histogram sslEncryptionTimePerKB;
public final Histogram sslDecryptionTimePerKB;
public final Counter sslRenegotiationCount;
public NetworkMetrics(final SocketRequestResponseChannel channel, MetricRegistry registry,
final List<Processor> processorThreads) {
this.registry = registry;
requestQueueSize = new Gauge<Integer>() {
@Override
public Integer getValue() {
return channel.getRequestQueueSize();
}
};
registry.register(MetricRegistry.name(SocketRequestResponseChannel.class, "RequestQueueSize"), requestQueueSize);
responseQueueSize = new ArrayList<Gauge<Integer>>(channel.getNumberOfProcessors());
for (int i = 0; i < channel.getNumberOfProcessors(); i++) {
final int index = i;
responseQueueSize.add(i, new Gauge<Integer>() {
@Override
public Integer getValue() {
return channel.getResponseQueueSize(index);
}
});
registry.register(MetricRegistry.name(SocketRequestResponseChannel.class, i + "-ResponseQueueSize"),
responseQueueSize.get(i));
}
sendInFlight = registry.counter(MetricRegistry.name(SocketServer.class, "SendInFlight"));
selectorConnectionClosed = registry.counter(MetricRegistry.name(Selector.class, "SelectorConnectionClosed"));
selectorConnectionCreated = registry.counter(MetricRegistry.name(Selector.class, "SelectorConnectionCreated"));
selectorSelectRate = registry.counter(MetricRegistry.name(Selector.class, "SelectorSelectRate"));
selectorIORate = registry.counter(MetricRegistry.name(Selector.class, "SelectorIORate"));
selectorSelectTime = registry.histogram(MetricRegistry.name(Selector.class, "SelectorSelectTime"));
selectorIOTime = registry.histogram(MetricRegistry.name(Selector.class, "SelectorIOTime"));
selectorNioCloseErrorCount = registry.counter(MetricRegistry.name(Selector.class, "SelectorNioCloseErrorCount"));
selectorDisconnectedErrorCount =
registry.counter(MetricRegistry.name(Selector.class, "SelectorDisconnectedErrorCount"));
selectorIOErrorCount = registry.counter(MetricRegistry.name(Selector.class, "SelectorIoErrorCount"));
selectorKeyOperationErrorCount =
registry.counter(MetricRegistry.name(Selector.class, "SelectorKeyOperationErrorCount"));
selectorCloseKeyErrorCount = registry.counter(MetricRegistry.name(Selector.class, "SelectorCloseKeyErrorCount"));
selectorCloseSocketErrorCount =
registry.counter(MetricRegistry.name(Selector.class, "SelectorCloseSocketErrorCount"));
plaintextReceiveBytesRate = registry.histogram(MetricRegistry.name(Selector.class, "PlaintextReceiveBytesRate"));
plaintextSendBytesRate = registry.histogram(MetricRegistry.name(Selector.class, "PlaintextSendBytesRate"));
plaintextReceiveTimePerKB = registry.histogram(MetricRegistry.name(Selector.class, "PlaintextReceiveTimePerKB"));
plaintextSendTime = registry.histogram(MetricRegistry.name(Selector.class, "PlaintextSendTime"));
sslReceiveBytesRate = registry.histogram(MetricRegistry.name(Selector.class, "SslReceiveBytesRate"));
sslSendBytesRate = registry.histogram(MetricRegistry.name(Selector.class, "SslSendBytesRate"));
sslEncryptionTimePerKB = registry.histogram(MetricRegistry.name(Selector.class, "SslEncryptionTimePerKB"));
sslDecryptionTimePerKB = registry.histogram(MetricRegistry.name(Selector.class, "SslDecryptionTimePerKB"));
sslReceiveTimePerKB = registry.histogram(MetricRegistry.name(Selector.class, "SslReceiveTimePerKB"));
sslSendTime = registry.histogram(MetricRegistry.name(Selector.class, "SslSendTime"));
sslFactoryInitializationCount =
registry.counter(MetricRegistry.name(Selector.class, "SslFactoryInitializationCount"));
sslFactoryInitializationErrorCount =
registry.counter(MetricRegistry.name(Selector.class, "SslFactoryInitializationErrorCount"));
sslTransmissionInitializationCount =
registry.counter(MetricRegistry.name(Selector.class, "SslTransmissionInitializationCount"));
sslTransmissionInitializationErrorCount =
registry.counter(MetricRegistry.name(Selector.class, "SslTransmissionInitializationErrorCount"));
sslHandshakeTime = registry.histogram(MetricRegistry.name(Selector.class, "SslHandshakeTime"));
sslHandshakeCount = registry.counter(MetricRegistry.name(Selector.class, "SslHandshakeCount"));
sslHandshakeErrorCount = registry.counter(MetricRegistry.name(Selector.class, "SslHandshakeErrorCount"));
sslRenegotiationCount = registry.counter(MetricRegistry.name(Selector.class, "SslRenegotiationCount"));
numberOfProcessorThreads = new Gauge<Integer>() {
@Override
public Integer getValue() {
return getLiveThreads(processorThreads);
}
};
registry.register(MetricRegistry.name(SocketServer.class, "NumberOfProcessorThreads"), numberOfProcessorThreads);
acceptConnectionErrorCount =
registry.counter(MetricRegistry.name(SocketServer.class, "AcceptConnectionErrorCount"));
acceptorShutDownErrorCount =
registry.counter(MetricRegistry.name(SocketServer.class, "AcceptorShutDownErrorCount"));
processorShutDownErrorCount =
registry.counter(MetricRegistry.name(SocketServer.class, "ProcessorShutDownErrorCount"));
processNewResponseErrorCount =
registry.counter(MetricRegistry.name(SocketServer.class, "ProcessNewResponseErrorCount"));
selectorNodeMetricMap = new HashMap<String, SelectorNodeMetric>();
}
private int getLiveThreads(List<Processor> replicaThreads) {
int count = 0;
for (Processor thread : replicaThreads) {
if (thread.isRunning()) {
count++;
}
}
return count;
}
public void initializeSelectorMetricsIfRequired(final AtomicLong activeConnections) {
selectorActiveConnections = new Gauge<Long>() {
@Override
public Long getValue() {
return activeConnections.get();
}
};
}
public void initializeSelectorNodeMetricIfRequired(String hostname, int port) {
if (!selectorNodeMetricMap.containsKey(hostname + port)) {
SelectorNodeMetric nodeMetric = new SelectorNodeMetric(registry, hostname, port);
selectorNodeMetricMap.put(hostname + port, nodeMetric);
}
}
public void updateNodeSendMetric(String hostName, int port, long bytesSentCount, long timeTakenToSendInMs) {
if (!selectorNodeMetricMap.containsKey(hostName + port)) {
throw new IllegalArgumentException("Node " + hostName + " with port " + port + " does not exist in metric map");
}
SelectorNodeMetric nodeMetric = selectorNodeMetricMap.get(hostName + port);
nodeMetric.sendCount.inc();
nodeMetric.bytesSentCount.inc(bytesSentCount);
nodeMetric.bytesSentLatency.update(timeTakenToSendInMs);
}
public void updateNodeReceiveMetric(String hostName, int port, long bytesReceivedCount, long timeTakenToReceiveInMs) {
if (!selectorNodeMetricMap.containsKey(hostName + port)) {
throw new IllegalArgumentException("Node " + hostName + " with port " + port + " does not exist in metric map");
}
SelectorNodeMetric nodeMetric = selectorNodeMetricMap.get(hostName + port);
nodeMetric.bytesReceivedCount.inc(bytesReceivedCount);
nodeMetric.bytesReceivedLatency.update(timeTakenToReceiveInMs);
}
class SelectorNodeMetric {
public final Counter sendCount;
public final Histogram bytesSentLatency;
public final Histogram bytesReceivedLatency;
public final Counter bytesSentCount;
public final Counter bytesReceivedCount;
public SelectorNodeMetric(MetricRegistry registry, String hostname, int port) {
sendCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-SendCount"));
bytesSentLatency =
registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesSentLatencyInMs"));
bytesReceivedLatency =
registry.histogram(MetricRegistry.name(Selector.class, hostname + "-" + port + "- BytesReceivedLatencyInMs"));
bytesSentCount = registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesSentCount"));
bytesReceivedCount =
registry.counter(MetricRegistry.name(Selector.class, hostname + "-" + port + "-BytesReceivedCount"));
}
}
}
|
package ti.modules.titanium.android;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.kroll.KrollProxy;
import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.util.Log;
import org.appcelerator.titanium.util.TiConfig;
import org.appcelerator.titanium.util.TiConvert;
import android.content.Intent;
import android.net.Uri;
@Kroll.proxy(creatableInModule=AndroidModule.class)
public class IntentProxy extends KrollProxy
{
private static final String LCAT = "TiIntent";
private static boolean DBG = TiConfig.LOGD;
protected Intent intent;
public IntentProxy(TiContext tiContext)
{
super(tiContext);
}
public void handleCreationDict(KrollDict dict) {
intent = new Intent();
// See which set of options we have to work with.
String action = dict.getString("action");
String data = dict.getString("data");
String classname = dict.getString("className");
String packageName = dict.getString("packageName");
String type = dict.getString("type");
if (action != null) {
if (DBG) {
Log.d(LCAT, "Setting action: " + action);
}
intent.setAction(action);
}
if (data != null) {
if (DBG) {
Log.d(LCAT, "Setting data uri: " + data);
}
intent.setData(Uri.parse(data));
}
if (packageName != null) {
if (DBG) {
Log.d(LCAT, "Setting package: " + packageName);
}
intent.setPackage(packageName);
}
if (classname != null) {
if (packageName != null) {
if (DBG) {
Log.d(LCAT, "Both className and packageName set, using intent.setClassName(packageName, className");
}
intent.setClassName(packageName, classname);
} else {
try {
Class<?> c = getClass().getClassLoader().loadClass(classname);
intent.setClass(getTiContext().getActivity().getApplicationContext(), c);
} catch (ClassNotFoundException e) {
Log.e(LCAT, "Unable to locate class for name: " + classname);
throw new IllegalStateException("Missing class for name: " + classname, e);
}
}
}
if (type != null) {
if (DBG) {
Log.d(LCAT, "Setting type: " + type);
intent.setType(type);
}
} else {
if (action != null && action.equals(Intent.ACTION_SEND)) {
if (DBG) {
Log.d(LCAT, "Intent type not set, defaulting to text/plain because action is a SEND action");
}
intent.setType("text/plain");
}
}
}
@Kroll.method
public void putExtra(String key, Object value)
{
if (value instanceof String) {
intent.putExtra(key, (String) value);
} else if (value instanceof Boolean) {
intent.putExtra(key, (Boolean) value);
} else if (value instanceof Double) {
intent.putExtra(key, (Double) value);
} else if (value instanceof Integer) {
intent.putExtra(key, (Integer) value);
} else {
Log.w(LCAT, "Warning unimplemented put conversion for " + value.getClass().getCanonicalName() + " trying String");
intent.putExtra(key, TiConvert.toString(value));
}
}
protected Intent getIntent() {
return intent;
}
}
|
package org.appcelerator.titanium.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.codec.digest.DigestUtils;
import org.appcelerator.titanium.TiApplication;
public class TiResponseCache extends ResponseCache {
private static final String HEADER_SUFFIX = ".hdr";
private static final String BODY_SUFFIX = ".bdy";
private static final String CACHE_SIZE_KEY = "ti.android.cache.size.max";
private static final int MAX_CACHE_SIZE = 25 * 1024 * 1024; // 25MB
private static class TiCacheCleanup implements Runnable {
private File cacheDir;
private long maxSize;
private long contentLength;
private File hdrFile;
public TiCacheCleanup(File cacheDir, long maxSize, File hdrFile, long contentLength) {
this.cacheDir = cacheDir;
this.maxSize = maxSize;
this.contentLength = contentLength;
this.hdrFile = hdrFile;
}
@Override
public void run() {
// Build up a list of access times
HashMap<Long, File> lastTime = new HashMap<Long, File>();
for (File hdrFile : cacheDir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(HEADER_SUFFIX);
}
})) {
if (hdrFile.equals(this.hdrFile)) continue;
lastTime.put(hdrFile.lastModified(), hdrFile);
}
// Ensure that the cache is under the required size
List<Long> sz = new ArrayList<Long>(lastTime.keySet());
Collections.sort(sz);
Collections.reverse(sz);
long cacheSize = contentLength;
for (Long last : sz) {
File hdrFile = lastTime.get(last);
String h = hdrFile.getName().substring(0, hdrFile.getName().lastIndexOf('.')); // Hash
File bdyFile = new File(cacheDir, h + BODY_SUFFIX);
cacheSize += hdrFile.length();
cacheSize += bdyFile.length();
if (cacheSize > this.maxSize) {
hdrFile.delete();
bdyFile.delete();
}
}
}
}
private static class TiCacheBodyOutputStream extends FileOutputStream {
private File hFile;
private File bFile;
private String headers;
public TiCacheBodyOutputStream(File bFile, File hFile, String headers) throws IOException {
super(bFile);
this.bFile = bFile;
this.hFile = hFile;
this.headers = headers;
}
@Override
public void close() throws IOException {
super.close();
if (!hFile.createNewFile()) {
this.abort();
return;
}
// Write out the headers
FileWriter wrtr = new FileWriter(hFile);
wrtr.write(headers);
wrtr.close();
}
public void abort() throws IOException {
try {
super.close();
} finally {
bFile.delete();
}
}
}
private static class TiCacheResponse extends CacheResponse {
private Map<String, List<String>> headers;
private InputStream istream;
public TiCacheResponse(Map<String, List<String>> hdrs, InputStream istr) {
super();
headers = hdrs;
istream = istr;
}
@Override
public Map<String, List<String>> getHeaders() throws IOException {
return headers;
}
@Override
public InputStream getBody() throws IOException {
return istream;
}
}
private static class TiCacheRequest extends CacheRequest {
private TiCacheBodyOutputStream ostream;
public TiCacheRequest(TiCacheBodyOutputStream ostream) {
super();
this.ostream = ostream;
}
@Override
public OutputStream getBody() throws IOException {
return ostream;
}
@Override
public void abort() {
try {
ostream.abort();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File cacheDir = null;
public TiResponseCache(File cachedir) {
super();
assert cachedir.isDirectory() : "cachedir MUST be a directory";
cacheDir = cachedir;
}
@Override
public CacheResponse get(URI uri, String rqstMethod,
Map<String, List<String>> rqstHeaders) throws IOException {
if (cacheDir == null) return null;
// Get our key, which is a hash of the URI
String hash = DigestUtils.shaHex(uri.toString());
// Make our cache files
File hFile = new File(cacheDir, hash + HEADER_SUFFIX);
File bFile = new File(cacheDir, hash + BODY_SUFFIX);
// Read in the headers
Map<String, List<String>> headers = new HashMap<String, List<String>>();
BufferedReader rdr = new BufferedReader(new FileReader(hFile));
for (String line=rdr.readLine() ; line != null ; line=rdr.readLine()) {
String keyval[] = line.split("=", 2);
if (!headers.containsKey(keyval[0]))
headers.put(keyval[0], new ArrayList<String>());
headers.get(keyval[0]).add(keyval[1]);
}
rdr.close();
// Update the access log
hFile.setLastModified(System.currentTimeMillis());
// Respond with the cache
return new TiCacheResponse(headers, new FileInputStream(bFile));
}
@Override
public CacheRequest put(URI uri, URLConnection conn) throws IOException {
if (cacheDir == null) return null;
String cacheControl = conn.getHeaderField("Cache-Control");
if (cacheControl != null && cacheControl.matches("(?i:(no-cache|no-store|must-revalidate))"))
return null; // See RFC-2616
// Form the headers and generate the content length
String newl = System.getProperty("line.separator");
long contentLength = conn.getHeaderFieldInt("Content-Length", 0);
StringBuilder sb = new StringBuilder();
for (String hdr : conn.getHeaderFields().keySet())
for (String val : conn.getHeaderFields().get(hdr)) {
sb.append(hdr);
sb.append("=");
sb.append(val);
sb.append(newl);
}
contentLength += sb.length();
if (contentLength > MAX_CACHE_SIZE)
return null;
// Work around an android bug which gives us the wrong URI
try {
uri = conn.getURL().toURI();
} catch (URISyntaxException e) {
e.printStackTrace();
}
// Get our key, which is a hash of the URI
String hash = DigestUtils.shaHex(uri.toString());
// Make our cache files
File hFile = new File(cacheDir, hash + HEADER_SUFFIX);
File bFile = new File(cacheDir, hash + BODY_SUFFIX);
// Cleanup asynchronously
int cacheSize = TiApplication.getInstance().getSystemProperties().getInt(CACHE_SIZE_KEY, MAX_CACHE_SIZE);
TiBackgroundExecutor.execute(new TiCacheCleanup(cacheDir, cacheSize, hFile, contentLength));
synchronized (this) { // Don't add it to the cache if its already being written
if (!hFile.createNewFile())
return null;
return new TiCacheRequest(new TiCacheBodyOutputStream(bFile, hFile, sb.toString()));
}
}
}
|
package org.sakaiproject.evaluation.logic;
import java.util.List;
import org.sakaiproject.evaluation.model.EvalItem;
import org.sakaiproject.evaluation.model.EvalTemplateItem;
public interface EvalItemsLogic {
/**
* Get an item by its unique id<br/>
* An item represents a reusable question item in the system<br/>
* Note: if you need to get a group of items
* then use {@link #getItemsOwnedByUser(String)} or
* use the template collection of templateItems to get the items
*
* @param itemId the id of an EvalItem object
* @return an {@link EvalItem} object or null if not found
*/
public EvalItem getItemById(Long itemId);
public void saveItem(EvalItem item, String userId);
public void deleteItem(Long itemId, String userId);
/**
* Get a list of all the items visible to a specific user,
* can limit it to only items owned by that user or
* items by sharing level
*
* @param userId the internal user id (not username)
* @param sharingConstant a SHARING constant from
* {@link org.sakaiproject.evaluation.model.constant.EvalConstants},
* if null, return all items visible to the
* user, if set to a sharing constant then return just the visible
* items that match that sharing setting (can be used to get all
* items owned by this user for example)
* @return a list of {@link EvalItem} objects
*/
public List getItemsForUser(String userId, String sharingConstant);
/**
* Get a list of items in a template that are visible to a user,
* most of the time you will want to get the items by getting the
* templateItems from the template and then
* using that to get the items themselves or
* using {@link #getTemplateItemsForTemplate(Long, String)},
* but if you do not have the template OR you need the items
* restricted to visibility to a specific user then use this method
*
* @param templateId the unique id of an EvalTemplate object
* @param userId the internal user id (not username), if this is null then
* it will return all items in the template
* @return a list of {@link EvalItem} objects
*/
public List getItemsForTemplate(Long templateId, String userId);
// TEMPLATE ITEMS
/**
* Get a template item by its unique id<br/>
* A template item represents a specific instance of an item in a specific template<br/>
* Note: if you need to get a group of template items
* then use {@link #getTemplateItemsForTemplate(Long)}
*
* @param templateItemId the id of an EvalTemplateItem object
* @return an {@link EvalTemplateItem} object or null if not found
*/
public EvalTemplateItem getTemplateItemById(Long templateItemId);
/**
* Save a templateItem to create a link between an item and a template or
* update display settings for an item in a template,
* template items cannot be saved in locked templates, the item and template
* cannot be changed after the templateItem is created<br/>
* A template item represents a specific instance of an item in a specific template<br/>
* Validates display settings based on the type of item, creates the association between
* the template and this templateItem and the item and this templateItem,
* fills in default optional values, sets the display order correctly for newly
* created items (to the next available number)
*
* @param templateItem a templateItem object to be saved
* @param userId the internal user id (not username)
*/
public void saveTemplateItem(EvalTemplateItem templateItem, String userId);
public void deleteTemplateItem(Long templateItemId, String userId);
/**
* Get all the templateItems for this template that are visible to a user,
* most of the time you will want to just get the items by getting the
* templateItems from the template itself,
* but if you do not have the template OR you need the templateItems
* restricted to visibility to a specific user then use this method
*
* @param templateId the unique id of an EvalTemplate object
* @param userId the internal user id (not username), if this is null then
* it will return all items in the template
* @return a list of {@link EvalTemplateItem} objects, ordered by displayOrder
*/
public List getTemplateItemsForTemplate(Long templateId, String userId);
// BLOCKS
/**
* Get the child block templateItems for a parent templateItem,
* optionally include the parent templateItem,
* returns the items in display order (with parent first if requested)
*
* @param parentId the unique id of the parent {@link EvalTemplateItem} object
* @param includeParent if false then only return child items, if true then return the entire block (parent and child items)
* @return a List of {@link EvalTemplateItem} objects
*/
public List getBlockChildTemplateItemsForBlockParent(Long parentId, boolean includeParent);
// EXPERT ITEMS
// TODO - stuff here! -AZ
/**
* Check if a user can control (update or delete) a specific item,
* locked items cannot be modified in any way
*
* @param userId the internal user id (not username)
* @param itemId the id of an {@link EvalItem} object
* @return true if user can control this item, false otherwise
*/
public boolean canControlItem(String userId, Long itemId);
/**
* Check if a user can control (update or delete) a specific templateItem,
* templateItems associated with a locked template cannot be modified
*
* @param userId the internal user id (not username)
* @param templateItemId the id of an {@link EvalTemplateItem} object
* @return true if user can control this templateItem, false otherwise
*/
public boolean canControlTemplateItem(String userId, Long templateItemId);
}
|
package org.royaldev.royalcommands.rcommands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
import org.royaldev.royalcommands.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Random;
public class CmdWorldManager implements CommandExecutor {
RoyalCommands plugin;
public CmdWorldManager(RoyalCommands instance) {
plugin = instance;
}
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("worldmanager")) {
if (!plugin.isAuthorized(cs, "rcmds.worldmanager")) {
RUtils.dispNoPerms(cs);
return true;
}
if (args.length < 1) {
cs.sendMessage(cmd.getDescription());
return false;
}
String command = args[0].toLowerCase();
if (command.equals("create")) {
if (args.length < 4) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
String name = args[1];
for (World w : plugin.getServer().getWorlds()) {
if (w.getName().equals(name)) {
cs.sendMessage(ChatColor.RED + "A world with that name already exists!");
return true;
}
}
WorldType type = WorldType.getByName(args[2].toUpperCase());
if (type == null) {
cs.sendMessage(ChatColor.RED + "Invalid world type!");
String types = "";
for (WorldType t : WorldType.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.getName() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.getName() + ChatColor.WHITE);
cs.sendMessage(types);
return true;
}
World.Environment we;
try {
we = World.Environment.valueOf(args[3].toUpperCase());
} catch (Exception e) {
cs.sendMessage(ChatColor.RED + "Invalid environment!");
String types = "";
for (World.Environment t : World.Environment.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.name() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.name() + ChatColor.WHITE);
cs.sendMessage(types);
return true;
}
cs.sendMessage(ChatColor.BLUE + "Creating world...");
WorldCreator wc = new WorldCreator(name);
wc = wc.type(type);
wc = wc.environment(we);
if (args.length > 4) {
long seed;
try {
seed = Long.valueOf(args[4]);
} catch (Exception e) {
seed = args[4].hashCode();
}
wc = wc.seed(seed);
} else wc = wc.seed(new Random().nextLong());
if (args.length > 5) {
wc = wc.generator(args[5]);
RoyalCommands.wm.getConfig().setString(args[5], "worlds." + name + ".generator");
}
World w = wc.createWorld();
w.save();
cs.sendMessage(ChatColor.BLUE + "World " + ChatColor.GRAY + w.getName() + ChatColor.BLUE + " created successfully.");
return true;
} else if (command.equals("unload")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
World w = plugin.getServer().getWorld(args[1]);
if (w == null) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Unloading world...");
if (args.length > 2 && Boolean.getBoolean(args[2].toLowerCase()))
for (Player p : w.getPlayers())
p.kickPlayer("Your world is being unloaded!");
boolean success = plugin.getServer().unloadWorld(w, true);
if (success)
cs.sendMessage(ChatColor.BLUE + "World unloaded successfully!");
else cs.sendMessage(ChatColor.RED + "Could not unload that world.");
return true;
} else if (command.equals("delete")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
World w = plugin.getServer().getWorld(args[1]);
if (w == null) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Unloading world...");
if (args.length > 2 && args[2].equalsIgnoreCase("true"))
for (Player p : w.getPlayers())
p.kickPlayer("Your world is being unloaded!");
boolean success = plugin.getServer().unloadWorld(w, true);
if (success)
cs.sendMessage(ChatColor.BLUE + "World unloaded successfully!");
else {
cs.sendMessage(ChatColor.RED + "Could not unload that world.");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Deleting world...");
try {
FileUtils.deleteDirectory(w.getWorldFolder());
success = true;
} catch (IOException e) {
success = false;
}
if (success)
cs.sendMessage(ChatColor.BLUE + "Successfully deleted world!");
else cs.sendMessage(ChatColor.RED + "Could not delete world.");
return true;
} else if (command.equals("list")) {
cs.sendMessage(ChatColor.BLUE + "Worlds:");
String worlds = "";
for (World w : plugin.getServer().getWorlds())
worlds = (worlds.equals("")) ? worlds.concat(ChatColor.GRAY + RUtils.getMVWorldName(w)) : worlds.concat(ChatColor.WHITE + ", " + ChatColor.GRAY + RUtils.getMVWorldName(w));
cs.sendMessage(worlds);
return true;
} else if (command.equals("help")) {
cs.sendMessage(ChatColor.BLUE + "RoyalCommands WorldManager Help");
cs.sendMessage(ChatColor.BLUE + "===============================");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " create [name] [type] [environment] (seed) (generator)" + ChatColor.BLUE + " - Creates a new world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " load [name]" + ChatColor.BLUE + " - Loads a world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " unload [name] (true)" + ChatColor.BLUE + " - Unloads a world. If true is specified, will kick all players on the world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " delete [name] (true)" + ChatColor.BLUE + " - Unloads and deletes a world. If true is specified, will kick all players on the world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " info" + ChatColor.BLUE + " - Displays available world types and environments; if you are a player, displays information about your world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " help" + ChatColor.BLUE + " - Displays this help.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " list" + ChatColor.BLUE + " - Lists all the loaded worlds.");
return true;
} else if (command.equals("load")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
String name = args[1];
boolean contains = false;
for (File f : plugin.getServer().getWorldContainer().listFiles()) {
if (f.getName().equals(name)) contains = true;
}
if (!contains) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
World w;
try {
w = RoyalCommands.wm.loadWorld(name);
} catch (IllegalArgumentException e) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
} catch (NullPointerException e) {
cs.sendMessage(ChatColor.RED + "Could not read world folders!");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Loaded world " + ChatColor.GRAY + w.getName() + ChatColor.BLUE + ".");
return true;
} else if (command.equals("info")) {
cs.sendMessage(ChatColor.BLUE + "RoyalCommands WorldManager Info");
cs.sendMessage(ChatColor.BLUE + "===============================");
cs.sendMessage(ChatColor.BLUE + "Available world types:");
String types = "";
for (WorldType t : WorldType.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.getName() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.getName() + ChatColor.WHITE);
cs.sendMessage(" " + types);
types = "";
cs.sendMessage(ChatColor.BLUE + "Available world environments:");
for (World.Environment t : World.Environment.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.name() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.name() + ChatColor.WHITE);
cs.sendMessage(" " + types);
if (!(cs instanceof Player)) return true;
Player p = (Player) cs;
World w = p.getWorld();
cs.sendMessage(ChatColor.BLUE + "Information on this world:");
cs.sendMessage(ChatColor.BLUE + "Name: " + ChatColor.GRAY + w.getName());
cs.sendMessage(ChatColor.BLUE + "Environment: " + ChatColor.GRAY + w.getEnvironment().name());
return true;
} else if (command.equals("tp") || command.equals("teleport")) {
if (!(cs instanceof Player)) {
cs.sendMessage(ChatColor.RED + "This command is only available to players!");
return true;
}
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
Player p = (Player) cs;
String world = args[1];
World w = plugin.getServer().getWorld(world);
if (w == null) {
cs.sendMessage(ChatColor.RED + "That world does not exist!");
return true;
}
p.sendMessage(ChatColor.BLUE + "Teleporting you to world " + ChatColor.GRAY + RUtils.getMVWorldName(w) + ChatColor.BLUE + ".");
String error = RUtils.teleport(p, CmdSpawn.getWorldSpawn(w));
if (!error.isEmpty()) {
p.sendMessage(ChatColor.RED + error);
return true;
}
return true;
} else if (command.equals("who")) {
for (World w : plugin.getServer().getWorlds()) {
StringBuilder sb = new StringBuilder(RUtils.getMVWorldName(w));
sb.append(": ");
if (w.getPlayers().isEmpty()) {
cs.sendMessage(ChatColor.RED + "No players in " + ChatColor.GRAY + RUtils.getMVWorldName(w) + ChatColor.RED + ".");
continue;
}
for (Player p : w.getPlayers()) {
sb.append(ChatColor.GRAY);
sb.append(p.getName());
sb.append(ChatColor.RESET);
sb.append(", ");
}
cs.sendMessage(sb.substring(0, sb.length() - 4));
}
return true;
} else {
cs.sendMessage(ChatColor.RED + "Invalid subcommand!");
return true;
}
}
return false;
}
}
|
package ch.hslu.mobpro.proj.thinkquick.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import ch.hslu.mobpro.proj.thinkquick.game.checker.ExerciseResult;
/**
* This class represents a database adapter.
*/
public class DbAdapter {
public final static String DB_NAME = "thinkDb";
public final static int DB_VERSION = 1;
public final static String DB_RESULT_TABLE = "tbl_results";
private final static int SQLITE_ERROR_CODE = -1;
private final DbHelper dbHelper;
private SQLiteDatabase db;
public DbAdapter(final Context context) {
dbHelper = new DbHelper(context);
}
/**
* Opens the database with write access.
*/
public void open() {
if (db == null || !db.isOpen()) {
db = dbHelper.getWritableDatabase();
}
}
/**
* Closes the database.
*/
public void close() {
dbHelper.close();
}
/**
* Inserts the given result into the database.
*
* @param result The exercise result.
* @throws IOException If the result could not be inserted.
*/
public void insert(final ExerciseResult result) throws IOException {
final ContentValues values = new ContentValues();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
values.put("date", simpleDateFormat.format(new Date()));
values.put("points", result.getPoints());
final long id = db.insert(DB_RESULT_TABLE, null, values);
if (id == SQLITE_ERROR_CODE) {
throw new IOException("The result could not be inserted.");
}
}
public void insert(final int points, final Date date) throws IOException {
final ContentValues values = new ContentValues();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
values.put("date", simpleDateFormat.format(date));
values.put("points", points);
final long id = db.insert(DB_RESULT_TABLE, null, values);
if (id == SQLITE_ERROR_CODE) {
throw new IOException("The result could not be inserted.");
}
}
/**
* Reads all results from the result table.
*
* @return A list with all results.
* @throws IOException If the results could not be read.
*/
public List<DbResultsEntry> getAllResults() throws IOException {
final List<DbResultsEntry> results = new ArrayList<>();
final Cursor cursor = initAllResultCursor(DB_RESULT_TABLE);
while (!cursor.isAfterLast()) {
results.add(fetchResultFromCursor(cursor));
cursor.moveToNext();
}
cursor.close();
return results;
}
/**
* Initializes a db cursor to read all results ordered by Points.
*
* @param tableName The table with results.
* @return Database sursor.
* @throws IOException If the results could not be read.
*/
private Cursor initAllResultCursor(final String tableName) throws IOException {
final Cursor cursor = db.rawQuery("SELECT * FROM " + tableName + " ORDER BY Points", null);
if (!cursor.moveToFirst()) {
throw new IOException("Could not read from table " + tableName);
}
return cursor;
}
public void clearAllContent() {
db.execSQL("delete from " + DB_RESULT_TABLE);
}
/**
* Reads the current table entry of the given cursor. This method creates an ExerciseResult object.
*
* @param cursor Database cursor.
* @return The current result.
*/
private DbResultsEntry fetchResultFromCursor(final Cursor cursor) {
final DbResultsEntry currentResult = new DbResultsEntry();
currentResult.setPoints(cursor.getInt(1));
currentResult.setDate(cursor.getString(0));
return currentResult;
}
}
|
package cmput301f17t01.bronzify.controllers;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.searchly.jestdroid.DroidClientConfig;
import com.searchly.jestdroid.JestClientFactory;
import com.searchly.jestdroid.JestDroidClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import cmput301f17t01.bronzify.adapters.UserAdapter;
import cmput301f17t01.bronzify.exceptions.ElasticException;
import cmput301f17t01.bronzify.models.AppLocale;
import cmput301f17t01.bronzify.models.User;
import io.searchbox.client.JestResult;
import io.searchbox.core.Delete;
import io.searchbox.core.DocumentResult;
import io.searchbox.core.Get;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
public class ElasticSearch {
private static JestDroidClient client;
private static String serverString = "http://cmput301.softwareprocess.es:8080";
private static String indexString = "cmput301f17t01_bronzify";
private static String typeString = "test_user_v2";
private static final Gson userGson = new GsonBuilder().registerTypeAdapter(User.class,
new UserAdapter()).create();
public User update(User user) {
User remoteUser = getUser(user.getUserID());
if (remoteUser == null) { //elasticsearch error
return user;
}
if (remoteUser.getLastUpdated().after(user.getLastUpdated())) {
return remoteUser;
} else {
user.setLastUpdated(new Date());
postUser(user);
return user;
}
}
public void requestFollow(User user, String otherUserID) {
if (user.getFollowing().contains(otherUserID)){
Log.i("Error", "already following");
return;
}
User remoteUser = getUser(otherUserID);
if (remoteUser == null) {
Log.i("Error", "user not found");
return;
}
if (remoteUser.getPendingFollowRequests().contains(user.getUserID())) {
Log.i("Error", "already sent request");
return;
}
remoteUser.addPendingFollowRequest(user.getUserID());
remoteUser.setLastInfluenced(new Date());
postUser(remoteUser);
}
public void acceptFollow(User user, String otherUserID) {
User remoteUser = getUser(otherUserID);
remoteUser.addFollowing(user.getUserID());
remoteUser.setLastInfluenced(new Date());
postUser(remoteUser);
user.removePendingFollowRequest(otherUserID);
user.addFollowedBy(otherUserID);
userUpdate(user);
}
public void userUpdate(User user) {
ElasticSearch elastic = new ElasticSearch();
User newestUser = elastic.update(user);
user.setLastUpdated(newestUser.getLastUpdated());
user.setFollowing(newestUser.getFollowing());
user.setPendingFollowRequests(newestUser.getPendingFollowRequests());
user.setHabitTypes(newestUser.getHabitTypes());
AppLocale.getInstance().setUser(user);
}
public void postUser(User user) {
ElasticSearch.PostUser addUserTask
= new ElasticSearch.PostUser();
addUserTask.execute(user);
}
public User getUserLocalFirst(String userID) {
User foundUser = AppLocale.getInstance().getLocalUser(userID);
if (foundUser == null) {
ElasticSearch.GetUser getUserTask
= new ElasticSearch.GetUser();
getUserTask.execute(userID);
try {
foundUser = getUserTask.get();
} catch (Exception e) {
foundUser = null;
// e.printStackTrace();
}
}
return foundUser;
}
public User getUser(String userID) {
User foundUser;
ElasticSearch.GetUser getUserTask
= new ElasticSearch.GetUser();
getUserTask.execute(userID);
try {
foundUser = getUserTask.get();
} catch (Exception e) {
foundUser = null;
// e.printStackTrace();
}
if (foundUser == null) {
foundUser = AppLocale.getInstance().getLocalUser(userID);
}
return foundUser;
}
public void deleteUser(String userID) {
AppLocale appLocale = AppLocale.getInstance();
appLocale.removeLocalUser(userID);
ElasticSearch.DeleteUser deleteUserTask
= new ElasticSearch.DeleteUser();
deleteUserTask.execute(userID);
}
public ArrayList<User> findHighScore() {
ArrayList<User> users = new ArrayList<>();
ElasticSearch.FindHighScore highScoreTask
= new ElasticSearch.FindHighScore();
highScoreTask.execute();
try {
users = highScoreTask.get();
} catch (Exception e) {
// e.printStackTrace();
}
return users;
}
public static class PostUser extends AsyncTask<User, Void, Void> {
@Override
protected Void doInBackground(User... users) {
verifySettings();
for (User user : users) {
String userJson = userGson.toJson(user);
Index index = new Index.Builder(userJson)
.index(indexString)
.type(typeString)
.id(user.getUserID())
.build();
try {
DocumentResult result = client.execute(index);
if (result.isSucceeded()) {
user.setUserID(result.getId());
} else {
throw new ElasticException();
}
} catch (Exception e) {
Log.i("Error", "The application failed to build and send the user");
}
}
return null;
}
}
public static class GetUser extends AsyncTask<String, Void, User> {
@Override
protected User doInBackground(String... strings) {
verifySettings();
User foundUser = null;
Get get = new Get.Builder(indexString, strings[0]) //index, id
.type(typeString)
.build();
Log.i("Get", get.toString());
try {
JestResult result = client.execute(get);
if (result.isSucceeded()) {
String foundJson = result.getSourceAsString();
foundUser = userGson.fromJson(foundJson, User.class);
} else {
throw new ElasticException();
}
} catch (ElasticException e) {
Log.i("Error", "Something went wrong when communicating with the server");
foundUser = null;
// foundUser = AppLocale.getInstance().getLocalUser(strings[0]);
} catch (IOException e) {
foundUser = null;
// foundUser = AppLocale.getInstance().getLocalUser(strings[0]);
Log.i("Error", "Could not connect to the server");
}
return foundUser;
}
}
public static class DeleteUser extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... strings) {
verifySettings();
Delete delete = new Delete.Builder(strings[0])
.index(indexString)
.type(typeString)
.build();
try {
JestResult result = client.execute(delete);
if (result.isSucceeded()) {
Log.i("User", "deleted");
} else {
throw new ElasticException();
}
} catch (Exception e) {
Log.i("Error", "Something went wrong");
}
return null;
}
}
public static class FindHighScore extends AsyncTask<Void, Void, ArrayList<User>> {
@Override
protected ArrayList<User> doInBackground(Void... voids) {
verifySettings();
ArrayList<User> users = new ArrayList<User>();
/*
'{
"sort" : [
{"score" : {"order" : "desc"}}
]
}' */
String query =
"{\n" +
" \"sort\": [\n" +
" {\"score\" : {\"order\" : \"desc\"}}\n" +
" ]\n" +
"}";
// SearchSourceBuilder ssb = new SearchSourceBuilder()
// .sort("score", SortOrder.DESC)
// .size(20);
Search search = new Search.Builder(query)
.addIndex(indexString)
.addType(typeString)
.build();
try {
SearchResult result = client.execute(search);
if (result.isSucceeded()) {
List<String> strhits = result.getSourceAsStringList();
Iterator<String> itr = strhits.iterator();
while (itr.hasNext()) {
User next = userGson.fromJson(itr.next(), User.class);
users.add(next);
}
return users;
} else {
throw new ElasticException();
}
} catch (ElasticException e) {
Log.i("Error", "Something went wrong when communicating with the server");
// foundUser = AppLocale.getInstance().getLocalUser(strings[0]);
} catch (IOException e) {
// foundUser = AppLocale.getInstance().getLocalUser(strings[0]);
Log.i("Error", "Could not connect to the server");
}
return users;
}
}
public static void verifySettings() {
if (client == null) {
DroidClientConfig.Builder builder = new DroidClientConfig
//.Builder("localhost:9200");
.Builder(serverString);
DroidClientConfig config = builder.build();
JestClientFactory factory = new JestClientFactory();
factory.setDroidClientConfig(config);
client = (JestDroidClient) factory.getObject();
}
}
}
|
package com.averi.worldscribe.dropbox;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.averi.worldscribe.R;
import com.averi.worldscribe.utilities.FileRetriever;
import com.dropbox.core.DbxException;
import com.dropbox.core.v2.DbxClientV2;
import com.dropbox.core.v2.files.CreateFolderErrorException;
import com.dropbox.core.v2.files.WriteMode;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class UploadToDropboxTask extends AsyncTask {
private DbxClientV2 dbxClient;
private File file;
private Context context;
private boolean uploadSuccessful = true;
private ProgressDialog progressDialog;
public UploadToDropboxTask(DbxClientV2 dbxClient, File file, Context context) {
this.dbxClient = dbxClient;
this.file = file;
this.context = context;
}
@Override
protected void onPreExecute() {
showProgressDialog();
}
/**
* Displays a loading dialog that will stay on-screen while uploading occurs.
*/
private void showProgressDialog() {
String title = context.getString(R.string.dropboxUploadProgressTitle);
String message = context.getString(R.string.dropboxUploadProgressMessage);
progressDialog = ProgressDialog.show(context, title, message);
}
@Override
protected Object doInBackground(Object[] params) {
try {
uploadRecursive(file);
} catch (DbxException | IOException e) {
Log.e("WorldScribe", e.getMessage());
uploadSuccessful = false;
}
return null;
}
/**
* Upload the given file to Dropbox; if it is a directory, its contents will be recursively
* uploaded.
* @param originalFile The file to upload to the client's Dropbox account
* @throws DbxException If an error occurs with accessing the client's Dropbox account
* @throws IOException If an error occurs with file uploading
*/
private void uploadRecursive(File originalFile) throws DbxException, IOException {
if (file.exists()) {
File[] files = originalFile.listFiles();
for (int i = 0; i < files.length; ++i) {
File file = files[i];
String dropboxPath = getDropboxPath(file);
if (file.isDirectory()) {
try {
dbxClient.files().createFolder(dropboxPath);
} catch (CreateFolderErrorException ex) {
}
uploadRecursive(file);
} else {
InputStream inputStream = new FileInputStream(file);
dbxClient.files().uploadBuilder(dropboxPath)
.withMode(WriteMode.OVERWRITE)
.uploadAndFinish(inputStream);
}
}
}
}
/**
* Returns the path of the given Android file on the client's Dropbox account.
* @param file The file whose Dropbox path will be retrieved
* @return The Dropbox file path of file
*/
private String getDropboxPath(File file) {
String androidFilePath = file.getAbsolutePath();
String appFilePath = FileRetriever.getAppDirectory().getAbsolutePath();
String dropboxPath = androidFilePath.replace(appFilePath, "");
// Dropbox will not upload files that have a "." prefix.
// To get around this, we upload those files without the "." prefix.
String fileName = file.getName();
if (fileName.startsWith(".")) {
String fileNameWithoutDotPrefix = fileName.substring(1);
dropboxPath = dropboxPath.replace(fileName, fileNameWithoutDotPrefix);
}
return dropboxPath;
}
@Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
progressDialog.dismiss();
showOutcomeDialog();
}
/**
* Displays an AlertDialog telling the user whether or not the upload was successful.
*/
private void showOutcomeDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
String message;
if (uploadSuccessful) {
message = context.getString(R.string.dropboxUploadSuccess);
} else {
message = context.getString(R.string.dropboxUploadFailure);
}
builder.setMessage(message);
builder.setPositiveButton(context.getString(R.string.dismissDropboxUploadOutcome), null);
builder.create().show();
}
}
|
package com.battlelancer.seriesguide.settings;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.format.DateUtils;
import androidx.preference.PreferenceManager;
import com.battlelancer.seriesguide.BuildConfig;
import com.google.firebase.crashlytics.FirebaseCrashlytics;
import timber.log.Timber;
public class AppSettings {
public static final String KEY_VERSION = "oldversioncode";
public static final String KEY_GOOGLEANALYTICS = "enableGAnalytics";
@SuppressWarnings("unused")
@Deprecated
public static final String KEY_HAS_SEEN_NAV_DRAWER = "hasSeenNavDrawer";
public static final String KEY_ASKED_FOR_FEEDBACK = "askedForFeedback";
public static final String KEY_SEND_ERROR_REPORTS = "com.battlelancer.seriesguide.sendErrorReports";
public static final String KEY_USER_DEBUG_MODE_ENBALED = "com.battlelancer.seriesguide.userDebugModeEnabled";
/**
* Returns the version code of the previously installed version. Is the current version on fresh
* installs.
*/
public static int getLastVersionCode(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int lastVersionCode = prefs.getInt(KEY_VERSION, -1);
if (lastVersionCode == -1) {
// set current version as default value
lastVersionCode = BuildConfig.VERSION_CODE;
prefs.edit().putInt(KEY_VERSION, lastVersionCode).apply();
}
return lastVersionCode;
}
public static boolean isGaEnabled(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_GOOGLEANALYTICS, true);
}
public static boolean shouldAskForFeedback(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean(KEY_ASKED_FOR_FEEDBACK, false)) {
return false; // already asked for feedback
}
try {
PackageInfo ourPackageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
boolean installedRecently = System.currentTimeMillis()
< ourPackageInfo.firstInstallTime + 30 * DateUtils.DAY_IN_MILLIS;
if (installedRecently) {
return false; // was only installed recently
}
} catch (PackageManager.NameNotFoundException e) {
Timber.e(e, "Failed to find our package info.");
return false; // failed to find our package
}
return true;
}
public static void setAskedForFeedback(Context context) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_ASKED_FOR_FEEDBACK, true)
.apply();
}
public static boolean isSendErrorReports(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_SEND_ERROR_REPORTS, true);
}
public static void setSendErrorReports(Context context, boolean isEnabled, boolean save) {
if (save) {
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putBoolean(KEY_SEND_ERROR_REPORTS, isEnabled)
.apply();
}
Timber.d("Turning error reporting %s", isEnabled ? "ON" : "OFF");
FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(isEnabled);
}
/**
* Returns if user-visible debug components should be enabled
* (e.g. logging to logcat, debug views). Always true for debug builds.
*/
public static boolean isUserDebugModeEnabled(Context context) {
return BuildConfig.DEBUG || PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_USER_DEBUG_MODE_ENBALED, false);
}
}
|
package com.carltondennis.spotifystreamer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.session.PlaybackState;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.util.ArrayList;
public class PlaybackService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener {
public static final String TAG = PlaybackService.class.getSimpleName();
public static final String ACTION_PLAY = "action_play";
public static final String ACTION_PAUSE = "action_pause";
public static final String ACTION_NEXT = "action_next";
public static final String ACTION_PREVIOUS = "action_previous";
public static final String ACTION_STOP = "action_stop";
public static final String ACTION_SEEK_TO = "action_seek_to";
public static final String ACTION_UPDATE_STATE = "action_update_state";
public static final String SEEK_POS_KEY = "seek_pos";
private static final int NOTIFICATION_ID = 411;
private MediaPlayer mMediaPlayer;
private ArrayList<SpotifyTrack> mTracks;
private int mTracksQueuePosition;
private int mCurrentPosition;
private int mState;
private NotificationManager mNotificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
private void handleIntent(Intent intent) {
if (intent == null || intent.getAction() == null)
return;
setupQueueFromIntent(intent);
String action = intent.getAction();
if (action.equalsIgnoreCase(ACTION_PLAY)) {
play();
buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
} else if (action.equalsIgnoreCase(ACTION_PAUSE)) {
pause();
buildNotification(generateAction(android.R.drawable.ic_media_play, "Play", ACTION_PLAY));
} else if (action.equalsIgnoreCase(ACTION_PREVIOUS)) {
skipToPrevious();
buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
} else if (action.equalsIgnoreCase(ACTION_NEXT)) {
skipToNext();
buildNotification(generateAction(android.R.drawable.ic_media_pause, "Pause", ACTION_PAUSE));
} else if (action.equalsIgnoreCase(ACTION_STOP)) {
stop();
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(1);
stopSelf();
} else if (action.equalsIgnoreCase(ACTION_SEEK_TO)) {
Bundle extras = intent.getExtras();
if (extras != null && extras.containsKey(SEEK_POS_KEY)) {
int pos = extras.getInt(SEEK_POS_KEY, 0);
if (pos != 0) {
seekTo(pos);
}
}
} else if (action.equalsIgnoreCase(ACTION_UPDATE_STATE)) {
updatePlaybackState(null);
}
}
private void setupQueueFromIntent(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
Log.d(TAG, "Setting up queue for PlaybackService");
if (extras.containsKey(PlayerActivityFragment.TRACK_KEY) && extras.containsKey(PlayerActivityFragment.TRACKS_KEY)) {
mTracks = extras.getParcelableArrayList(PlayerActivityFragment.TRACKS_KEY);
mTracksQueuePosition = extras.getInt(PlayerActivityFragment.TRACK_KEY);
}
}
}
private Notification.Action generateAction(int icon, String title, String intentAction) {
Intent intent = new Intent(getApplicationContext(), PlaybackService.class);
intent.setAction(intentAction);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
return new Notification.Action.Builder(icon, title, pendingIntent).build();
}
private void buildNotification(Notification.Action action) {
Notification.MediaStyle style = new Notification.MediaStyle();
if (mTracks == null || mTracksQueuePosition < 0 || mTracksQueuePosition > mTracks.size()) {
return;
}
SpotifyTrack track = mTracks.get(mTracksQueuePosition);
Intent intent = new Intent(getApplicationContext(), PlaybackService.class);
intent.setAction(ACTION_STOP);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
final Notification.Builder builder = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setVisibility(Notification.VISIBILITY_PUBLIC)
.setContentTitle(track.name)
.setContentText(track.albumName)
.setContentIntent(createContentIntent())
.setDeleteIntent(pendingIntent)
.setStyle(style);
builder.addAction(generateAction(android.R.drawable.ic_media_previous, "Previous", ACTION_PREVIOUS));
builder.addAction(action);
builder.addAction(generateAction(android.R.drawable.ic_media_next, "Next", ACTION_NEXT));
style.setShowActionsInCompactView(0, 1, 2);
Picasso.with(getApplicationContext())
.load(track.imageLargeURL)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// cache is now warmed up
builder.setLargeIcon(bitmap);
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
private PendingIntent createContentIntent() {
Intent openUI = new Intent(getApplicationContext(), PlayerActivity.class);
openUI.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
openUI.putExtra(PlayerActivityFragment.TRACK_KEY, mTracksQueuePosition);
openUI.putExtra(PlayerActivityFragment.TRACKS_KEY, mTracks);
openUI.putExtra(PlayerActivityFragment.ARTIST_KEY, "Michael J");
return PendingIntent.getActivity(getApplicationContext(), 1, openUI,
PendingIntent.FLAG_CANCEL_CURRENT);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleIntent(intent);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onPrepared(MediaPlayer player) {
player.start();
if (player.isPlaying()) {
mState = PlaybackState.STATE_PLAYING;
updatePlaybackState(null);
}
}
/**
* Called when there's an error playing media. When this happens, the media
* player goes to the Error state. We warn the user about the error and
* reset the media player.
*
* @see MediaPlayer.OnErrorListener
*/
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(TAG, "Media player error: what=" + what + ", extra=" + extra);
return true; // true indicates we handled the error
}
@Override
public void onCompletion(MediaPlayer mp) {
skipToNext();
}
@Override
public void onSeekComplete(MediaPlayer mp) {
Log.d(TAG, "onSeekComplete from MediaPlayer:" + mp.getCurrentPosition());
mCurrentPosition = mp.getCurrentPosition();
if (mState == PlaybackState.STATE_BUFFERING) {
mMediaPlayer.start();
mState = PlaybackState.STATE_PLAYING;
}
}
private void createMediaPlayerIfNeeded() {
if (mMediaPlayer == null) {
mMediaPlayer = new MediaPlayer();
// Make sure the media player will acquire a wake-lock while
// playing. If we don't do that, the CPU might go to sleep while the
// song is playing, causing playback to stop.
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
// we want the media player to notify us when it's ready preparing,
// and when it's done playing:
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnErrorListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnSeekCompleteListener(this);
} else {
mMediaPlayer.reset();
}
}
private void play() {
if (mTracksQueuePosition < 0 || mTracksQueuePosition >= mTracks.size()) {
Log.d(TAG, String.format("Invalid q pos: %d", mTracksQueuePosition));
return;
}
if (mMediaPlayer != null && mState == PlaybackState.STATE_PAUSED) {
mMediaPlayer.start();
if (mMediaPlayer.isPlaying()) {
mState = PlaybackState.STATE_PLAYING;
updatePlaybackState(null);
}
return;
}
SpotifyTrack track = mTracks.get(mTracksQueuePosition);
try {
if (track.isPlayable()) {
Log.d(TAG, "Preparing source: " + track.previewURL);
createMediaPlayerIfNeeded();
mMediaPlayer.setDataSource(track.previewURL);
mMediaPlayer.prepareAsync();
mState = PlaybackState.STATE_BUFFERING;
}
} catch (IOException ioex) {
Log.d(TAG, ioex.getMessage());
}
}
private void pause() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mState = PlaybackState.STATE_PAUSED;
updatePlaybackState(null);
}
}
}
private void skipToNext() {
mTracksQueuePosition++;
// play next track unless we are at the end of the list.
if (mTracksQueuePosition >= mTracks.size()) {
mTracksQueuePosition = mTracks.size() - 1;
} else {
play();
}
}
private void skipToPrevious() {
// Restart track if its been playing for more than a 5 seconds.
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
int currentSeekPos = mMediaPlayer.getCurrentPosition();
if (currentSeekPos >= (Utility.SECOND_IN_MILLISECONDS * 5)) {
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
updatePlaybackState(null);
return;
}
}
mTracksQueuePosition
if (mTracksQueuePosition < 0) {
mTracksQueuePosition = 0;
}
play();
}
private void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mState = PlaybackState.STATE_STOPPED;
updatePlaybackState(null);
}
}
private void seekTo(int position) {
Log.d(TAG, "seekTo called with " + position);
if (mMediaPlayer == null) {
// If we do not have a current media player, simply update the current position
mCurrentPosition = position;
} else {
if (mMediaPlayer.isPlaying()) {
mState = PlaybackState.STATE_BUFFERING;
}
mMediaPlayer.seekTo(position);
updatePlaybackState(null);
}
}
private long getAvailableActions() {
long actions = PlaybackState.ACTION_PLAY | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID |
PlaybackState.ACTION_PLAY_FROM_SEARCH;
if (mTracks == null || mTracks.isEmpty()) {
return actions;
}
if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
actions |= PlaybackState.ACTION_PAUSE;
}
if (mTracksQueuePosition > 0) {
actions |= PlaybackState.ACTION_SKIP_TO_PREVIOUS;
}
if (mTracksQueuePosition < mTracks.size() - 1) {
actions |= PlaybackState.ACTION_SKIP_TO_NEXT;
}
return actions;
}
/**
* Update the current media player state, optionally showing an error message.
*
* @param error if not null, error message to present to the user.
*/
private void updatePlaybackState(String error) {
Log.d(TAG, "updatePlaybackState, playback state=" + mState);
long position = PlaybackState.PLAYBACK_POSITION_UNKNOWN;
long duration = 0;
if (mMediaPlayer != null) {
position = mMediaPlayer.getCurrentPosition();
duration = mMediaPlayer.getDuration();
}
PlaybackState.Builder stateBuilder = new PlaybackState.Builder()
.setActions(getAvailableActions());
int state = mState;
// If there is an error message, send it to the playback state:
if (error != null) {
// Error states are really only supposed to be used for errors that cause playback to
// stop unexpectedly and persist until the user takes action to fix it.
stateBuilder.setErrorMessage(error);
state = PlaybackState.STATE_ERROR;
}
stateBuilder.setState(state, position, 1.0f, SystemClock.elapsedRealtime());
// Set the activeQueueItemId if the current index is valid.
if (mTracks != null && mTracksQueuePosition >= 0 && mTracksQueuePosition < mTracks.size()) {
stateBuilder.setActiveQueueItemId(mTracksQueuePosition);
}
// mSession.setPlaybackState(stateBuilder.build());
Intent i = new Intent(PlayerActivityFragment.PlaybackUpdateReceiver.CUSTOM_INTENT);
Bundle extras = new Bundle();
extras.putParcelable(PlayerActivityFragment.PlaybackUpdateReceiver.PLAYBACK_KEY, stateBuilder.build());
extras.putLong(PlayerActivityFragment.PlaybackUpdateReceiver.DURATION_KEY, duration);
i.putExtras(extras);
sendBroadcast(i);
// if (state == PlaybackState.STATE_PLAYING || state == PlaybackState.STATE_PAUSED) {
// mMediaNotificationManager.startNotification();
}
}
|
package com.erakk.lnreader.adapter;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.erakk.lnreader.R;
import com.erakk.lnreader.UIHelper;
import com.erakk.lnreader.dao.NovelsDao;
import com.erakk.lnreader.helper.Util;
import com.erakk.lnreader.model.BookModel;
import com.erakk.lnreader.model.NovelCollectionModel;
import com.erakk.lnreader.model.PageModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class NovelCollectionAdapter extends ArrayAdapter<PageModel> {
private static final String TAG = PageModelAdapter.class.toString();
private final Context context;
private int layoutResourceId;
public List<PageModel> data;
private PageModel[] originalData = new PageModel[0];
private HashMap<String,NovelCollectionModel> novels;
public NovelCollectionAdapter(Context context, int resourceId, List<PageModel> objects) {
super(context, resourceId, objects);
this.layoutResourceId = resourceId;
this.context = context;
this.data = objects;
novels = new HashMap<>();
Log.d(TAG, "created with " + objects.size() + " items");
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
NovelCollectionHolder holder;
final PageModel novel = data.get(position);
if (null == row) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NovelCollectionHolder();
holder.txtNovel = (TextView) row.findViewById(R.id.novel_name);
holder.txtLastCheck = (TextView) row.findViewById(R.id.novel_last_check);
holder.txtLastUpdate = (TextView) row.findViewById(R.id.novel_last_update);
holder.txtStausVol = (TextView) row.findViewById(R.id.novel_status_volumes);
holder.chkIsWatched = (CheckBox) row.findViewById(R.id.novel_is_watched);
holder.ivNovelCover = (ImageView) row.findViewById(R.id.novel_cover);
holder.imgprogressBar = (ProgressBar) row.findViewById(R.id.imgprogressBar);
row.setTag(holder);
} else {
holder = (NovelCollectionHolder) row.getTag();
}
if (holder.txtNovel != null) {
holder.txtNovel.setText(novel.getTitle());
if (novel.isHighlighted()) {
holder.txtNovel.setTypeface(null, Typeface.BOLD);
holder.txtNovel.setTextSize(20);
holder.txtNovel.setText("⇒" + holder.txtNovel.getText());
}
}
if (holder.txtLastUpdate != null) {
holder.txtLastUpdate.setText(context.getResources().getString(R.string.last_update) + ": " + Util.formatDateForDisplay(context, novel.getLastUpdate()));
}
if (holder.txtLastCheck != null) {
holder.txtLastCheck.setText(context.getResources().getString(R.string.last_check) + ": " + Util.formatDateForDisplay(context, novel.getLastUpdate()));
}
if (holder.chkIsWatched != null) {
// Log.d(TAG, page.getId() + " " + page.getTitle() + " isWatched: " + page.isWatched());
holder.chkIsWatched.setOnCheckedChangeListener(null);
holder.chkIsWatched.setChecked(novel.isWatched());
holder.chkIsWatched.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
Toast.makeText(context, "Added to watch list: " + novel.getTitle(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "Removed from watch list: " + novel.getTitle(), Toast.LENGTH_SHORT).show();
}
// update the db!
novel.setWatched(isChecked);
NovelsDao.getInstance().updatePageModel(novel);
}
});
}
holder.ivNovelCover.setImageResource(R.drawable.dummy_1);
holder.txtStausVol.setText("N/A");
holder.ivNovelCover.setVisibility(View.GONE);
holder.imgprogressBar.setVisibility(View.VISIBLE);
holder.position = position;
if(novels.get(novel.getTitle())==null) {
new NovelLoader(position, holder).execute(novel);
}
else
{
populate(novels.get(novel.getTitle()),holder);
}
return row;
}
public List<PageModel> allData;
public void filterData(String query) {
// keep the original data
if(allData == null || allData.size() < data.size()) {
allData = new ArrayList<PageModel>();
allData.addAll(data);
}
if(Util.isStringNullOrEmpty(query)) {
// restore data
data.clear();
if(allData.size() > data.size()) {
data.addAll(allData);
}
}
else {
query = query.toLowerCase();
this.clear();
data.clear();
for(PageModel item : allData) {
if(item.getTitle().toLowerCase().contains(query)) data.add(item);
}
}
super.notifyDataSetChanged();
Log.d(TAG, "Filtered result : " + data.size());
}
public void filterData() {
this.clear();
data.clear();
for (PageModel item : originalData) {
if (!item.isHighlighted()) {
if (!UIHelper.getShowRedlink(getContext()) && item.isRedlink())
continue;
if (!UIHelper.getShowMissing(getContext()) && item.isMissing())
continue;
if (!UIHelper.getShowExternal(getContext()) && item.isExternal())
continue;
}
data.add(item);
}
super.notifyDataSetChanged();
Log.d(TAG, "Filtered result : " + data.size());
}
static class NovelCollectionHolder {
TextView txtNovel;
TextView txtLastUpdate;
TextView txtStausVol;
TextView txtLastCheck;
CheckBox chkIsWatched;
ImageView ivNovelCover;
int position;
ProgressBar imgprogressBar;
}
public void setResourceId(int id) {
this.layoutResourceId = id;
}
private void populate(NovelCollectionModel novelCollectionModel, NovelCollectionHolder holder)
{
PageModel novelpage = null;
try {
novelpage = novelCollectionModel.getPageModel();
} catch (Exception e) {
e.printStackTrace();
}
if(holder.ivNovelCover != null)
{
holder.ivNovelCover.setVisibility(View.VISIBLE);
holder.imgprogressBar.setVisibility(View.GONE);
if(novelCollectionModel!=null&&novelCollectionModel.getCoverBitmap()!=null) {
holder.ivNovelCover.setImageBitmap(novelCollectionModel.getCoverBitmap());
}
else
{
holder.ivNovelCover.setImageResource(R.drawable.dummy_2);
}
}
if (holder.txtStausVol !=null){
if(novelpage==null)
{
holder.txtStausVol.setText("N/A");
}
else
{
String category = getCategory(novelpage);
int volumes = novelCollectionModel.getBookCollections().size();
if(category.isEmpty())
{
holder.txtStausVol.setText(volumes + " Volume"+(volumes>1?"s":""));
}
else {
holder.txtStausVol.setText(category + " | " + volumes + " Volume"+(volumes>1?"s":""));
}
}
}
}
private String getCategory(PageModel novelpage)
{
ArrayList<String> categories = novelpage.getCategories();
for(String category:categories)
{
if(category.contains("Project"))
{
return category.substring(0,category.indexOf("Project")).replace("Category:","");
}
}
return "";
}
private class NovelLoader extends AsyncTask<PageModel,Void,NovelCollectionModel>
{
int position;
private NovelCollectionHolder holder;
PageModel p;
NovelLoader(int position, NovelCollectionHolder holder)
{
this.position = position;
this.holder = holder;
}
@Override
protected NovelCollectionModel doInBackground(PageModel... pageModels) {
try {
p = pageModels[0];
return NovelsDao.getInstance().getNovelDetails(p,null,false);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(NovelCollectionModel novelCollectionModel) {
super.onPostExecute(novelCollectionModel);
if(holder.position == position) {
novels.put(p.getTitle(),novelCollectionModel);
populate(novelCollectionModel,holder);
}
}
}
}
|
package com.example.android.sunshine.app;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.text.SimpleDateFormat;
import java.util.ArrayList;
/**
* A placeholder fragment containing a simple view.
*/
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchForecastTask weatherTask = new FetchForecastTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecast_fragment, menu);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> data = new ArrayList<String>();
data.add("Today-Sunny-88/63");
data.add("Today-Cloudy-80/61");
data.add("Today-Windy-90/77");
data.add("Today-Rainy-85/70");
mForecastAdapter = new ArrayAdapter<String>(
//the current context, the fragment's parent activity
getActivity(),
//ID of list item layout
R.layout.list_item_forecast,
//ID of the textview to populate
R.id.list_item_forecast_textview,
//forecast data
data);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView myListView = (ListView) rootView.findViewById(R.id.listview_forecast);
myListView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchForecastTask extends AsyncTask<String, Void, String[]> {
final String LOG_TAG = ForecastFragment.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city that is being
// asked for, which means that we need to know the GMT offset to translate this data
// properly.
// Since this data is also sent in-order and the first day is always the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected void onPostExecute(String[] results) {
super.onPostExecute(results);
if(results != null){
mForecastAdapter.clear();
for (String dayForecast: results){
mForecastAdapter.add(dayForecast);
}
}
}
@Override
protected String[] doInBackground(String... params) {
if (params.length == 0)
{
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String baseUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
final String APPID_PARAM = "APPID";
Uri builtUri = Uri.parse(baseUrl).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.appendQueryParameter(APPID_PARAM, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI: " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
}
forecastJsonStr = buffer.toString();
//Log.v(LOG_TAG, "Forecast JSON Data: " + forecastJsonStr);
} catch (IOException e) {
Log.e("ForecastFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ForecastFragment", "Error closing stream", e);
}
}
}
try{
return getWeatherDataFromJson(forecastJsonStr, numDays);
}
catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
}
|
package com.familybiz.greg.taqueue.network;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class NetworkRequest {
private String BASE_URL = "http://nine.eng.utah.edu";
private RequestQueue mQueue;
public NetworkRequest(Context context) {
mQueue = Volley.newRequestQueue(context);
}
/**
* Creates a new url using the BASE_URL and the given url: BASE_URL + url.
*/
public void executeGetRequest(String url) {
executeGetRequest(url, "", "");
}
/**
* Creates a new url using the BASE_URL and the given url: BASE_URL + url. Adds the username (id)
* and password (token) as basic authorization to the header.
*/
public void executeGetRequest(String url, final String id, String token) {
// TODO: Make the change to using Uri.Builder
// Make it so the authorization variables can be accessed from the inner class
final boolean authorize = !id.isEmpty();
final String username = id;
final String password = token;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
BASE_URL + url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
parseResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Get request error", "Something was wrong with the request.");
}
}){
// Set the correct header to prevent getting html back
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
// Encode the username and password if provided
if (authorize)
encodeHeader(headers, username, password);
return headers;
}
};
mQueue.add(stringRequest);
}
public void executePostRequest(String url, JSONObject params) {
executePostRequest(url, params, "", "");
}
public void executePostRequest(String url, JSONObject params, String id, String token) {
// TODO: Make the change to using Uri.Builder
// Make it so the authorization variables can be accessed from the inner class
final boolean authorize = !id.isEmpty();
final String username = id;
final String password = token;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
BASE_URL + url,
params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
parseResponse(response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Post request error", "Something went wrong.");
}
}){
// Set the correct header to prevent getting html back
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
// Encode the username and password if provided
if (authorize)
encodeHeader(headers, username, password);
return headers;
}
};
mQueue.add(jsonObjectRequest);
}
public void executeDeleteRequest(String url, String id, String token) {
final String username = id;
final String password = token;
StringRequest stringRequest = new StringRequest(
Request.Method.DELETE,
BASE_URL + url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
parseResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Delete request error", "Something was wrong with the request.");
}
}){
// Set the correct header to prevent getting html back
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
// Encode the username and password
encodeHeader(headers, username, password);
return headers;
}
};
mQueue.add(stringRequest);
}
public void executePutRequest(String url, final Map<String, String> jsonParams, String id, String token) {
// TODO: Make the change to using Uri.Builder
// Make it so the authorization variables can be accessed from the inner class
final boolean authorize = !id.isEmpty();
final String username = id;
final String password = token;
final Map<String, String> params = jsonParams;
StringRequest stringRequest = new StringRequest(
Request.Method.PUT,
BASE_URL + url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
parseResponse(response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Post request error", "Something went wrong.");
}
}){
// Set the correct header to prevent getting html back
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("Accept", "application/json");
// Encode the username and password if provided
if (authorize)
encodeHeader(headers, username, password);
return headers;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
mQueue.add(stringRequest);
}
private void encodeHeader(Map<String, String> headers, String username, String password) {
String code = Base64.encodeToString((username + ":" + password).getBytes(), Base64.DEFAULT);
code = code.replaceAll("\n", "");
code = "Basic " + code;
headers.put("Authorization", code);
}
/**
* Parses the HTTP response into either a json object or a json array, logs the error if it
* fails. Once parsed, it will trigger all appropriate listeners.
*/
private void parseResponse(String response) {
// Json array
try {
new JSONArray(response);
for (OnJsonArrayReceivedListener listener : mOnJsonArrayReceivedListeners)
listener.onJsonArrayReceived(response);
}
catch (JSONException e) {
// Json object
try {
new JSONObject(response);
for (OnJsonObjectReceivedListener listener : mOnJsonObjectReceivedListeners)
listener.onJsonObjectReceived(response);
}
catch (JSONException e1) {
Log.e("Json Parsing", "Error in parsing the json response.");
e1.printStackTrace();
}
}
}
// Json object listener
public interface OnJsonObjectReceivedListener {
public void onJsonObjectReceived(String jsonObject);
}
private Set<OnJsonObjectReceivedListener> mOnJsonObjectReceivedListeners = new HashSet<OnJsonObjectReceivedListener>();
public void addOnJsonObjectReceivedListener(OnJsonObjectReceivedListener onJsonObjectReceivedListener) {
mOnJsonObjectReceivedListeners.add(onJsonObjectReceivedListener);
}
public void removeOnJsonObjectReceivedListener(OnJsonObjectReceivedListener onJsonObjectReceivedListener) {
mOnJsonObjectReceivedListeners.remove(onJsonObjectReceivedListener);
}
// Json array listener
public interface OnJsonArrayReceivedListener {
public void onJsonArrayReceived(String jsonArray);
}
private Set<OnJsonArrayReceivedListener> mOnJsonArrayReceivedListeners = new HashSet<OnJsonArrayReceivedListener>();
public void addOnJsonArrayReceivedListener(OnJsonArrayReceivedListener onJsonArrayReceivedListener) {
mOnJsonArrayReceivedListeners.add(onJsonArrayReceivedListener);
}
public void removeOnJsonArrayReceivedListener(OnJsonArrayReceivedListener onJsonArrayReceivedListener) {
mOnJsonArrayReceivedListeners.remove(onJsonArrayReceivedListener);
}
}
|
package de.fau.cs.mad.kwikshop.android.util;
import org.joda.time.DateTime;
import org.joda.time.Hours;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.Minutes;
import org.joda.time.Period;
import org.joda.time.ReadableDuration;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.inject.Inject;
import de.fau.cs.mad.kwikshop.android.R;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.ResourceProvider;
/**
* Date formatter for human-friendly date strings:
* - displays "just now" if event was only minutes ago
* - displays the amount of minutes passed since the date if date was within an our of current time
* - displays the time of day for events of the same day
* - displays only the date without time if the date is not today
*/
public class DateFormatter {
private final ResourceProvider resourceProvider;
@Inject
public DateFormatter(ResourceProvider resourceProvider) {
if(resourceProvider == null) {
throw new IllegalArgumentException("'resourceProvider' must not be null");
}
this.resourceProvider = resourceProvider;
}
public String formatDate(Date date) {
if(date == null || date.getTime() == 0) {
return "";
}
DateTime now = DateTime.now();
DateTime toFormat = new DateTime(date);
//same day
if(now.getYear() == toFormat.getYear() && now.getDayOfYear() == toFormat.getDayOfYear()) {
int passedHours = Hours.hoursBetween(toFormat, now).getHours();
if(passedHours == 0) {
int passedMinutes = Minutes.minutesBetween(toFormat, now).getMinutes();
//within 5 minutes, just display "just now"
if(passedMinutes <= 5) {
return resourceProvider.getString(R.string.dateDescription_just_now);
//within same hour display something like "10 minutes ago"
} else {
String formatString = resourceProvider.getString(R.string.dateDescription_minutes_ago);
return String.format(formatString, passedMinutes);
}
} else {
//larger periods: display time
return SimpleDateFormat.getTimeInstance(SimpleDateFormat.SHORT, resourceProvider.getLocale()).format(date);
}
//other day
} else {
DateFormat format = SimpleDateFormat.getDateInstance(SimpleDateFormat.SHORT, resourceProvider.getLocale());
return format.format(date);
}
}
}
|
package net.firekesti.pinnumberpicker.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import net.firekesti.pinnumberpicker.OnFinalNumberDoneListener;
import net.firekesti.pinnumberpicker.PinNumberPicker;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PinNumberPicker.loadResources(this);
final PinNumberPicker numberPicker1 = (PinNumberPicker) findViewById(R.id.picker1);
final PinNumberPicker numberPicker2 = (PinNumberPicker) findViewById(R.id.picker2);
final PinNumberPicker numberPicker3 = (PinNumberPicker) findViewById(R.id.picker3);
final PinNumberPicker numberPicker4 = (PinNumberPicker) findViewById(R.id.picker4);
/**
* To remove the arrows from the layout, comment out this block. Then, in the sample app's
* dimens.xml, comment out the dimen that sets the height to "pin_number_picker_height_with_arrows"
*/
numberPicker1.setArrowsEnabled(true);
numberPicker2.setArrowsEnabled(true);
numberPicker3.setArrowsEnabled(true);
numberPicker4.setArrowsEnabled(true);
numberPicker1.setValueRange(0, 9);
numberPicker1.setNextNumberPicker(numberPicker2);
numberPicker2.setAllowPlaceholder(true);
numberPicker2.setValueRange(0, 9);
numberPicker2.setNextNumberPicker(numberPicker3);
numberPicker3.setValueRange(0, 9);
numberPicker3.setNextNumberPicker(numberPicker4);
numberPicker4.setValueRange(-1, 9);
numberPicker4.setAllowPlaceholder(true);
numberPicker4.setPlaceholderCharacter("*");
numberPicker4.setOnFinalNumberDoneListener(new OnFinalNumberDoneListener() {
@Override
public void onDone() {
String lastDigit = Integer.toString(numberPicker4.getValue());
if (numberPicker4.getValue() == -1) {
lastDigit = "";
}
String pin = "" + numberPicker1.getValue() + numberPicker2.getValue() +
numberPicker3.getValue() + lastDigit;
Toast.makeText(MainActivity.this, "PIN is " + pin, Toast.LENGTH_SHORT).show();
}
});
}
}
|
package uk.co.traintrackapp.traintrack.model;
import org.joda.time.DateTime;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.Serializable;
import uk.co.traintrackapp.traintrack.R;
import uk.co.traintrackapp.traintrack.utils.Utils;
public class CallingPoint implements Serializable {
public static final int START = R.drawable.start;
public static final int STOP = R.drawable.stop;
public static final int END = R.drawable.end;
public static final int PASS = R.drawable.pass;
private Station station;
private Tiploc tiploc;
private DateTime scheduledTimeArrival;
private DateTime estimatedTimeArrival;
private DateTime actualTimeArrival;
private DateTime scheduledTimeDeparture;
private DateTime estimatedTimeDeparture;
private DateTime actualTimeDeparture;
private boolean cancelled;
private boolean passingPoint;
private boolean noReport;
private String platform;
private int icon;
public CallingPoint() {
this.station = new Station();
this.tiploc = new Tiploc();
this.scheduledTimeArrival = null;
this.estimatedTimeArrival = null;
this.actualTimeArrival = null;
this.scheduledTimeDeparture = null;
this.estimatedTimeDeparture = null;
this.actualTimeDeparture = null;
this.cancelled = false;
this.passingPoint = false;
this.noReport = false;
this.platform = "";
}
public CallingPoint(JSONObject json) {
this();
try {
if (!json.isNull("station")) {
this.station = new Station(json.getJSONObject("station"));
}
if (!json.isNull("tiploc")) {
this.tiploc = new Tiploc(json.getJSONObject("tiploc"));
}
if (!json.isNull("sta")) {
String sta = json.getString("sta");
this.scheduledTimeArrival = Utils.getDateTimeFromString(sta);
}
if (!json.isNull("eta")) {
String eta = json.getString("eta");
this.estimatedTimeArrival = Utils.getDateTimeFromString(eta);
}
if (!json.isNull("ata")) {
String ata = json.getString("ata");
this.actualTimeArrival = Utils.getDateTimeFromString(ata);
}
if (!json.isNull("std")) {
String std = json.getString("std");
this.scheduledTimeDeparture = Utils.getDateTimeFromString(std);
}
if (!json.isNull("etd")) {
String etd = json.getString("etd");
this.estimatedTimeDeparture = Utils.getDateTimeFromString(etd);
}
if (!json.isNull("atd")) {
String atd = json.getString("atd");
this.actualTimeDeparture = Utils.getDateTimeFromString(atd);
}
if (json.has("cancelled")) {
this.cancelled = json.getBoolean("cancelled");
}
if (json.has("pass")) {
this.passingPoint = json.getBoolean("pass");
}
if (json.has("no_report")) {
this.noReport = json.getBoolean("no_report");
}
if (!json.isNull("platform")) {
this.platform = json.getString("platform");
}
} catch (JSONException e) {
Utils.log("Calling Point: " + e.getMessage());
}
}
public void setStation(Station station) {
this.station = station;
}
public Station getStation() {
return station;
}
public Tiploc getTiploc() {
return tiploc;
}
public void setTiploc(Tiploc tiploc) {
this.tiploc = tiploc;
}
public DateTime getScheduledTimeArrival() {
return scheduledTimeArrival;
}
public void setScheduledTimeArrival(DateTime scheduledTimeArrival) {
this.scheduledTimeArrival = scheduledTimeArrival;
}
public DateTime getEstimatedTimeArrival() {
return estimatedTimeArrival;
}
public void setEstimatedTimeArrival(DateTime estimatedTimeArrival) {
this.estimatedTimeArrival = estimatedTimeArrival;
}
public DateTime getActualTimeArrival() {
return actualTimeArrival;
}
public void setActualTimeArrival(DateTime actualTimeArrival) {
this.actualTimeArrival = actualTimeArrival;
}
public DateTime getScheduledTimeDeparture() {
return scheduledTimeDeparture;
}
public void setScheduledTimeDeparture(DateTime scheduledTimeDeparture) {
this.scheduledTimeDeparture = scheduledTimeDeparture;
}
public DateTime getEstimatedTimeDeparture() {
return estimatedTimeDeparture;
}
public void setEstimatedTimeDeparture(DateTime estimatedTimeDeparture) {
this.estimatedTimeDeparture = estimatedTimeDeparture;
}
public DateTime getActualTimeDeparture() {
return actualTimeDeparture;
}
public void setActualTimeDeparture(DateTime actualTimeDeparture) {
this.actualTimeDeparture = actualTimeDeparture;
}
public boolean isCancelled() {
return cancelled;
}
public void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
public boolean isPassingPoint() {
return passingPoint;
}
public void setPassingPoint(boolean passingPoint) {
this.passingPoint = passingPoint;
}
public boolean isNoReport() {
return noReport;
}
public void setNoReport(boolean noReport) {
this.noReport = noReport;
}
public String getPlatform() {
return platform;
}
public void setPlatform(String platform) {
this.platform = platform;
}
public void setIcon(int icon) {
this.icon = icon;
}
public int getIcon() {
return icon;
}
public String toString() {
return getScheduledTime() + " " + getName() + " " + getTime() + "\n";
}
public String getName() {
if (!getStation().getName().equals(Station.DEFAULT_NAME)) {
return getStation().toString();
} else if (!getTiploc().getName().equals(Tiploc.DEFAULT_NAME)) {
return getTiploc().toString();
} else {
return Station.DEFAULT_NAME;
}
}
public boolean hasArrived() {
return getActualTimeArrival() != null;
}
public boolean isOnTime() {
if (getEstimatedTimeDeparture() != null) {
return getEstimatedTimeDeparture().isAfter(getScheduledTimeDeparture());
} else if (getEstimatedTimeArrival() != null) {
return getEstimatedTimeArrival().isAfter(getScheduledTimeArrival());
}
else {
return true;
}
}
public DateTime getScheduledTime() {
if (getScheduledTimeDeparture() != null) {
return getScheduledTimeDeparture();
} else {
return getScheduledTimeArrival();
}
}
public DateTime getTime() {
if (getActualTimeDeparture() != null) {
return getActualTimeDeparture();
} else if (getEstimatedTimeDeparture() != null) {
return getEstimatedTimeDeparture();
} else {
return getScheduledTime();
}
}
}
|
package org.ccnx.ccn.protocol;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.ccnx.ccn.impl.support.DataUtils;
/**
* CCN has a time representation for versions and signing times that
* is quantized at a granularity of 2^-12 seconds (approximately 1/4 msec).
* Because it does not quantize time evenly on millisecond boundaries,
* this can lead to confusion -- t = System.currentTimeMillis(), when
* used to set a version v, for example, then ends up with v != t as
* v is quantized and t isn't. Simply providing quantization utility
* routines to help developers turned out to be error-prone. So we
* are moving all uses of time in CCN to pre-quantized CCNTime objects,
* which encapsulates CCN time quantization (which could change),
* and gives developers ways to deal with it without having to think
* about it.
*
* CCNTime, all though it implements methods like getNanos, only
* represents time with a granularity equal to the underlying
* CCN wire format -- i.e. ~.25 msec.
*/
public class CCNTime extends Timestamp {
private static final long serialVersionUID = -1537142893653443100L;
private byte [] _binarytime = null;
/**
* This is the highest nanos value that doesn't quantize to over the ns limit for Timestamp of 999999999.
*/
public static final int NANOS_MAX = 999877929;
/**
* Create a CCNTime.
* @param msec time in msec
*/
public CCNTime(long msec) {
this((msec/1000) * 1000, (msec % 1000) * 1000000L);
}
/**
* Create a CCNTime
* @param timestamp source timestamp to initialize from, some precision will be lost
*/
public CCNTime(Timestamp timestamp) {
this(timestamp.getTime(), timestamp.getNanos());
}
/**
* Create a CCNTime
* @param time source Date to initialize from, some precision will be lost
* as CCNTime does not round to unitary milliseconds
*/
public CCNTime(Date time) {
this(time.getTime());
}
/**
* Create a CCNTime from its binary encoding
* @param binaryTime12 the binary representation of a CCNTime
*/
public CCNTime(byte [] binaryTime12) {
this(DataUtils.byteArrayToUnsignedLong(binaryTime12), true);
if ((null == binaryTime12) || (binaryTime12.length == 0)) {
throw new IllegalArgumentException("Invalid binary time!");
} else if (binaryTime12.length > 6) {
throw new IllegalArgumentException("Time unacceptably far in the future, can't decode: " + DataUtils.printHexBytes(binaryTime12));
}
}
/**
* Creates a CCNTime initialized to the current time.
*/
public CCNTime() {
this(System.currentTimeMillis());
}
/**
* Creates a CCNTime from a specification of msec and nanos, to ease implementing
* compatibility with Timestamp and Date. Note that there is redundant data here --
* the last 3 significant digits of msec are also represented as the top 3 of nanos.
* We take the version in the nanos. This is derived from Java's slightly odd Timestamp handling.
* @param msec milliseconds
* @param nanos nanoseconds
*/
protected CCNTime(long msec, long nanos) {
this(toBinaryTimeAsLong(msec, nanos), true);
}
/**
* Creates a CCNTime from the internal long representation of the quantized time.
* Equivalent to setFromBinaryTimeAsLong.
* @param binaryTimeAsLong the time in our internal units
* @param unused a marker parameter to separate this from another constructor
*/
protected CCNTime(long binaryTimeAsLong, boolean unused) {
super((binaryTimeAsLong / 4096L) * 1000L);
super.setNanos((int)(((binaryTimeAsLong % 4096L) * 1000000000L) / 4096L));
}
/**
* Factory method to generate a CCNTime from our internal long time representation.
* Make this a static method to avoid confusion; should be little used
* @return
*/
public static CCNTime fromBinaryTimeAsLong(long binaryTimeAsLong) {
return new CCNTime(binaryTimeAsLong, true);
}
/**
* Generate the binary representation of a CCNTime
* @return the binary representation we use for encoding
*/
public byte [] toBinaryTime() {
if( null == _binarytime ) {
byte [] b = DataUtils.unsignedLongToByteArray(toBinaryTimeAsLong());
_binarytime = b;
}
return _binarytime;
}
/**
* Generate the internal long representation of a CCNTime, useful for comparisons
* and used internally
* @return the long representation of this time in our internal units
*/
public long toBinaryTimeAsLong() {
return toBinaryTimeAsLong(getTime(), getNanos());
}
/**
* Static method to convert from milliseconds and nanoseconds to our
* internal long representation.
* Assumes that nanos also contains the integral milliseconds for this
* time. Ignores msec component in msec.
* @param msec milliseconds
* @param nanos nanoseconds
* @return
*/
public static long toBinaryTimeAsLong(long msec, long nanos) {
long timeVal = (msec / 1000) * 4096L + (nanos * 4096L + 500000000L) / 1000000000L;
return timeVal;
}
protected void setFromBinaryTimeAsLong(long binaryTimeAsLong) {
_binarytime = null;
super.setTime((binaryTimeAsLong / 4096L) * 1000L);
super.setNanos((int)(((binaryTimeAsLong % 4096L) * 1000000000L) / 4096L));
}
@Override
public void setTime(long msec) {
_binarytime = null;
long binaryTimeAsLong = toBinaryTimeAsLong((msec/1000) * 1000, (msec % 1000) * 1000000L);
super.setTime((binaryTimeAsLong / 4096L) * 1000L);
super.setNanos((int)(((binaryTimeAsLong % 4096L) * 1000000000L) / 4096L));
}
@Override
public void setNanos(int nanos) {
_binarytime = null;
int quantizedNanos = (int)(((((nanos * 4096L + 500000000L) / 1000000000L)) * 1000000000L) / 4096L);
if ((quantizedNanos < 0) || (quantizedNanos > 999999999)) {
System.out.println("Quantizing nanos " + nanos + " resulted in out of range value " + quantizedNanos + "!");
}
super.setNanos(quantizedNanos);
}
/**
* Note: you have to use a relatively high value of nanos before you get across a quantization
* unit and have an impact. Our units are 2^-12 seconds, or ~250 msec. So 250000 nanos.
* @param nanos
*/
public void addNanos(int nanos) {
_binarytime = null;
setNanos(nanos + getNanos());
}
/**
* A helper method to increment to avoid collisions. Add a number
* of CCNx quantized time units to the time. Synchronize if modifications can
* be performed from multiple threads.
*/
public void increment(int timeUnits) {
_binarytime = null;
long binaryTimeAsLong = toBinaryTimeAsLong();
binaryTimeAsLong += timeUnits;
setFromBinaryTimeAsLong(binaryTimeAsLong);
}
/**
* We handle all comparison functions by quantizing the thing
* we are being compared to, then comparing. The only thing
* this won't catch is if a normal Timestamp or Date's comparison
* method is called with a CCNTime as an argument. This is a
* small risk, and worth it given the convenience of subclassing
* Timestamp and using it for most functionality.
*/
@Override
public boolean equals(Timestamp ts) {
return super.equals(new CCNTime(ts));
}
@Override
public int compareTo(Date o) {
return super.compareTo(new CCNTime(o));
}
@Override
public int compareTo(Timestamp ts) {
return super.compareTo(new CCNTime(ts));
}
@Override
public boolean before(Timestamp ts) {
return super.before(new CCNTime(ts));
}
@Override
public boolean after(Timestamp ts) {
return super.after(new CCNTime(ts));
}
@Override
public boolean before(Date when) {
return super.before(new CCNTime(when));
}
@Override
public boolean after(Date when) {
return super.after(new CCNTime(when));
}
/**
* Create a CCNTime initialized to the current date/time.
* @return the new CCNTime
*/
public static CCNTime now() {
return new CCNTime();
}
/**
* Generate a string representation of a CCNTime containing only date and HH:MM:SS,
* not milliseconds or nanoseconds.
*/
public String toShortString() {
// use . instead of : as URI printer will make it look nicer in the logs
SimpleDateFormat df = new SimpleDateFormat("yy-MM-dd-HH.mm.ss");
return df.format(this);
}
}
|
package org.bridje.vfs;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;
import org.bridje.ioc.Ioc;
public class VFile
{
private static VfsService VFS;
private static VfsService getVfs()
{
if(VFS == null)
{
VFS = Ioc.context().find(VfsService.class);
}
return VFS;
}
private final Path path;
public VFile(Path path)
{
this.path = path;
}
public VFile(String path)
{
this.path = new Path(path);
}
public String getName()
{
return path.getName();
}
public Path getPath()
{
return path;
}
public VFile getParent()
{
if(path.isRoot()) return null;
return new VFile(path.getParent());
}
public boolean isDirectory()
{
return getVfs().isDirectory(path);
}
public boolean exists()
{
return getVfs().exists(path);
}
public boolean createNewFile()
{
return getVfs().createNewFile(path);
}
public boolean delete()
{
return getVfs().delete(path);
}
public boolean mkdir()
{
return getVfs().mkdir(path);
}
public boolean isFile()
{
return getVfs().isFile(path);
}
public boolean canWrite()
{
return getVfs().canWrite(path);
}
public boolean canRead()
{
return getVfs().canRead(path);
}
public void mount(VfsSource source) throws FileNotFoundException
{
getVfs().mount(path, source);
}
public String[] list()
{
return getVfs().list(path);
}
public VFile[] listFiles()
{
String[] list = getVfs().list(path);
VFile[] result = new VFile[list.length];
for (int i = 0; i < list.length; i++)
{
String name = list[i];
result[i] = new VFile(path.join(name));
}
return result;
}
InputStream openForRead()
{
return getVfs().openForRead(path);
}
OutputStream openForWrite()
{
return getVfs().openForWrite(path);
}
public VFile[] search(GlobExpr globExpr)
{
return getVfs().search(globExpr, path);
}
public String getMimeType()
{
String ext = path.getExtension();
if(ext == null || ext.trim().isEmpty()) return null;
return getVfs().getMimeType(ext);
}
@Override
public String toString()
{
return path.toString();
}
@Override
public int hashCode()
{
return this.path.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null || getClass() != obj.getClass())
{
return false;
}
final VFile other = (VFile) obj;
return Objects.equals(this.path, other.path);
}
}
|
package jlibs.xml.sax;
import static jlibs.xml.sax.SAXFeatures.NAMESPACES;
import static jlibs.xml.sax.SAXFeatures.NAMESPACE_PREFIXES;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import java.util.HashSet;
import java.util.Set;
/**
* Base class for XMLReader implementation
*
* @author Santhosh Kumar T
*/
public abstract class AbstractXMLReader extends BaseXMLReader{
protected AbstractXMLReader(){
supportedFeatures.add(SAXFeatures.NAMESPACES);
}
protected final Set<String> supportedFeatures = new HashSet<String>();
private final Set<String> features = new HashSet<String>();
protected boolean nsFeature;
protected boolean nsPrefixesFeature;
@Override
public void setFeature(String name, boolean value) throws SAXNotRecognizedException{
if(supportedFeatures.contains(name)){
if(value)
features.add(name);
else
features.remove(name);
if(NAMESPACES.equals(name))
nsFeature = value;
else if(NAMESPACE_PREFIXES.equals(name))
nsPrefixesFeature = value;
}else
throw new SAXNotRecognizedException(name);
}
@Override
public boolean getFeature(String name) throws SAXNotRecognizedException{
if(supportedFeatures.contains(name))
return features.contains(name);
else
throw new SAXNotRecognizedException(name);
}
@Override
public void setProperty(String name, Object value) throws SAXNotRecognizedException, SAXNotSupportedException{
if(!_setProperty(name, value))
throw new SAXNotRecognizedException(name);
}
@Override
public Object getProperty(String name) throws SAXNotRecognizedException{
Object value = _getProperty(name);
if(value!=null)
return value;
else
throw new SAXNotRecognizedException(name);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.